generate.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927
  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. // 声明优先:toArray 上写了 @return array{...} 就用它,类型是真声明而非按字段名猜
  330. if ($doc = $m->getDocComment()) {
  331. if ($shape = parseArrayShape($doc->getText())) {
  332. return $shape;
  333. }
  334. }
  335. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  336. foreach ($array->items as $item) {
  337. if ($item && $item->key instanceof Node\Scalar\String_) {
  338. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  339. }
  340. }
  341. }
  342. // $data['x'] = …
  343. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  344. $var = $assign->var;
  345. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  346. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  347. }
  348. }
  349. }
  350. return $props ?: null;
  351. }
  352. /**
  353. * 解析 PHPDoc 里的 `@return array{uid: string, studio: array{...}|false, progress?: float}`。
  354. *
  355. * 支持嵌套 array{}、联合类型(取第一个具体类型,含 null/false 则标 nullable)、
  356. * `key?:` 表示该键只在部分口径下出现。解析不出形状时返回 null,调用方回落到按字段名猜。
  357. *
  358. * @return array<string, array>|null
  359. */
  360. function parseArrayShape(string $docText): ?array
  361. {
  362. if (! preg_match('/@return\s+array\s*\{/s', $docText, $m, PREG_OFFSET_CAPTURE)) {
  363. return null;
  364. }
  365. // 去掉每行开头的 * 再找花括号,避免注释前缀干扰
  366. $body = preg_replace('#^\s*\*\s?#m', '', $docText);
  367. if (! preg_match('/@return\s+array\s*\{(.*)/s', $body, $mm)) {
  368. return null;
  369. }
  370. $inner = extractBraced($mm[1]);
  371. return $inner === null ? null : shapeToProperties($inner);
  372. }
  373. /** 从 `{` 之后的文本里取出配平的内容 */
  374. function extractBraced(string $text): ?string
  375. {
  376. $depth = 1;
  377. $out = '';
  378. $len = strlen($text);
  379. for ($i = 0; $i < $len; $i++) {
  380. $ch = $text[$i];
  381. if ($ch === '{') {
  382. $depth++;
  383. } elseif ($ch === '}') {
  384. $depth--;
  385. if ($depth === 0) {
  386. return $out;
  387. }
  388. }
  389. $out .= $ch;
  390. }
  391. return null;
  392. }
  393. /** 按顶层逗号切分,忽略嵌套花括号与尖括号里的逗号 */
  394. function splitTopLevel(string $text): array
  395. {
  396. $parts = [];
  397. $buf = '';
  398. $depth = 0;
  399. $len = strlen($text);
  400. for ($i = 0; $i < $len; $i++) {
  401. $ch = $text[$i];
  402. if ($ch === '{' || $ch === '<') {
  403. $depth++;
  404. } elseif ($ch === '}' || $ch === '>') {
  405. $depth--;
  406. }
  407. if ($ch === ',' && $depth === 0) {
  408. $parts[] = $buf;
  409. $buf = '';
  410. continue;
  411. }
  412. $buf .= $ch;
  413. }
  414. if (trim($buf) !== '') {
  415. $parts[] = $buf;
  416. }
  417. return $parts;
  418. }
  419. /** array shape 的内容 → OpenAPI properties */
  420. function shapeToProperties(string $inner): array
  421. {
  422. $props = [];
  423. foreach (splitTopLevel($inner) as $part) {
  424. $part = trim($part);
  425. if ($part === '' || ! str_contains($part, ':')) {
  426. continue;
  427. }
  428. [$key, $type] = explode(':', $part, 2);
  429. $key = trim($key);
  430. $optional = str_ends_with($key, '?');
  431. $key = rtrim($key, '?');
  432. if ($key === '') {
  433. continue;
  434. }
  435. $schema = phpTypeToSchema(trim($type));
  436. if ($optional) {
  437. $schema['description'] = trim(($schema['description'] ?? '').' 仅在部分查询口径下返回。');
  438. }
  439. $props[$key] = $schema;
  440. }
  441. return $props;
  442. }
  443. /** PHPDoc 类型 → OpenAPI schema */
  444. function phpTypeToSchema(string $type): array
  445. {
  446. $type = trim($type);
  447. $nullable = false;
  448. if (str_starts_with($type, '?')) {
  449. $nullable = true;
  450. $type = substr($type, 1);
  451. }
  452. // 联合类型:null / false 视为可空,取第一个具体类型
  453. $members = splitTopLevel(str_replace('|', ',', preg_replace('/\|/', '|', $type)));
  454. if (count($members) > 1) {
  455. $concrete = [];
  456. foreach ($members as $mem) {
  457. $mem = trim($mem);
  458. if (in_array(strtolower($mem), ['null', 'false', 'true'], true)) {
  459. $nullable = true;
  460. continue;
  461. }
  462. $concrete[] = $mem;
  463. }
  464. $type = $concrete ? $concrete[0] : 'mixed';
  465. }
  466. $type = trim($type);
  467. // 嵌套 array{...}
  468. if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
  469. $innerText = extractBraced($m[1]);
  470. $schema = ['type' => 'object'];
  471. if ($innerText !== null && ($p = shapeToProperties($innerText))) {
  472. $schema['properties'] = $p;
  473. }
  474. if ($nullable) {
  475. $schema['nullable'] = true;
  476. }
  477. return $schema;
  478. }
  479. // 列表:array<T> / T[] / list<T>
  480. if (preg_match('/^(?:array|list)\s*<(.+)>$/s', $type, $m)) {
  481. $args = splitTopLevel($m[1]);
  482. $itemType = trim(end($args));
  483. $schema = ['type' => 'array', 'items' => phpTypeToSchema($itemType)];
  484. if ($nullable) {
  485. $schema['nullable'] = true;
  486. }
  487. return $schema;
  488. }
  489. if (str_ends_with($type, '[]')) {
  490. $schema = ['type' => 'array', 'items' => phpTypeToSchema(substr($type, 0, -2))];
  491. if ($nullable) {
  492. $schema['nullable'] = true;
  493. }
  494. return $schema;
  495. }
  496. $schema = match (strtolower($type)) {
  497. 'int', 'integer' => ['type' => 'integer'],
  498. 'float', 'double' => ['type' => 'number'],
  499. 'bool', 'boolean' => ['type' => 'boolean'],
  500. 'array' => ['type' => 'array', 'items' => ['type' => 'string']],
  501. 'object', 'mixed', '' => ['type' => 'object'],
  502. default => ['type' => 'string'],
  503. };
  504. if ($nullable) {
  505. $schema['nullable'] = true;
  506. }
  507. return $schema;
  508. }
  509. function guessType(string $field): string
  510. {
  511. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  512. return 'string';
  513. }
  514. if (preg_match('/^(is_|has_|can_)/', $field)) {
  515. return 'boolean';
  516. }
  517. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  518. return 'integer';
  519. }
  520. return 'string';
  521. }
  522. /* ------------------------------------------------------- 生成 operation */
  523. $listParams = Yaml::parseFile($protocol.'/resources/list_query.yaml');
  524. function buildOperation(array $route, string $httpMethod): array
  525. {
  526. global $listParams;
  527. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  528. $info = parseController($class, $method);
  529. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  530. $tag = tagOf($route['uri']);
  531. $op = [
  532. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  533. 'tags' => [$tag],
  534. 'operationId' => strtolower($httpMethod).'_'.preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  535. 'description' => trim(($info['description'] ?? '')."\n\n实现:`{$short}@{$method}`"),
  536. ];
  537. if (! empty($info['tags']['deprecated'])) {
  538. $op['deprecated'] = true;
  539. }
  540. $documented = $info['tags']['params'] ?? [];
  541. $params = [];
  542. // 路径参数
  543. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  544. foreach ($m[1] as $name) {
  545. $doc = $documented[$name] ?? null;
  546. $param = [
  547. 'name' => $name,
  548. 'in' => 'path',
  549. 'required' => true,
  550. 'schema' => ['type' => $doc['type'] ?? 'string'],
  551. ];
  552. if (! empty($doc['description'])) {
  553. $param['description'] = $doc['description'];
  554. }
  555. if (! empty($doc['enum'])) {
  556. $param['schema']['enum'] = $doc['enum'];
  557. }
  558. if (isset($doc['example'])) {
  559. $param['example'] = $doc['example'];
  560. }
  561. $params[] = $param;
  562. }
  563. }
  564. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  565. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  566. $names = array_keys($info['params']);
  567. foreach ($documented as $name => $doc) {
  568. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  569. $names[] = $name;
  570. }
  571. }
  572. foreach ($names as $name) {
  573. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  574. $doc = $documented[$name] ?? null;
  575. if (preg_match('/\{'.preg_quote($name, '/').'\??\}/', $route['uri'])) {
  576. continue;
  577. }
  578. // 文档注释把它标成 body 参数时,不再当查询参数输出
  579. if ($doc && $doc['in'] !== 'query') {
  580. continue;
  581. }
  582. if (! $isRead && ! $doc) {
  583. continue;
  584. }
  585. if (! $isRead) {
  586. continue;
  587. }
  588. $schema = ['type' => $doc['type'] ?? $p['type']];
  589. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  590. if ($enum) {
  591. $schema['enum'] = $enum;
  592. }
  593. $default = $doc['default'] ?? $p['default'] ?? null;
  594. if ($default !== null) {
  595. $schema['default'] = $default;
  596. }
  597. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  598. if (! empty($doc['description'])) {
  599. $param['description'] = $doc['description'];
  600. }
  601. if (! empty($doc['required'])) {
  602. $param['required'] = true;
  603. }
  604. if (isset($doc['example'])) {
  605. $param['example'] = $doc['example'];
  606. }
  607. $params[] = $param;
  608. }
  609. if ($method === 'index' && $httpMethod === 'GET') {
  610. $known = array_column($params, 'name');
  611. foreach ($listParams as $lp) {
  612. if (! in_array($lp['name'], $known, true)) {
  613. $params[] = $lp;
  614. }
  615. }
  616. }
  617. if ($params) {
  618. $op['parameters'] = $params;
  619. }
  620. // 请求体
  621. if (! $isRead) {
  622. $props = [];
  623. $required = [];
  624. foreach ($info['validate'] as $field => $rule) {
  625. $schema = ['type' => $rule['type'], 'description' => '规则:'.$rule['raw']];
  626. if (! empty($rule['enum'])) {
  627. $schema['enum'] = $rule['enum'];
  628. }
  629. $props[$field] = $schema;
  630. if ($rule['required']) {
  631. $required[] = $field;
  632. }
  633. }
  634. foreach ($info['params'] as $name => $p) {
  635. if (isset($props[$name])) {
  636. continue;
  637. }
  638. $schema = ['type' => $p['type']];
  639. if (! empty($p['enum'])) {
  640. $schema['enum'] = $p['enum'];
  641. }
  642. if ($p['default'] !== null) {
  643. $schema['default'] = $p['default'];
  644. }
  645. $props[$name] = $schema;
  646. }
  647. // 文档注释里写明的字段最权威,覆盖推断结果
  648. foreach ($documented as $name => $doc) {
  649. if ($doc['in'] === 'path') {
  650. continue;
  651. }
  652. $schema = ['type' => $doc['type']];
  653. if (! empty($doc['description'])) {
  654. $schema['description'] = $doc['description'];
  655. }
  656. if (! empty($doc['enum'])) {
  657. $schema['enum'] = $doc['enum'];
  658. }
  659. if (isset($doc['default'])) {
  660. $schema['default'] = $doc['default'];
  661. }
  662. if (isset($doc['example'])) {
  663. $schema['example'] = $doc['example'];
  664. }
  665. $props[$name] = $schema;
  666. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  667. $required[] = $name;
  668. }
  669. }
  670. if ($props) {
  671. $body = ['type' => 'object', 'properties' => $props];
  672. if ($required) {
  673. $body['required'] = $required;
  674. }
  675. $op['requestBody'] = [
  676. 'required' => (bool) $required,
  677. 'content' => ['application/json' => ['schema' => $body]],
  678. ];
  679. }
  680. }
  681. // 响应
  682. $data = ['type' => 'object'];
  683. if ($props = resourceSchema($info['resource'])) {
  684. $data = ['type' => 'object', 'properties' => $props];
  685. }
  686. if ($method === 'index') {
  687. $data = [
  688. 'type' => 'object',
  689. 'properties' => [
  690. 'rows' => ['type' => 'array', 'items' => $data],
  691. 'count' => ['type' => 'integer'],
  692. ],
  693. ];
  694. }
  695. $op['responses'] = [
  696. '200' => [
  697. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  698. 'content' => ['application/json' => ['schema' => [
  699. 'type' => 'object',
  700. 'properties' => [
  701. 'ok' => ['type' => 'boolean'],
  702. 'message' => ['type' => 'string'],
  703. 'data' => $data,
  704. ],
  705. ]]],
  706. ],
  707. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  708. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  709. ];
  710. return $op;
  711. }
  712. function defaultSummary(string $method, string $uri): string
  713. {
  714. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  715. return match ($method) {
  716. 'index' => "列出 {$res}",
  717. 'show' => "获取单个 {$res}",
  718. 'store' => "新建 {$res}",
  719. 'update' => "更新 {$res}",
  720. 'destroy' => "删除 {$res}",
  721. default => "{$method} {$res}",
  722. };
  723. }
  724. function tagOf(string $uri): string
  725. {
  726. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  727. $first = explode('/', $path)[0];
  728. return $first === '' ? 'misc' : $first;
  729. }
  730. /* ----------------------------------------------------------- 遍历路由 */
  731. $paths = [];
  732. foreach ($routes as $route) {
  733. $uri = $route['uri'];
  734. if (! str_starts_with($uri, 'api/') || ! str_contains((string) $route['action'], '@')) {
  735. continue;
  736. }
  737. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  738. continue;
  739. }
  740. foreach (explode('|', $route['method']) as $httpMethod) {
  741. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  742. continue;
  743. }
  744. $openapiPath = '/'.preg_replace('#^api/#', '', $uri);
  745. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  746. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  747. }
  748. }
  749. ksort($paths);
  750. /* --------------------------------------------------------- 合并 override */
  751. function deepMerge(array $base, array $over): array
  752. {
  753. foreach ($over as $k => $v) {
  754. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! array_is_list($v))
  755. ? deepMerge($base[$k], $v)
  756. : $v;
  757. }
  758. return $base;
  759. }
  760. function pathSlug(string $path): string
  761. {
  762. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  763. }
  764. $overridden = 0;
  765. foreach ($paths as $path => $ops) {
  766. $file = $overrideDir.'/'.pathSlug($path).'.yaml';
  767. if (is_file($file)) {
  768. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  769. $overridden++;
  770. }
  771. }
  772. /* ------------------------------------------------------------- 写文件 */
  773. foreach (glob($autoDir.'/*.yaml') ?: [] as $stale) {
  774. unlink($stale);
  775. }
  776. @mkdir($autoDir, 0o755, true);
  777. @mkdir($overrideDir, 0o755, true);
  778. $refs = [];
  779. foreach ($paths as $path => $ops) {
  780. $name = pathSlug($path).'.yaml';
  781. file_put_contents(
  782. $autoDir.'/'.$name,
  783. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n".
  784. Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)
  785. );
  786. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  787. }
  788. $main = [
  789. 'openapi' => '3.0.3',
  790. 'info' => [
  791. 'title' => 'MINT API',
  792. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n".
  793. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n".
  794. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  795. 'version' => date('Y.n.j'),
  796. ],
  797. // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
  798. 'servers' => [
  799. ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
  800. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
  801. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  802. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  803. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  804. ],
  805. 'components' => [
  806. 'securitySchemes' => [
  807. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  808. ],
  809. 'responses' => [
  810. 'Unauthorized' => [
  811. 'description' => '未登录或无权限',
  812. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  813. ],
  814. 'ValidationError' => [
  815. 'description' => '参数校验失败',
  816. 'content' => ['application/json' => ['schema' => [
  817. 'type' => 'object',
  818. 'properties' => [
  819. 'message' => ['type' => 'string'],
  820. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  821. ],
  822. ]]],
  823. ],
  824. ],
  825. 'schemas' => [
  826. 'Envelope' => [
  827. 'type' => 'object',
  828. 'properties' => [
  829. 'ok' => ['type' => 'boolean'],
  830. 'message' => ['type' => 'string'],
  831. 'data' => ['description' => '业务数据,形状随接口而定'],
  832. ],
  833. ],
  834. ],
  835. ],
  836. 'security' => [['bearerAuth' => []]],
  837. 'paths' => $refs,
  838. ];
  839. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  840. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  841. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  842. file_put_contents(
  843. $protocol.'/main.yaml',
  844. "# 由 openapi/scripts/generate.php 生成,请勿手改\n".$mainYaml
  845. );
  846. printf("生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  847. count($paths),
  848. array_sum(array_map('count', $paths)),
  849. $overridden
  850. );