generate.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  1. <?php
  2. /**
  3. * 从 api-v13 的路由与控制器源码生成 OpenAPI 规格。
  4. *
  5. * 用法:
  6. * php openapi/scripts/generate.php
  7. *
  8. * 产物:
  9. * openapi/public/assets/protocol/main.yaml 入口,按 path $ref 到下面的文件
  10. * openapi/public/assets/protocol/resources/auto/… 每个 path 一个文件(自动生成,勿手改)
  11. *
  12. * 手写补充放在 openapi/public/assets/protocol/overrides/<同名路径>.yaml,
  13. * 生成时会深度合并覆盖自动结果,因此重跑不会丢失人工撰写的描述与示例。
  14. */
  15. declare(strict_types=1);
  16. use PhpParser\Node;
  17. use PhpParser\NodeFinder;
  18. use PhpParser\ParserFactory;
  19. use Symfony\Component\Yaml\Yaml;
  20. $root = dirname(__DIR__, 2);
  21. $api = $root.'/api-v13';
  22. require $api.'/vendor/autoload.php';
  23. $protocol = dirname(__DIR__).'/public/assets/protocol';
  24. $autoDir = $protocol.'/resources/auto';
  25. $overrideDir = $protocol.'/overrides';
  26. $parser = (new ParserFactory)->createForNewestSupportedVersion();
  27. $finder = new NodeFinder;
  28. /* ---------------------------------------------------------------- 路由 */
  29. exec('cd '.escapeshellarg($api).' && php artisan route:list --json 2>/dev/null', $out, $code);
  30. $routes = json_decode(implode('', $out), true);
  31. if (! is_array($routes)) {
  32. fwrite(STDERR, "无法读取 php artisan route:list --json\n");
  33. exit(1);
  34. }
  35. /** 解析控制器方法,结果按 class::method 缓存 */
  36. $methodCache = [];
  37. function parseController(string $class, string $method): array
  38. {
  39. global $api, $parser, $finder, $methodCache;
  40. $key = $class.'::'.$method;
  41. if (isset($methodCache[$key])) {
  42. return $methodCache[$key];
  43. }
  44. $empty = ['summary' => null, 'description' => null, 'params' => [], 'validate' => [], 'resource' => null, 'tags' => ['params' => [], 'deprecated' => false]];
  45. $file = $api.'/'.str_replace(['App\\', '\\'], ['app/', '/'], $class).'.php';
  46. if (! is_file($file)) {
  47. return $methodCache[$key] = $empty;
  48. }
  49. $ast = $parser->parse(file_get_contents($file));
  50. if (! $ast) {
  51. return $methodCache[$key] = $empty;
  52. }
  53. $node = null;
  54. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  55. if ($m->name->toString() === $method) {
  56. $node = $m;
  57. break;
  58. }
  59. }
  60. if (! $node) {
  61. return $methodCache[$key] = $empty;
  62. }
  63. $info = $empty;
  64. // 文档注释首行作为 summary,其余作为 description;
  65. // @queryParam / @bodyParam / @urlParam / @deprecated 作为结构化补充
  66. if ($doc = $node->getDocComment()) {
  67. $lines = [];
  68. $tagLines = [];
  69. foreach (explode("\n", $doc->getText()) as $line) {
  70. $line = trim(preg_replace('#^\s*(/\*\*|\*/|\*)\s?#u', '', $line));
  71. if ($line === '') {
  72. continue;
  73. }
  74. if (str_starts_with($line, '@')) {
  75. $tagLines[] = $line;
  76. continue;
  77. }
  78. // 上一行是带标签的参数说明时,缩进的续行并入该参数的描述
  79. if ($tagLines && preg_match('/^@(queryParam|bodyParam|urlParam)\b/', end($tagLines))) {
  80. $tagLines[count($tagLines) - 1] .= ' '.$line;
  81. continue;
  82. }
  83. $lines[] = $line;
  84. }
  85. $info['tags'] = parseDocTags($tagLines);
  86. // Laravel 脚手架留下的英文样板不如按资源名生成的摘要有用
  87. $stubs = [
  88. 'Display a listing of the resource.',
  89. 'Display the specified resource.',
  90. 'Store a newly created resource in storage.',
  91. 'Update the specified resource in storage.',
  92. 'Remove the specified resource from storage.',
  93. 'Show the form for creating a new resource.',
  94. 'Show the form for editing the specified resource.',
  95. ];
  96. $lines = array_values(array_filter($lines, fn ($l) => ! in_array($l, $stubs, true)));
  97. if ($lines) {
  98. $info['summary'] = array_shift($lines);
  99. $info['description'] = $lines ? implode("\n", $lines) : null;
  100. }
  101. }
  102. // $request->input('x', default) / query / has / filled / boolean / integer / string
  103. $readers = ['input', 'query', 'has', 'filled', 'boolean', 'integer', 'string', 'get', 'post'];
  104. foreach ($finder->findInstanceOf($node, Node\Expr\MethodCall::class) as $call) {
  105. if (! $call->name instanceof Node\Identifier) {
  106. continue;
  107. }
  108. $name = $call->name->toString();
  109. if (! in_array($name, $readers, true) || ! $call->args) {
  110. continue;
  111. }
  112. if (! ($call->var instanceof Node\Expr\Variable && $call->var->name === 'request')) {
  113. continue;
  114. }
  115. $arg = $call->args[0]->value ?? null;
  116. if (! $arg instanceof Node\Scalar\String_) {
  117. continue;
  118. }
  119. $param = $arg->value;
  120. $default = null;
  121. if (isset($call->args[1]) && $call->args[1]->value instanceof Node\Scalar\String_) {
  122. $default = $call->args[1]->value->value;
  123. }
  124. $type = match ($name) {
  125. 'boolean' => 'boolean',
  126. 'integer' => 'integer',
  127. default => 'string',
  128. };
  129. $prev = $info['params'][$param] ?? null;
  130. $info['params'][$param] = [
  131. 'type' => $prev['type'] ?? $type,
  132. 'default' => $prev['default'] ?? $default,
  133. ];
  134. }
  135. // switch ($request->input('x')) { case 'a': … } → 枚举值
  136. foreach ($finder->findInstanceOf($node, Node\Stmt\Switch_::class) as $switch) {
  137. $cond = $switch->cond;
  138. if (! $cond instanceof Node\Expr\MethodCall || ! $cond->name instanceof Node\Identifier) {
  139. continue;
  140. }
  141. if (! in_array($cond->name->toString(), ['input', 'query', 'get'], true)) {
  142. continue;
  143. }
  144. $arg = $cond->args[0]->value ?? null;
  145. if (! $arg instanceof Node\Scalar\String_ || ! isset($info['params'][$arg->value])) {
  146. continue;
  147. }
  148. $enum = [];
  149. foreach ($switch->cases as $case) {
  150. if ($case->cond instanceof Node\Scalar\String_) {
  151. $enum[] = $case->cond->value;
  152. }
  153. }
  154. if ($enum) {
  155. $info['params'][$arg->value]['enum'] = array_values(array_unique($enum));
  156. }
  157. }
  158. // $request->validate([...]) / Validator::make($request->all(), [...])
  159. foreach ($finder->findInstanceOf($node, Node\Expr\MethodCall::class) as $call) {
  160. if (! $call->name instanceof Node\Identifier || $call->name->toString() !== 'validate') {
  161. continue;
  162. }
  163. $arg = $call->args[0]->value ?? null;
  164. if ($arg instanceof Node\Expr\Array_) {
  165. $info['validate'] += rulesFromArray($arg);
  166. }
  167. }
  168. foreach ($finder->findInstanceOf($node, Node\Expr\StaticCall::class) as $call) {
  169. if (! $call->name instanceof Node\Identifier || $call->name->toString() !== 'make') {
  170. continue;
  171. }
  172. $arg = $call->args[1]->value ?? null;
  173. if ($arg instanceof Node\Expr\Array_) {
  174. $info['validate'] += rulesFromArray($arg);
  175. }
  176. }
  177. // 返回的 Resource 类
  178. foreach ($finder->findInstanceOf($node, Node\Expr\StaticCall::class) as $call) {
  179. $cls = $call->class instanceof Node\Name ? $call->class->toString() : null;
  180. if ($cls && str_ends_with($cls, 'Resource')) {
  181. $info['resource'] = $cls;
  182. break;
  183. }
  184. }
  185. if (! $info['resource']) {
  186. foreach ($finder->findInstanceOf($node, Node\Expr\New_::class) as $new) {
  187. $cls = $new->class instanceof Node\Name ? $new->class->toString() : null;
  188. if ($cls && str_ends_with($cls, 'Resource')) {
  189. $info['resource'] = $cls;
  190. break;
  191. }
  192. }
  193. }
  194. return $methodCache[$key] = $info;
  195. }
  196. /**
  197. * 解析文档注释里的结构化标签。
  198. *
  199. * 支持(Scribe 风格,位置固定):
  200. * @queryParam name type [required] 描述。可在描述里写 Enum: a,b,c / Default: x / Example: y
  201. * @bodyParam name type [required] 描述
  202. * @urlParam name type [required] 描述
  203. * @deprecated 弃用说明
  204. *
  205. * @return array{params: array<string, array>, deprecated: bool}
  206. */
  207. function parseDocTags(array $tagLines): array
  208. {
  209. $result = ['params' => [], 'deprecated' => false];
  210. foreach ($tagLines as $line) {
  211. if (str_starts_with($line, '@deprecated')) {
  212. $result['deprecated'] = true;
  213. continue;
  214. }
  215. if (! preg_match('/^@(queryParam|bodyParam|urlParam)\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
  216. continue;
  217. }
  218. [, $tag, $name, $type, $rest] = $m;
  219. $rest = trim($rest);
  220. $required = false;
  221. if (preg_match('/^required\b\.?\s*/u', $rest)) {
  222. $required = true;
  223. $rest = trim(preg_replace('/^required\b\.?\s*/u', '', $rest));
  224. }
  225. $entry = [
  226. 'in' => match ($tag) {
  227. 'queryParam' => 'query',
  228. 'urlParam' => 'path',
  229. default => 'body',
  230. },
  231. 'type' => normalizeType($type),
  232. 'required' => $required,
  233. ];
  234. if (preg_match('/\bEnum:\s*((?:(?!\bDefault:|\bExample:)[^.。\n])+)/u', $rest, $e)) {
  235. $entry['enum'] = array_values(array_filter(array_map('trim', explode(',', $e[1]))));
  236. $rest = trim(str_replace($e[0], '', $rest));
  237. }
  238. if (preg_match('/\bDefault:\s*((?:(?!\bExample:)[^.。\n])+)/u', $rest, $d)) {
  239. $entry['default'] = trim($d[1]);
  240. $rest = trim(str_replace($d[0], '', $rest));
  241. }
  242. if (preg_match('/\bExample:\s*([^\n]+)/u', $rest, $x)) {
  243. $entry['example'] = trim($x[1]);
  244. $rest = trim(str_replace($x[0], '', $rest));
  245. }
  246. // trim() 按字节裁剪会把末尾的中文字符截断成非法 UTF-8,这里用 /u 正则
  247. $entry['description'] = preg_replace('/^\s+|[\s.。]+$/u', '', $rest);
  248. $result['params'][$name] = $entry;
  249. }
  250. return $result;
  251. }
  252. function normalizeType(string $type): string
  253. {
  254. return match (strtolower($type)) {
  255. 'int', 'integer' => 'integer',
  256. 'float', 'double', 'number' => 'number',
  257. 'bool', 'boolean' => 'boolean',
  258. 'array', 'string[]', 'int[]' => 'array',
  259. 'object' => 'object',
  260. default => 'string',
  261. };
  262. }
  263. /** 验证规则数组 → [字段 => ['required'=>bool,'type'=>string,'enum'=>[]]] */
  264. function rulesFromArray(Node\Expr\Array_ $array): array
  265. {
  266. $rules = [];
  267. foreach ($array->items as $item) {
  268. if (! $item || ! $item->key instanceof Node\Scalar\String_) {
  269. continue;
  270. }
  271. $raw = null;
  272. if ($item->value instanceof Node\Scalar\String_) {
  273. $raw = $item->value->value;
  274. } elseif ($item->value instanceof Node\Expr\Array_) {
  275. $parts = [];
  276. foreach ($item->value->items as $r) {
  277. if ($r && $r->value instanceof Node\Scalar\String_) {
  278. $parts[] = $r->value->value;
  279. }
  280. }
  281. $raw = implode('|', $parts);
  282. }
  283. if ($raw === null) {
  284. continue;
  285. }
  286. $tokens = explode('|', $raw);
  287. $rule = ['required' => in_array('required', $tokens, true), 'type' => 'string', 'raw' => $raw];
  288. foreach ($tokens as $t) {
  289. if ($t === 'integer' || $t === 'numeric') {
  290. $rule['type'] = $t === 'integer' ? 'integer' : 'number';
  291. } elseif ($t === 'boolean') {
  292. $rule['type'] = 'boolean';
  293. } elseif ($t === 'array') {
  294. $rule['type'] = 'array';
  295. } elseif (str_starts_with($t, 'in:')) {
  296. $rule['enum'] = explode(',', substr($t, 3));
  297. }
  298. }
  299. $rules[$item->key->value] = $rule;
  300. }
  301. return $rules;
  302. }
  303. /** Resource 类的 toArray 键 → schema properties */
  304. function resourceSchema(?string $class): ?array
  305. {
  306. global $api, $parser, $finder;
  307. if (! $class) {
  308. return null;
  309. }
  310. $class = ltrim($class, '\\');
  311. $file = $api.'/'.str_replace(['App\\', '\\'], ['app/', '/'], $class).'.php';
  312. // 控制器里通常写的是短类名(new ChannelResource(...)),按全名拼不出路径,
  313. // 回落到 app/Http/Resources 下同名文件
  314. if (! is_file($file) && ! str_contains($class, '\\')) {
  315. $file = $api.'/app/Http/Resources/'.$class.'.php';
  316. }
  317. if (! is_file($file)) {
  318. return null;
  319. }
  320. $ast = $parser->parse(file_get_contents($file));
  321. if (! $ast) {
  322. return null;
  323. }
  324. $props = [];
  325. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  326. if ($m->name->toString() !== 'toArray') {
  327. continue;
  328. }
  329. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  330. foreach ($array->items as $item) {
  331. if ($item && $item->key instanceof Node\Scalar\String_) {
  332. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  333. }
  334. }
  335. }
  336. // $data['x'] = …
  337. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  338. $var = $assign->var;
  339. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  340. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  341. }
  342. }
  343. }
  344. return $props ?: null;
  345. }
  346. function guessType(string $field): string
  347. {
  348. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  349. return 'string';
  350. }
  351. if (preg_match('/^(is_|has_|can_)/', $field)) {
  352. return 'boolean';
  353. }
  354. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  355. return 'integer';
  356. }
  357. return 'string';
  358. }
  359. /* ------------------------------------------------------- 生成 operation */
  360. $listParams = Yaml::parseFile($protocol.'/resources/list_query.yaml');
  361. function buildOperation(array $route, string $httpMethod): array
  362. {
  363. global $listParams;
  364. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  365. $info = parseController($class, $method);
  366. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  367. $tag = tagOf($route['uri']);
  368. $op = [
  369. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  370. 'tags' => [$tag],
  371. 'operationId' => strtolower($httpMethod).'_'.preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  372. 'description' => trim(($info['description'] ?? '')."\n\n实现:`{$short}@{$method}`"),
  373. ];
  374. if (! empty($info['tags']['deprecated'])) {
  375. $op['deprecated'] = true;
  376. }
  377. $documented = $info['tags']['params'] ?? [];
  378. $params = [];
  379. // 路径参数
  380. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  381. foreach ($m[1] as $name) {
  382. $doc = $documented[$name] ?? null;
  383. $param = [
  384. 'name' => $name,
  385. 'in' => 'path',
  386. 'required' => true,
  387. 'schema' => ['type' => $doc['type'] ?? 'string'],
  388. ];
  389. if (! empty($doc['description'])) {
  390. $param['description'] = $doc['description'];
  391. }
  392. if (! empty($doc['enum'])) {
  393. $param['schema']['enum'] = $doc['enum'];
  394. }
  395. if (isset($doc['example'])) {
  396. $param['example'] = $doc['example'];
  397. }
  398. $params[] = $param;
  399. }
  400. }
  401. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  402. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  403. $names = array_keys($info['params']);
  404. foreach ($documented as $name => $doc) {
  405. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  406. $names[] = $name;
  407. }
  408. }
  409. foreach ($names as $name) {
  410. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  411. $doc = $documented[$name] ?? null;
  412. if (preg_match('/\{'.preg_quote($name, '/').'\??\}/', $route['uri'])) {
  413. continue;
  414. }
  415. // 文档注释把它标成 body 参数时,不再当查询参数输出
  416. if ($doc && $doc['in'] !== 'query') {
  417. continue;
  418. }
  419. if (! $isRead && ! $doc) {
  420. continue;
  421. }
  422. if (! $isRead) {
  423. continue;
  424. }
  425. $schema = ['type' => $doc['type'] ?? $p['type']];
  426. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  427. if ($enum) {
  428. $schema['enum'] = $enum;
  429. }
  430. $default = $doc['default'] ?? $p['default'] ?? null;
  431. if ($default !== null) {
  432. $schema['default'] = $default;
  433. }
  434. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  435. if (! empty($doc['description'])) {
  436. $param['description'] = $doc['description'];
  437. }
  438. if (! empty($doc['required'])) {
  439. $param['required'] = true;
  440. }
  441. if (isset($doc['example'])) {
  442. $param['example'] = $doc['example'];
  443. }
  444. $params[] = $param;
  445. }
  446. if ($method === 'index' && $httpMethod === 'GET') {
  447. $known = array_column($params, 'name');
  448. foreach ($listParams as $lp) {
  449. if (! in_array($lp['name'], $known, true)) {
  450. $params[] = $lp;
  451. }
  452. }
  453. }
  454. if ($params) {
  455. $op['parameters'] = $params;
  456. }
  457. // 请求体
  458. if (! $isRead) {
  459. $props = [];
  460. $required = [];
  461. foreach ($info['validate'] as $field => $rule) {
  462. $schema = ['type' => $rule['type'], 'description' => '规则:'.$rule['raw']];
  463. if (! empty($rule['enum'])) {
  464. $schema['enum'] = $rule['enum'];
  465. }
  466. $props[$field] = $schema;
  467. if ($rule['required']) {
  468. $required[] = $field;
  469. }
  470. }
  471. foreach ($info['params'] as $name => $p) {
  472. if (isset($props[$name])) {
  473. continue;
  474. }
  475. $schema = ['type' => $p['type']];
  476. if (! empty($p['enum'])) {
  477. $schema['enum'] = $p['enum'];
  478. }
  479. if ($p['default'] !== null) {
  480. $schema['default'] = $p['default'];
  481. }
  482. $props[$name] = $schema;
  483. }
  484. // 文档注释里写明的字段最权威,覆盖推断结果
  485. foreach ($documented as $name => $doc) {
  486. if ($doc['in'] === 'path') {
  487. continue;
  488. }
  489. $schema = ['type' => $doc['type']];
  490. if (! empty($doc['description'])) {
  491. $schema['description'] = $doc['description'];
  492. }
  493. if (! empty($doc['enum'])) {
  494. $schema['enum'] = $doc['enum'];
  495. }
  496. if (isset($doc['default'])) {
  497. $schema['default'] = $doc['default'];
  498. }
  499. if (isset($doc['example'])) {
  500. $schema['example'] = $doc['example'];
  501. }
  502. $props[$name] = $schema;
  503. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  504. $required[] = $name;
  505. }
  506. }
  507. if ($props) {
  508. $body = ['type' => 'object', 'properties' => $props];
  509. if ($required) {
  510. $body['required'] = $required;
  511. }
  512. $op['requestBody'] = [
  513. 'required' => (bool) $required,
  514. 'content' => ['application/json' => ['schema' => $body]],
  515. ];
  516. }
  517. }
  518. // 响应
  519. $data = ['type' => 'object'];
  520. if ($props = resourceSchema($info['resource'])) {
  521. $data = ['type' => 'object', 'properties' => $props];
  522. }
  523. if ($method === 'index') {
  524. $data = [
  525. 'type' => 'object',
  526. 'properties' => [
  527. 'rows' => ['type' => 'array', 'items' => $data],
  528. 'count' => ['type' => 'integer'],
  529. ],
  530. ];
  531. }
  532. $op['responses'] = [
  533. '200' => [
  534. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  535. 'content' => ['application/json' => ['schema' => [
  536. 'type' => 'object',
  537. 'properties' => [
  538. 'ok' => ['type' => 'boolean'],
  539. 'message' => ['type' => 'string'],
  540. 'data' => $data,
  541. ],
  542. ]]],
  543. ],
  544. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  545. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  546. ];
  547. return $op;
  548. }
  549. function defaultSummary(string $method, string $uri): string
  550. {
  551. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  552. return match ($method) {
  553. 'index' => "列出 {$res}",
  554. 'show' => "获取单个 {$res}",
  555. 'store' => "新建 {$res}",
  556. 'update' => "更新 {$res}",
  557. 'destroy' => "删除 {$res}",
  558. default => "{$method} {$res}",
  559. };
  560. }
  561. function tagOf(string $uri): string
  562. {
  563. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  564. $first = explode('/', $path)[0];
  565. return $first === '' ? 'misc' : $first;
  566. }
  567. /* ----------------------------------------------------------- 遍历路由 */
  568. $paths = [];
  569. foreach ($routes as $route) {
  570. $uri = $route['uri'];
  571. if (! str_starts_with($uri, 'api/') || ! str_contains((string) $route['action'], '@')) {
  572. continue;
  573. }
  574. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  575. continue;
  576. }
  577. foreach (explode('|', $route['method']) as $httpMethod) {
  578. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  579. continue;
  580. }
  581. $openapiPath = '/'.preg_replace('#^api/#', '', $uri);
  582. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  583. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  584. }
  585. }
  586. ksort($paths);
  587. /* --------------------------------------------------------- 合并 override */
  588. function deepMerge(array $base, array $over): array
  589. {
  590. foreach ($over as $k => $v) {
  591. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! array_is_list($v))
  592. ? deepMerge($base[$k], $v)
  593. : $v;
  594. }
  595. return $base;
  596. }
  597. function pathSlug(string $path): string
  598. {
  599. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  600. }
  601. $overridden = 0;
  602. foreach ($paths as $path => $ops) {
  603. $file = $overrideDir.'/'.pathSlug($path).'.yaml';
  604. if (is_file($file)) {
  605. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  606. $overridden++;
  607. }
  608. }
  609. /* ------------------------------------------------------------- 写文件 */
  610. foreach (glob($autoDir.'/*.yaml') ?: [] as $stale) {
  611. unlink($stale);
  612. }
  613. @mkdir($autoDir, 0o755, true);
  614. @mkdir($overrideDir, 0o755, true);
  615. $refs = [];
  616. foreach ($paths as $path => $ops) {
  617. $name = pathSlug($path).'.yaml';
  618. file_put_contents(
  619. $autoDir.'/'.$name,
  620. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n".
  621. Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)
  622. );
  623. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  624. }
  625. $main = [
  626. 'openapi' => '3.0.3',
  627. 'info' => [
  628. 'title' => 'MINT API',
  629. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n".
  630. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n".
  631. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  632. 'version' => date('Y.n.j'),
  633. ],
  634. 'servers' => [
  635. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  636. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  637. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  638. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发'],
  639. ],
  640. 'components' => [
  641. 'securitySchemes' => [
  642. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  643. ],
  644. 'responses' => [
  645. 'Unauthorized' => [
  646. 'description' => '未登录或无权限',
  647. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  648. ],
  649. 'ValidationError' => [
  650. 'description' => '参数校验失败',
  651. 'content' => ['application/json' => ['schema' => [
  652. 'type' => 'object',
  653. 'properties' => [
  654. 'message' => ['type' => 'string'],
  655. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  656. ],
  657. ]]],
  658. ],
  659. ],
  660. 'schemas' => [
  661. 'Envelope' => [
  662. 'type' => 'object',
  663. 'properties' => [
  664. 'ok' => ['type' => 'boolean'],
  665. 'message' => ['type' => 'string'],
  666. 'data' => ['description' => '业务数据,形状随接口而定'],
  667. ],
  668. ],
  669. ],
  670. ],
  671. 'security' => [['bearerAuth' => []]],
  672. 'paths' => $refs,
  673. ];
  674. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  675. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  676. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  677. file_put_contents(
  678. $protocol.'/main.yaml',
  679. "# 由 openapi/scripts/generate.php 生成,请勿手改\n".$mainYaml
  680. );
  681. printf("生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  682. count($paths),
  683. array_sum(array_map('count', $paths)),
  684. $overridden
  685. );