generate.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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. $file = $api.'/'.str_replace(['App\\', '\\'], ['app/', '/'], ltrim($class, '\\')).'.php';
  311. if (! is_file($file)) {
  312. return null;
  313. }
  314. $ast = $parser->parse(file_get_contents($file));
  315. if (! $ast) {
  316. return null;
  317. }
  318. $props = [];
  319. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  320. if ($m->name->toString() !== 'toArray') {
  321. continue;
  322. }
  323. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  324. foreach ($array->items as $item) {
  325. if ($item && $item->key instanceof Node\Scalar\String_) {
  326. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  327. }
  328. }
  329. }
  330. // $data['x'] = …
  331. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  332. $var = $assign->var;
  333. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  334. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  335. }
  336. }
  337. }
  338. return $props ?: null;
  339. }
  340. function guessType(string $field): string
  341. {
  342. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  343. return 'string';
  344. }
  345. if (preg_match('/^(is_|has_|can_)/', $field)) {
  346. return 'boolean';
  347. }
  348. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  349. return 'integer';
  350. }
  351. return 'string';
  352. }
  353. /* ------------------------------------------------------- 生成 operation */
  354. $listParams = Yaml::parseFile($protocol.'/resources/list_query.yaml');
  355. function buildOperation(array $route, string $httpMethod): array
  356. {
  357. global $listParams;
  358. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  359. $info = parseController($class, $method);
  360. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  361. $tag = tagOf($route['uri']);
  362. $op = [
  363. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  364. 'tags' => [$tag],
  365. 'operationId' => strtolower($httpMethod).'_'.preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  366. 'description' => trim(($info['description'] ?? '')."\n\n实现:`{$short}@{$method}`"),
  367. ];
  368. if (! empty($info['tags']['deprecated'])) {
  369. $op['deprecated'] = true;
  370. }
  371. $documented = $info['tags']['params'] ?? [];
  372. $params = [];
  373. // 路径参数
  374. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  375. foreach ($m[1] as $name) {
  376. $doc = $documented[$name] ?? null;
  377. $param = [
  378. 'name' => $name,
  379. 'in' => 'path',
  380. 'required' => true,
  381. 'schema' => ['type' => $doc['type'] ?? 'string'],
  382. ];
  383. if (! empty($doc['description'])) {
  384. $param['description'] = $doc['description'];
  385. }
  386. if (! empty($doc['enum'])) {
  387. $param['schema']['enum'] = $doc['enum'];
  388. }
  389. if (isset($doc['example'])) {
  390. $param['example'] = $doc['example'];
  391. }
  392. $params[] = $param;
  393. }
  394. }
  395. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  396. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  397. $names = array_keys($info['params']);
  398. foreach ($documented as $name => $doc) {
  399. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  400. $names[] = $name;
  401. }
  402. }
  403. foreach ($names as $name) {
  404. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  405. $doc = $documented[$name] ?? null;
  406. if (preg_match('/\{'.preg_quote($name, '/').'\??\}/', $route['uri'])) {
  407. continue;
  408. }
  409. // 文档注释把它标成 body 参数时,不再当查询参数输出
  410. if ($doc && $doc['in'] !== 'query') {
  411. continue;
  412. }
  413. if (! $isRead && ! $doc) {
  414. continue;
  415. }
  416. if (! $isRead) {
  417. continue;
  418. }
  419. $schema = ['type' => $doc['type'] ?? $p['type']];
  420. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  421. if ($enum) {
  422. $schema['enum'] = $enum;
  423. }
  424. $default = $doc['default'] ?? $p['default'] ?? null;
  425. if ($default !== null) {
  426. $schema['default'] = $default;
  427. }
  428. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  429. if (! empty($doc['description'])) {
  430. $param['description'] = $doc['description'];
  431. }
  432. if (! empty($doc['required'])) {
  433. $param['required'] = true;
  434. }
  435. if (isset($doc['example'])) {
  436. $param['example'] = $doc['example'];
  437. }
  438. $params[] = $param;
  439. }
  440. if ($method === 'index' && $httpMethod === 'GET') {
  441. $known = array_column($params, 'name');
  442. foreach ($listParams as $lp) {
  443. if (! in_array($lp['name'], $known, true)) {
  444. $params[] = $lp;
  445. }
  446. }
  447. }
  448. if ($params) {
  449. $op['parameters'] = $params;
  450. }
  451. // 请求体
  452. if (! $isRead) {
  453. $props = [];
  454. $required = [];
  455. foreach ($info['validate'] as $field => $rule) {
  456. $schema = ['type' => $rule['type'], 'description' => '规则:'.$rule['raw']];
  457. if (! empty($rule['enum'])) {
  458. $schema['enum'] = $rule['enum'];
  459. }
  460. $props[$field] = $schema;
  461. if ($rule['required']) {
  462. $required[] = $field;
  463. }
  464. }
  465. foreach ($info['params'] as $name => $p) {
  466. if (isset($props[$name])) {
  467. continue;
  468. }
  469. $schema = ['type' => $p['type']];
  470. if (! empty($p['enum'])) {
  471. $schema['enum'] = $p['enum'];
  472. }
  473. if ($p['default'] !== null) {
  474. $schema['default'] = $p['default'];
  475. }
  476. $props[$name] = $schema;
  477. }
  478. // 文档注释里写明的字段最权威,覆盖推断结果
  479. foreach ($documented as $name => $doc) {
  480. if ($doc['in'] === 'path') {
  481. continue;
  482. }
  483. $schema = ['type' => $doc['type']];
  484. if (! empty($doc['description'])) {
  485. $schema['description'] = $doc['description'];
  486. }
  487. if (! empty($doc['enum'])) {
  488. $schema['enum'] = $doc['enum'];
  489. }
  490. if (isset($doc['default'])) {
  491. $schema['default'] = $doc['default'];
  492. }
  493. if (isset($doc['example'])) {
  494. $schema['example'] = $doc['example'];
  495. }
  496. $props[$name] = $schema;
  497. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  498. $required[] = $name;
  499. }
  500. }
  501. if ($props) {
  502. $body = ['type' => 'object', 'properties' => $props];
  503. if ($required) {
  504. $body['required'] = $required;
  505. }
  506. $op['requestBody'] = [
  507. 'required' => (bool) $required,
  508. 'content' => ['application/json' => ['schema' => $body]],
  509. ];
  510. }
  511. }
  512. // 响应
  513. $data = ['type' => 'object'];
  514. if ($props = resourceSchema($info['resource'])) {
  515. $data = ['type' => 'object', 'properties' => $props];
  516. }
  517. if ($method === 'index') {
  518. $data = [
  519. 'type' => 'object',
  520. 'properties' => [
  521. 'rows' => ['type' => 'array', 'items' => $data],
  522. 'count' => ['type' => 'integer'],
  523. ],
  524. ];
  525. }
  526. $op['responses'] = [
  527. '200' => [
  528. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  529. 'content' => ['application/json' => ['schema' => [
  530. 'type' => 'object',
  531. 'properties' => [
  532. 'ok' => ['type' => 'boolean'],
  533. 'message' => ['type' => 'string'],
  534. 'data' => $data,
  535. ],
  536. ]]],
  537. ],
  538. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  539. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  540. ];
  541. return $op;
  542. }
  543. function defaultSummary(string $method, string $uri): string
  544. {
  545. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  546. return match ($method) {
  547. 'index' => "列出 {$res}",
  548. 'show' => "获取单个 {$res}",
  549. 'store' => "新建 {$res}",
  550. 'update' => "更新 {$res}",
  551. 'destroy' => "删除 {$res}",
  552. default => "{$method} {$res}",
  553. };
  554. }
  555. function tagOf(string $uri): string
  556. {
  557. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  558. $first = explode('/', $path)[0];
  559. return $first === '' ? 'misc' : $first;
  560. }
  561. /* ----------------------------------------------------------- 遍历路由 */
  562. $paths = [];
  563. foreach ($routes as $route) {
  564. $uri = $route['uri'];
  565. if (! str_starts_with($uri, 'api/') || ! str_contains((string) $route['action'], '@')) {
  566. continue;
  567. }
  568. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  569. continue;
  570. }
  571. foreach (explode('|', $route['method']) as $httpMethod) {
  572. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  573. continue;
  574. }
  575. $openapiPath = '/'.preg_replace('#^api/#', '', $uri);
  576. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  577. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  578. }
  579. }
  580. ksort($paths);
  581. /* --------------------------------------------------------- 合并 override */
  582. function deepMerge(array $base, array $over): array
  583. {
  584. foreach ($over as $k => $v) {
  585. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! array_is_list($v))
  586. ? deepMerge($base[$k], $v)
  587. : $v;
  588. }
  589. return $base;
  590. }
  591. function pathSlug(string $path): string
  592. {
  593. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  594. }
  595. $overridden = 0;
  596. foreach ($paths as $path => $ops) {
  597. $file = $overrideDir.'/'.pathSlug($path).'.yaml';
  598. if (is_file($file)) {
  599. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  600. $overridden++;
  601. }
  602. }
  603. /* ------------------------------------------------------------- 写文件 */
  604. foreach (glob($autoDir.'/*.yaml') ?: [] as $stale) {
  605. unlink($stale);
  606. }
  607. @mkdir($autoDir, 0o755, true);
  608. @mkdir($overrideDir, 0o755, true);
  609. $refs = [];
  610. foreach ($paths as $path => $ops) {
  611. $name = pathSlug($path).'.yaml';
  612. file_put_contents(
  613. $autoDir.'/'.$name,
  614. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n".
  615. Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)
  616. );
  617. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  618. }
  619. $main = [
  620. 'openapi' => '3.0.3',
  621. 'info' => [
  622. 'title' => 'MINT API',
  623. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n".
  624. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n".
  625. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  626. 'version' => date('Y.n.j'),
  627. ],
  628. 'servers' => [
  629. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  630. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  631. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  632. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发'],
  633. ],
  634. 'components' => [
  635. 'securitySchemes' => [
  636. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  637. ],
  638. 'responses' => [
  639. 'Unauthorized' => [
  640. 'description' => '未登录或无权限',
  641. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  642. ],
  643. 'ValidationError' => [
  644. 'description' => '参数校验失败',
  645. 'content' => ['application/json' => ['schema' => [
  646. 'type' => 'object',
  647. 'properties' => [
  648. 'message' => ['type' => 'string'],
  649. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  650. ],
  651. ]]],
  652. ],
  653. ],
  654. 'schemas' => [
  655. 'Envelope' => [
  656. 'type' => 'object',
  657. 'properties' => [
  658. 'ok' => ['type' => 'boolean'],
  659. 'message' => ['type' => 'string'],
  660. 'data' => ['description' => '业务数据,形状随接口而定'],
  661. ],
  662. ],
  663. ],
  664. ],
  665. 'security' => [['bearerAuth' => []]],
  666. 'paths' => $refs,
  667. ];
  668. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  669. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  670. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  671. file_put_contents(
  672. $protocol.'/main.yaml',
  673. "# 由 openapi/scripts/generate.php 生成,请勿手改\n".$mainYaml
  674. );
  675. printf("生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  676. count($paths),
  677. array_sum(array_map('count', $paths)),
  678. $overridden
  679. );