2
0

generate.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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, 'unauthenticated' => false, 'responses' => []]];
  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, 'unauthenticated' => false, 'responses' => []];
  210. foreach ($tagLines as $line) {
  211. if (str_starts_with($line, '@deprecated')) {
  212. $result['deprecated'] = true;
  213. continue;
  214. }
  215. if (str_starts_with($line, '@unauthenticated')) {
  216. $result['unauthenticated'] = true;
  217. continue;
  218. }
  219. // @responseStatus 503 服务停机维护中
  220. if (preg_match('/^@responseStatus\s+(\d{3})\s*(.*)$/u', $line, $r)) {
  221. $result['responses'][$r[1]] = trim($r[2]) ?: '';
  222. continue;
  223. }
  224. if (! preg_match('/^@(queryParam|bodyParam|urlParam)\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
  225. continue;
  226. }
  227. [, $tag, $name, $type, $rest] = $m;
  228. $rest = trim($rest);
  229. $required = false;
  230. if (preg_match('/^required\b\.?\s*/u', $rest)) {
  231. $required = true;
  232. $rest = trim(preg_replace('/^required\b\.?\s*/u', '', $rest));
  233. }
  234. $entry = [
  235. 'in' => match ($tag) {
  236. 'queryParam' => 'query',
  237. 'urlParam' => 'path',
  238. default => 'body',
  239. },
  240. 'type' => normalizeType($type),
  241. 'required' => $required,
  242. ];
  243. if (preg_match('/\bEnum:\s*((?:(?!\bDefault:|\bExample:)[^.。\n])+)/u', $rest, $e)) {
  244. $entry['enum'] = array_values(array_filter(array_map('trim', explode(',', $e[1]))));
  245. $rest = trim(str_replace($e[0], '', $rest));
  246. }
  247. if (preg_match('/\bDefault:\s*((?:(?!\bExample:)[^.。\n])+)/u', $rest, $d)) {
  248. $entry['default'] = trim($d[1]);
  249. $rest = trim(str_replace($d[0], '', $rest));
  250. }
  251. if (preg_match('/\bExample:\s*([^\n]+)/u', $rest, $x)) {
  252. $example = trim($x[1]);
  253. // 形如 ["a","b"] 或 {...} 的示例按 JSON 解析,否则数组参数的示例
  254. // 会变成字符串,与 schema 的 type 对不上
  255. if (preg_match('/^[\[{]/', $example)) {
  256. $decoded = json_decode($example, true);
  257. if (json_last_error() === JSON_ERROR_NONE) {
  258. $example = $decoded;
  259. }
  260. }
  261. $entry['example'] = $example;
  262. $rest = trim(str_replace($x[0], '', $rest));
  263. }
  264. // trim() 按字节裁剪会把末尾的中文字符截断成非法 UTF-8,这里用 /u 正则
  265. $entry['description'] = preg_replace('/^\s+|[\s.。]+$/u', '', $rest);
  266. $result['params'][$name] = $entry;
  267. }
  268. return $result;
  269. }
  270. function normalizeType(string $type): string
  271. {
  272. return match (strtolower($type)) {
  273. 'int', 'integer' => 'integer',
  274. 'float', 'double', 'number' => 'number',
  275. 'bool', 'boolean' => 'boolean',
  276. 'array', 'string[]', 'int[]' => 'array',
  277. 'object' => 'object',
  278. default => 'string',
  279. };
  280. }
  281. /** 验证规则数组 → [字段 => ['required'=>bool,'type'=>string,'enum'=>[]]] */
  282. function rulesFromArray(Node\Expr\Array_ $array): array
  283. {
  284. $rules = [];
  285. foreach ($array->items as $item) {
  286. if (! $item || ! $item->key instanceof Node\Scalar\String_) {
  287. continue;
  288. }
  289. $raw = null;
  290. if ($item->value instanceof Node\Scalar\String_) {
  291. $raw = $item->value->value;
  292. } elseif ($item->value instanceof Node\Expr\Array_) {
  293. $parts = [];
  294. foreach ($item->value->items as $r) {
  295. if ($r && $r->value instanceof Node\Scalar\String_) {
  296. $parts[] = $r->value->value;
  297. }
  298. }
  299. $raw = implode('|', $parts);
  300. }
  301. if ($raw === null) {
  302. continue;
  303. }
  304. $tokens = explode('|', $raw);
  305. $rule = ['required' => in_array('required', $tokens, true), 'type' => 'string', 'raw' => $raw];
  306. foreach ($tokens as $t) {
  307. if ($t === 'integer' || $t === 'numeric') {
  308. $rule['type'] = $t === 'integer' ? 'integer' : 'number';
  309. } elseif ($t === 'boolean') {
  310. $rule['type'] = 'boolean';
  311. } elseif ($t === 'array') {
  312. $rule['type'] = 'array';
  313. } elseif (str_starts_with($t, 'in:')) {
  314. $rule['enum'] = explode(',', substr($t, 3));
  315. }
  316. }
  317. $rules[$item->key->value] = $rule;
  318. }
  319. return $rules;
  320. }
  321. /** Resource 类的 toArray 键 → schema properties */
  322. function resourceSchema(?string $class): ?array
  323. {
  324. global $api, $parser, $finder;
  325. if (! $class) {
  326. return null;
  327. }
  328. $class = ltrim($class, '\\');
  329. $file = $api.'/'.str_replace(['App\\', '\\'], ['app/', '/'], $class).'.php';
  330. // 控制器里通常写的是短类名(new ChannelResource(...)),按全名拼不出路径,
  331. // 回落到 app/Http/Resources 下同名文件
  332. if (! is_file($file) && ! str_contains($class, '\\')) {
  333. $file = $api.'/app/Http/Resources/'.$class.'.php';
  334. }
  335. if (! is_file($file)) {
  336. return null;
  337. }
  338. $ast = $parser->parse(file_get_contents($file));
  339. if (! $ast) {
  340. return null;
  341. }
  342. $props = [];
  343. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  344. if ($m->name->toString() !== 'toArray') {
  345. continue;
  346. }
  347. // 声明优先:toArray 上写了 @return array{...} 就用它,类型是真声明而非按字段名猜
  348. if ($doc = $m->getDocComment()) {
  349. if ($shape = parseArrayShape($doc->getText())) {
  350. return $shape;
  351. }
  352. }
  353. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  354. foreach ($array->items as $item) {
  355. if ($item && $item->key instanceof Node\Scalar\String_) {
  356. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  357. }
  358. }
  359. }
  360. // $data['x'] = …
  361. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  362. $var = $assign->var;
  363. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  364. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  365. }
  366. }
  367. }
  368. return $props ?: null;
  369. }
  370. /**
  371. * 解析 PHPDoc 里的 `@return array{uid: string, studio: array{...}|false, progress?: float}`。
  372. *
  373. * 支持嵌套 array{}、联合类型(取第一个具体类型,含 null/false 则标 nullable)、
  374. * `key?:` 表示该键只在部分口径下出现。解析不出形状时返回 null,调用方回落到按字段名猜。
  375. *
  376. * @return array<string, array>|null
  377. */
  378. function parseArrayShape(string $docText): ?array
  379. {
  380. if (! preg_match('/@return\s+array\s*\{/s', $docText, $m, PREG_OFFSET_CAPTURE)) {
  381. return null;
  382. }
  383. // 去掉每行开头的 * 再找花括号,避免注释前缀干扰
  384. $body = preg_replace('#^\s*\*\s?#m', '', $docText);
  385. if (! preg_match('/@return\s+array\s*\{(.*)/s', $body, $mm)) {
  386. return null;
  387. }
  388. $inner = extractBraced($mm[1]);
  389. return $inner === null ? null : shapeToProperties($inner);
  390. }
  391. /** 从 `{` 之后的文本里取出配平的内容 */
  392. function extractBraced(string $text): ?string
  393. {
  394. $depth = 1;
  395. $out = '';
  396. $len = strlen($text);
  397. for ($i = 0; $i < $len; $i++) {
  398. $ch = $text[$i];
  399. if ($ch === '{') {
  400. $depth++;
  401. } elseif ($ch === '}') {
  402. $depth--;
  403. if ($depth === 0) {
  404. return $out;
  405. }
  406. }
  407. $out .= $ch;
  408. }
  409. return null;
  410. }
  411. /** 按顶层逗号切分,忽略嵌套花括号与尖括号里的逗号 */
  412. function splitTopLevel(string $text): array
  413. {
  414. $parts = [];
  415. $buf = '';
  416. $depth = 0;
  417. $len = strlen($text);
  418. for ($i = 0; $i < $len; $i++) {
  419. $ch = $text[$i];
  420. if ($ch === '{' || $ch === '<') {
  421. $depth++;
  422. } elseif ($ch === '}' || $ch === '>') {
  423. $depth--;
  424. }
  425. if ($ch === ',' && $depth === 0) {
  426. $parts[] = $buf;
  427. $buf = '';
  428. continue;
  429. }
  430. $buf .= $ch;
  431. }
  432. if (trim($buf) !== '') {
  433. $parts[] = $buf;
  434. }
  435. return $parts;
  436. }
  437. /** array shape 的内容 → OpenAPI properties */
  438. function shapeToProperties(string $inner): array
  439. {
  440. $props = [];
  441. foreach (splitTopLevel($inner) as $part) {
  442. $part = trim($part);
  443. if ($part === '' || ! str_contains($part, ':')) {
  444. continue;
  445. }
  446. [$key, $type] = explode(':', $part, 2);
  447. $key = trim($key);
  448. $optional = str_ends_with($key, '?');
  449. $key = rtrim($key, '?');
  450. if ($key === '') {
  451. continue;
  452. }
  453. $schema = phpTypeToSchema(trim($type));
  454. if ($optional) {
  455. $schema['description'] = trim(($schema['description'] ?? '').' 仅在部分查询口径下返回。');
  456. }
  457. $props[$key] = $schema;
  458. }
  459. return $props;
  460. }
  461. /** PHPDoc 类型 → OpenAPI schema */
  462. function phpTypeToSchema(string $type): array
  463. {
  464. $type = trim($type);
  465. $nullable = false;
  466. if (str_starts_with($type, '?')) {
  467. $nullable = true;
  468. $type = substr($type, 1);
  469. }
  470. // 联合类型:null / false 视为可空,取第一个具体类型
  471. $members = splitTopLevel(str_replace('|', ',', preg_replace('/\|/', '|', $type)));
  472. if (count($members) > 1) {
  473. $concrete = [];
  474. foreach ($members as $mem) {
  475. $mem = trim($mem);
  476. if (in_array(strtolower($mem), ['null', 'false', 'true'], true)) {
  477. $nullable = true;
  478. continue;
  479. }
  480. $concrete[] = $mem;
  481. }
  482. $type = $concrete ? $concrete[0] : 'mixed';
  483. }
  484. $type = trim($type);
  485. // 嵌套 array{...}
  486. if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
  487. $innerText = extractBraced($m[1]);
  488. $schema = ['type' => 'object'];
  489. if ($innerText !== null && ($p = shapeToProperties($innerText))) {
  490. $schema['properties'] = $p;
  491. }
  492. if ($nullable) {
  493. $schema['nullable'] = true;
  494. }
  495. return $schema;
  496. }
  497. // 列表:array<T> / T[] / list<T>
  498. if (preg_match('/^(?:array|list)\s*<(.+)>$/s', $type, $m)) {
  499. $args = splitTopLevel($m[1]);
  500. $itemType = trim(end($args));
  501. $schema = ['type' => 'array', 'items' => phpTypeToSchema($itemType)];
  502. if ($nullable) {
  503. $schema['nullable'] = true;
  504. }
  505. return $schema;
  506. }
  507. if (str_ends_with($type, '[]')) {
  508. $schema = ['type' => 'array', 'items' => phpTypeToSchema(substr($type, 0, -2))];
  509. if ($nullable) {
  510. $schema['nullable'] = true;
  511. }
  512. return $schema;
  513. }
  514. $schema = match (strtolower($type)) {
  515. 'int', 'integer' => ['type' => 'integer'],
  516. 'float', 'double' => ['type' => 'number'],
  517. 'bool', 'boolean' => ['type' => 'boolean'],
  518. 'array' => ['type' => 'array', 'items' => ['type' => 'string']],
  519. 'object', 'mixed', '' => ['type' => 'object'],
  520. default => ['type' => 'string'],
  521. };
  522. if ($nullable) {
  523. $schema['nullable'] = true;
  524. }
  525. return $schema;
  526. }
  527. function guessType(string $field): string
  528. {
  529. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  530. return 'string';
  531. }
  532. if (preg_match('/^(is_|has_|can_)/', $field)) {
  533. return 'boolean';
  534. }
  535. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  536. return 'integer';
  537. }
  538. return 'string';
  539. }
  540. /* ------------------------------------------------------- 生成 operation */
  541. $listParams = Yaml::parseFile($protocol.'/resources/list_query.yaml');
  542. function buildOperation(array $route, string $httpMethod): array
  543. {
  544. global $listParams;
  545. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  546. $info = parseController($class, $method);
  547. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  548. $tag = tagOf($route['uri']);
  549. $op = [
  550. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  551. 'tags' => [$tag],
  552. 'operationId' => strtolower($httpMethod).'_'.preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  553. 'description' => trim(($info['description'] ?? '')."\n\n实现:`{$short}@{$method}`"),
  554. ];
  555. if (! empty($info['tags']['deprecated'])) {
  556. $op['deprecated'] = true;
  557. }
  558. $documented = $info['tags']['params'] ?? [];
  559. $params = [];
  560. // 路径参数
  561. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  562. foreach ($m[1] as $name) {
  563. $doc = $documented[$name] ?? null;
  564. $param = [
  565. 'name' => $name,
  566. 'in' => 'path',
  567. 'required' => true,
  568. 'schema' => ['type' => $doc['type'] ?? 'string'],
  569. ];
  570. if (! empty($doc['description'])) {
  571. $param['description'] = $doc['description'];
  572. }
  573. if (! empty($doc['enum'])) {
  574. $param['schema']['enum'] = $doc['enum'];
  575. }
  576. if (isset($doc['example'])) {
  577. $param['example'] = $doc['example'];
  578. }
  579. $params[] = $param;
  580. }
  581. }
  582. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  583. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  584. $names = array_keys($info['params']);
  585. foreach ($documented as $name => $doc) {
  586. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  587. $names[] = $name;
  588. }
  589. }
  590. foreach ($names as $name) {
  591. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  592. $doc = $documented[$name] ?? null;
  593. if (preg_match('/\{'.preg_quote($name, '/').'\??\}/', $route['uri'])) {
  594. continue;
  595. }
  596. // 文档注释把它标成 body 参数时,不再当查询参数输出
  597. if ($doc && $doc['in'] !== 'query') {
  598. continue;
  599. }
  600. if (! $isRead && ! $doc) {
  601. continue;
  602. }
  603. if (! $isRead) {
  604. continue;
  605. }
  606. $schema = ['type' => $doc['type'] ?? $p['type']];
  607. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  608. if ($enum) {
  609. $schema['enum'] = $enum;
  610. }
  611. $default = $doc['default'] ?? $p['default'] ?? null;
  612. if ($default !== null) {
  613. $schema['default'] = $default;
  614. }
  615. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  616. if (! empty($doc['description'])) {
  617. $param['description'] = $doc['description'];
  618. }
  619. if (! empty($doc['required'])) {
  620. $param['required'] = true;
  621. }
  622. if (isset($doc['example'])) {
  623. $param['example'] = $doc['example'];
  624. }
  625. $params[] = $param;
  626. }
  627. // v2 列表的通用参数(search/order/dir/limit/offset)只属于 v2;
  628. // v3 的分页是 page/per_page,且参数一律要在文档注释里写明,不做兜底注入
  629. if ($method === 'index' && $httpMethod === 'GET' && ! isV3($route['uri'])) {
  630. $known = array_column($params, 'name');
  631. foreach ($listParams as $lp) {
  632. if (! in_array($lp['name'], $known, true)) {
  633. $params[] = $lp;
  634. }
  635. }
  636. }
  637. if ($params) {
  638. $op['parameters'] = $params;
  639. }
  640. // 请求体
  641. if (! $isRead) {
  642. $props = [];
  643. $required = [];
  644. foreach ($info['validate'] as $field => $rule) {
  645. $schema = ['type' => $rule['type'], 'description' => '规则:'.$rule['raw']];
  646. if (! empty($rule['enum'])) {
  647. $schema['enum'] = $rule['enum'];
  648. }
  649. $props[$field] = $schema;
  650. if ($rule['required']) {
  651. $required[] = $field;
  652. }
  653. }
  654. foreach ($info['params'] as $name => $p) {
  655. if (isset($props[$name])) {
  656. continue;
  657. }
  658. $schema = ['type' => $p['type']];
  659. if (! empty($p['enum'])) {
  660. $schema['enum'] = $p['enum'];
  661. }
  662. if ($p['default'] !== null) {
  663. $schema['default'] = $p['default'];
  664. }
  665. $props[$name] = $schema;
  666. }
  667. // 文档注释里写明的字段最权威,覆盖推断结果
  668. foreach ($documented as $name => $doc) {
  669. if ($doc['in'] === 'path') {
  670. continue;
  671. }
  672. $schema = ['type' => $doc['type']];
  673. if (! empty($doc['description'])) {
  674. $schema['description'] = $doc['description'];
  675. }
  676. if (! empty($doc['enum'])) {
  677. $schema['enum'] = $doc['enum'];
  678. }
  679. if (isset($doc['default'])) {
  680. $schema['default'] = $doc['default'];
  681. }
  682. if (isset($doc['example'])) {
  683. $schema['example'] = $doc['example'];
  684. }
  685. $props[$name] = $schema;
  686. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  687. $required[] = $name;
  688. }
  689. }
  690. if ($props) {
  691. $body = ['type' => 'object', 'properties' => $props];
  692. if ($required) {
  693. $body['required'] = $required;
  694. }
  695. $op['requestBody'] = [
  696. 'required' => (bool) $required,
  697. 'content' => ['application/json' => ['schema' => $body]],
  698. ];
  699. }
  700. }
  701. // 响应。v2 与 v3 的信封不同:v2 是 {ok, message, data} 且业务失败也回 200,
  702. // v3 用真实状态码、Laravel 默认的 {data} 包装、错误体是 RFC 9457 Problem Details
  703. $data = ['type' => 'object'];
  704. if ($props = resourceSchema($info['resource'])) {
  705. $data = ['type' => 'object', 'properties' => $props];
  706. }
  707. if (isV3($route['uri'])) {
  708. // v3 用 Laravel Resource 的原生形状:列表 {data: [...], meta: {...}},单个 {data: {...}}
  709. $success = $method === 'index'
  710. ? [
  711. 'type' => 'object',
  712. 'properties' => [
  713. 'data' => ['type' => 'array', 'items' => $data],
  714. 'meta' => ['$ref' => '../../main.yaml#/components/schemas/PaginationMeta'],
  715. ],
  716. ]
  717. : ['type' => 'object', 'properties' => ['data' => $data]];
  718. $responses = [
  719. '200' => [
  720. 'description' => '成功',
  721. 'content' => ['application/json' => ['schema' => $success]],
  722. ],
  723. ];
  724. // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
  725. if (empty($info['tags']['unauthenticated'])) {
  726. $responses['401'] = ['$ref' => '../../main.yaml#/components/responses/ProblemUnauthorized'];
  727. }
  728. // 有入参才可能 422
  729. if (! empty($op['parameters']) || ! empty($op['requestBody'])) {
  730. $responses['422'] = ['$ref' => '../../main.yaml#/components/responses/ProblemValidation'];
  731. }
  732. // @responseStatus 声明的额外状态码
  733. foreach ($info['tags']['responses'] ?? [] as $code => $desc) {
  734. $responses[(string) $code] = [
  735. 'description' => $desc !== '' ? $desc : 'Problem Details',
  736. 'content' => ['application/problem+json' => [
  737. 'schema' => ['$ref' => '../../main.yaml#/components/schemas/ProblemDetails'],
  738. ]],
  739. ];
  740. }
  741. ksort($responses);
  742. $op['responses'] = $responses;
  743. return $op;
  744. }
  745. if ($method === 'index') {
  746. $data = [
  747. 'type' => 'object',
  748. 'properties' => [
  749. 'rows' => ['type' => 'array', 'items' => $data],
  750. 'count' => ['type' => 'integer'],
  751. ],
  752. ];
  753. }
  754. $op['responses'] = [
  755. '200' => [
  756. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  757. 'content' => ['application/json' => ['schema' => [
  758. 'type' => 'object',
  759. 'properties' => [
  760. 'ok' => ['type' => 'boolean'],
  761. 'message' => ['type' => 'string'],
  762. 'data' => $data,
  763. ],
  764. ]]],
  765. ],
  766. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  767. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  768. ];
  769. return $op;
  770. }
  771. /** v3 路由用新契约:真实状态码 + {data} 包装 + Problem Details */
  772. function isV3(string $uri): bool
  773. {
  774. return str_starts_with($uri, 'api/v3/');
  775. }
  776. function defaultSummary(string $method, string $uri): string
  777. {
  778. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  779. return match ($method) {
  780. 'index' => "列出 {$res}",
  781. 'show' => "获取单个 {$res}",
  782. 'store' => "新建 {$res}",
  783. 'update' => "更新 {$res}",
  784. 'destroy' => "删除 {$res}",
  785. default => "{$method} {$res}",
  786. };
  787. }
  788. function tagOf(string $uri): string
  789. {
  790. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  791. $first = explode('/', $path)[0];
  792. return $first === '' ? 'misc' : $first;
  793. }
  794. /* ----------------------------------------------------------- 遍历路由 */
  795. $paths = [];
  796. foreach ($routes as $route) {
  797. $uri = $route['uri'];
  798. if (! str_starts_with($uri, 'api/') || ! str_contains((string) $route['action'], '@')) {
  799. continue;
  800. }
  801. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  802. continue;
  803. }
  804. foreach (explode('|', $route['method']) as $httpMethod) {
  805. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  806. continue;
  807. }
  808. $openapiPath = '/'.preg_replace('#^api/#', '', $uri);
  809. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  810. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  811. }
  812. }
  813. ksort($paths);
  814. /* --------------------------------------------------------- 合并 override */
  815. function deepMerge(array $base, array $over): array
  816. {
  817. foreach ($over as $k => $v) {
  818. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! array_is_list($v))
  819. ? deepMerge($base[$k], $v)
  820. : $v;
  821. }
  822. return $base;
  823. }
  824. function pathSlug(string $path): string
  825. {
  826. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  827. }
  828. $overridden = 0;
  829. foreach ($paths as $path => $ops) {
  830. $file = $overrideDir.'/'.pathSlug($path).'.yaml';
  831. if (is_file($file)) {
  832. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  833. $overridden++;
  834. }
  835. }
  836. /* ------------------------------------------------------------- 写文件 */
  837. foreach (glob($autoDir.'/*.yaml') ?: [] as $stale) {
  838. unlink($stale);
  839. }
  840. @mkdir($autoDir, 0o755, true);
  841. @mkdir($overrideDir, 0o755, true);
  842. $refs = [];
  843. foreach ($paths as $path => $ops) {
  844. $name = pathSlug($path).'.yaml';
  845. file_put_contents(
  846. $autoDir.'/'.$name,
  847. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n".
  848. Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)
  849. );
  850. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  851. }
  852. $main = [
  853. 'openapi' => '3.0.3',
  854. 'info' => [
  855. 'title' => 'MINT API',
  856. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n".
  857. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n".
  858. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  859. 'version' => date('Y.n.j'),
  860. ],
  861. // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
  862. 'servers' => [
  863. ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
  864. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
  865. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  866. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  867. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  868. ],
  869. 'components' => [
  870. 'securitySchemes' => [
  871. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  872. ],
  873. 'responses' => [
  874. 'Unauthorized' => [
  875. 'description' => '未登录或无权限',
  876. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  877. ],
  878. 'ProblemUnauthorized' => [
  879. 'description' => '未登录或无权限(v3)',
  880. 'content' => ['application/problem+json' => [
  881. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  882. ]],
  883. ],
  884. 'ProblemValidation' => [
  885. 'description' => '参数校验失败(v3)',
  886. 'content' => ['application/problem+json' => [
  887. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  888. ]],
  889. ],
  890. 'ValidationError' => [
  891. 'description' => '参数校验失败',
  892. 'content' => ['application/json' => ['schema' => [
  893. 'type' => 'object',
  894. 'properties' => [
  895. 'message' => ['type' => 'string'],
  896. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  897. ],
  898. ]]],
  899. ],
  900. ],
  901. 'schemas' => [
  902. 'ProblemDetails' => [
  903. 'type' => 'object',
  904. 'description' => "RFC 9457 Problem Details,v3 端点的错误响应体。\n".
  905. "由 bootstrap/app.php 的异常处理器统一渲染,控制器不自己拼。\n".
  906. 'media type 是 application/problem+json。',
  907. 'properties' => [
  908. 'type' => ['type' => 'string', 'description' => '问题类型标识,形如 urn:problem:not-found', 'example' => 'urn:problem:not-found'],
  909. 'title' => ['type' => 'string', 'description' => '稳定的英文摘要,同类问题恒定,供机器识别'],
  910. 'status' => ['type' => 'integer'],
  911. 'detail' => ['type' => 'string', 'description' => '面向人的文案,已本地化;5xx 在生产环境会省略以免泄露内部信息'],
  912. 'instance' => ['type' => 'string', 'description' => '出问题的请求 URI'],
  913. 'errors' => [
  914. 'type' => 'object',
  915. 'description' => '字段级校验错误,仅 422 时出现',
  916. 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']],
  917. ],
  918. ],
  919. 'required' => ['type', 'title', 'status'],
  920. ],
  921. 'PaginationMeta' => [
  922. 'type' => 'object',
  923. 'description' => "v3 列表接口的分页信息,由 Laravel paginator 生成。\n".
  924. "刻意不含 links / path:那些是 APP_URL 拼出的绝对地址,反代下会拼错,前端也用不到。\n".
  925. '手工分页的接口会附加自己的字段(如 has_more / first_para / page_size)。',
  926. 'properties' => [
  927. 'current_page' => ['type' => 'integer'],
  928. 'per_page' => ['type' => 'integer'],
  929. 'total' => ['type' => 'integer'],
  930. 'last_page' => ['type' => 'integer'],
  931. 'from' => ['type' => 'integer', 'nullable' => true],
  932. 'to' => ['type' => 'integer', 'nullable' => true],
  933. ],
  934. // 手工分页的接口未必有 per_page(例如按字节切页的阅读接口用 page_size)
  935. 'required' => ['current_page', 'total'],
  936. ],
  937. 'Envelope' => [
  938. 'type' => 'object',
  939. 'properties' => [
  940. 'ok' => ['type' => 'boolean'],
  941. 'message' => ['type' => 'string'],
  942. 'data' => ['description' => '业务数据,形状随接口而定'],
  943. ],
  944. ],
  945. ],
  946. ],
  947. 'security' => [['bearerAuth' => []]],
  948. 'paths' => $refs,
  949. ];
  950. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  951. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  952. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  953. file_put_contents(
  954. $protocol.'/main.yaml',
  955. "# 由 openapi/scripts/generate.php 生成,请勿手改\n".$mainYaml
  956. );
  957. printf("生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  958. count($paths),
  959. array_sum(array_map('count', $paths)),
  960. $overridden
  961. );