2
0

generate.php 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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, 'collection' => false, 'tags' => ['params' => [], 'deprecated' => false, 'unauthenticated' => false, 'responses' => [], 'meta' => []]];
  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. // use 语句:短类名 → 全名。控制器里写的是 `ReactionResource::collection(...)`,
  65. // 只有短名,拼不出文件路径;控制器和 Resource 一旦进了子命名空间
  66. // (App\Http\Resources\V3\…),按平铺目录找就会静默落空、schema 变成空对象。
  67. $imports = [];
  68. foreach ($finder->findInstanceOf($ast, Node\Stmt\Use_::class) as $use) {
  69. foreach ($use->uses as $single) {
  70. $imports[$single->getAlias()->toString()] = $single->name->toString();
  71. }
  72. }
  73. // 文档注释首行作为 summary,其余作为 description;
  74. // @queryParam / @bodyParam / @urlParam / @deprecated 作为结构化补充
  75. if ($doc = $node->getDocComment()) {
  76. $lines = [];
  77. $tagLines = [];
  78. foreach (explode("\n", $doc->getText()) as $line) {
  79. $line = trim(preg_replace('#^\s*(/\*\*|\*/|\*)\s?#u', '', $line));
  80. if ($line === '') {
  81. continue;
  82. }
  83. if (str_starts_with($line, '@')) {
  84. $tagLines[] = $line;
  85. continue;
  86. }
  87. // 上一行是带标签的参数说明时,缩进的续行并入该参数的描述
  88. if ($tagLines && preg_match('/^@(queryParam|bodyParam|urlParam)\b/', end($tagLines))) {
  89. $tagLines[count($tagLines) - 1] .= ' '.$line;
  90. continue;
  91. }
  92. $lines[] = $line;
  93. }
  94. $info['tags'] = parseDocTags($tagLines);
  95. // Laravel 脚手架留下的英文样板不如按资源名生成的摘要有用
  96. $stubs = [
  97. 'Display a listing of the resource.',
  98. 'Display the specified resource.',
  99. 'Store a newly created resource in storage.',
  100. 'Update the specified resource in storage.',
  101. 'Remove the specified resource from storage.',
  102. 'Show the form for creating a new resource.',
  103. 'Show the form for editing the specified resource.',
  104. ];
  105. $lines = array_values(array_filter($lines, fn ($l) => ! in_array($l, $stubs, true)));
  106. if ($lines) {
  107. $info['summary'] = array_shift($lines);
  108. $info['description'] = $lines ? implode("\n", $lines) : null;
  109. }
  110. }
  111. // $request->input('x', default) / query / has / filled / boolean / integer / string
  112. $readers = ['input', 'query', 'has', 'filled', 'boolean', 'integer', 'string', 'get', 'post'];
  113. foreach ($finder->findInstanceOf($node, Node\Expr\MethodCall::class) as $call) {
  114. if (! $call->name instanceof Node\Identifier) {
  115. continue;
  116. }
  117. $name = $call->name->toString();
  118. if (! in_array($name, $readers, true) || ! $call->args) {
  119. continue;
  120. }
  121. if (! ($call->var instanceof Node\Expr\Variable && $call->var->name === 'request')) {
  122. continue;
  123. }
  124. $arg = $call->args[0]->value ?? null;
  125. if (! $arg instanceof Node\Scalar\String_) {
  126. continue;
  127. }
  128. $param = $arg->value;
  129. $default = null;
  130. if (isset($call->args[1]) && $call->args[1]->value instanceof Node\Scalar\String_) {
  131. $default = $call->args[1]->value->value;
  132. }
  133. $type = match ($name) {
  134. 'boolean' => 'boolean',
  135. 'integer' => 'integer',
  136. default => 'string',
  137. };
  138. $prev = $info['params'][$param] ?? null;
  139. $info['params'][$param] = [
  140. 'type' => $prev['type'] ?? $type,
  141. 'default' => $prev['default'] ?? $default,
  142. ];
  143. }
  144. // switch ($request->input('x')) { case 'a': … } → 枚举值
  145. foreach ($finder->findInstanceOf($node, Node\Stmt\Switch_::class) as $switch) {
  146. $cond = $switch->cond;
  147. if (! $cond instanceof Node\Expr\MethodCall || ! $cond->name instanceof Node\Identifier) {
  148. continue;
  149. }
  150. if (! in_array($cond->name->toString(), ['input', 'query', 'get'], true)) {
  151. continue;
  152. }
  153. $arg = $cond->args[0]->value ?? null;
  154. if (! $arg instanceof Node\Scalar\String_ || ! isset($info['params'][$arg->value])) {
  155. continue;
  156. }
  157. $enum = [];
  158. foreach ($switch->cases as $case) {
  159. if ($case->cond instanceof Node\Scalar\String_) {
  160. $enum[] = $case->cond->value;
  161. }
  162. }
  163. if ($enum) {
  164. $info['params'][$arg->value]['enum'] = array_values(array_unique($enum));
  165. }
  166. }
  167. // $request->validate([...]) / Validator::make($request->all(), [...])
  168. foreach ($finder->findInstanceOf($node, Node\Expr\MethodCall::class) as $call) {
  169. if (! $call->name instanceof Node\Identifier || $call->name->toString() !== 'validate') {
  170. continue;
  171. }
  172. $arg = $call->args[0]->value ?? null;
  173. if ($arg instanceof Node\Expr\Array_) {
  174. $info['validate'] += rulesFromArray($arg);
  175. }
  176. }
  177. foreach ($finder->findInstanceOf($node, Node\Expr\StaticCall::class) as $call) {
  178. if (! $call->name instanceof Node\Identifier || $call->name->toString() !== 'make') {
  179. continue;
  180. }
  181. $arg = $call->args[1]->value ?? null;
  182. if ($arg instanceof Node\Expr\Array_) {
  183. $info['validate'] += rulesFromArray($arg);
  184. }
  185. }
  186. // 返回的 Resource 类,以及它是 ::collection() 还是单个
  187. foreach ($finder->findInstanceOf($node, Node\Expr\StaticCall::class) as $call) {
  188. $cls = $call->class instanceof Node\Name ? $call->class->toString() : null;
  189. if ($cls && str_ends_with($cls, 'Resource')) {
  190. $info['resource'] = $imports[$cls] ?? $cls;
  191. $info['collection'] = $call->name instanceof Node\Identifier
  192. && $call->name->toString() === 'collection';
  193. break;
  194. }
  195. }
  196. if (! $info['resource']) {
  197. foreach ($finder->findInstanceOf($node, Node\Expr\New_::class) as $new) {
  198. $cls = $new->class instanceof Node\Name ? $new->class->toString() : null;
  199. if ($cls && str_ends_with($cls, 'Resource')) {
  200. $info['resource'] = $imports[$cls] ?? $cls;
  201. break;
  202. }
  203. }
  204. }
  205. return $methodCache[$key] = $info;
  206. }
  207. /**
  208. * 把 `Default:` / `Example:` 里写的字面量转成参数声明的那个类型。
  209. *
  210. * 文档注释里写什么都是字符串,直接吐出去会得到 `type: integer` 配 `example: '9001'`,
  211. * redocly 的 no-invalid-parameter-examples 会报警,生成的前端类型也对不上。
  212. */
  213. function castToType(string $value, string $type): mixed
  214. {
  215. return match ($type) {
  216. 'integer' => is_numeric($value) ? (int) $value : $value,
  217. 'number' => is_numeric($value) ? (float) $value : $value,
  218. 'boolean' => match (strtolower($value)) {
  219. 'true', '1' => true,
  220. 'false', '0' => false,
  221. default => $value,
  222. },
  223. default => $value,
  224. };
  225. }
  226. /**
  227. * 解析文档注释里的结构化标签。
  228. *
  229. * 支持(Scribe 风格,位置固定):
  230. * @queryParam name type [required] 描述。可在描述里写 Enum: a,b,c / Default: x / Example: y
  231. * @bodyParam name type [required] 描述
  232. * @urlParam name type [required] 描述
  233. * @deprecated 弃用说明
  234. * @unauthenticated 该端点无需登录,不挂 401
  235. * @responseStatus 码 描述 额外的状态码。v3 下 2xx 视为另一种成功口径(响应体与 200
  236. * 同形,如 201 Created),非 2xx 的响应体是 Problem Details
  237. * @meta name type 描述 v3 列表响应的手工分页 meta 字段(如游标式阅读接口)。
  238. * 声明后 meta 不再套通用 PaginationMeta,而是按声明生成专用 schema
  239. *
  240. * @return array{params: array<string, array>, meta: array<string, array>, deprecated: bool}
  241. */
  242. function parseDocTags(array $tagLines): array
  243. {
  244. $result = ['params' => [], 'deprecated' => false, 'unauthenticated' => false, 'responses' => [], 'meta' => []];
  245. foreach ($tagLines as $line) {
  246. if (str_starts_with($line, '@deprecated')) {
  247. $result['deprecated'] = true;
  248. continue;
  249. }
  250. if (str_starts_with($line, '@unauthenticated')) {
  251. $result['unauthenticated'] = true;
  252. continue;
  253. }
  254. // @responseStatus 503 服务停机维护中 / @responseStatus 201 首次创建
  255. if (preg_match('/^@responseStatus\s+(\d{3})\s*(.*)$/u', $line, $r)) {
  256. $result['responses'][$r[1]] = trim($r[2]) ?: '';
  257. continue;
  258. }
  259. // @meta name type 描述 —— 手工分页的 meta 字段
  260. if (preg_match('/^@meta\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
  261. [, $name, $type, $rest] = $m;
  262. $result['meta'][$name] = [
  263. 'type' => normalizeType($type),
  264. 'description' => preg_replace('/^\s+|[\s.。]+$/u', '', $rest),
  265. ];
  266. continue;
  267. }
  268. if (! preg_match('/^@(queryParam|bodyParam|urlParam)\s+(\S+)\s+(\S+)\s*(.*)$/u', $line, $m)) {
  269. continue;
  270. }
  271. [, $tag, $name, $type, $rest] = $m;
  272. $rest = trim($rest);
  273. $required = false;
  274. if (preg_match('/^required\b\.?\s*/u', $rest)) {
  275. $required = true;
  276. $rest = trim(preg_replace('/^required\b\.?\s*/u', '', $rest));
  277. }
  278. $entry = [
  279. 'in' => match ($tag) {
  280. 'queryParam' => 'query',
  281. 'urlParam' => 'path',
  282. default => 'body',
  283. },
  284. 'type' => normalizeType($type),
  285. 'required' => $required,
  286. ];
  287. if (preg_match('/\bEnum:\s*((?:(?!\bDefault:|\bExample:)[^.。\n])+)/u', $rest, $e)) {
  288. $entry['enum'] = array_values(array_filter(array_map('trim', explode(',', $e[1]))));
  289. $rest = trim(str_replace($e[0], '', $rest));
  290. }
  291. if (preg_match('/\bDefault:\s*((?:(?!\bExample:)[^.。\n])+)/u', $rest, $d)) {
  292. $entry['default'] = castToType(trim($d[1]), $entry['type']);
  293. $rest = trim(str_replace($d[0], '', $rest));
  294. }
  295. if (preg_match('/\bExample:\s*([^\n]+)/u', $rest, $x)) {
  296. $example = trim($x[1]);
  297. // 形如 ["a","b"] 或 {...} 的示例按 JSON 解析,否则数组参数的示例
  298. // 会变成字符串,与 schema 的 type 对不上
  299. if (preg_match('/^[\[{]/', $example)) {
  300. $decoded = json_decode($example, true);
  301. if (json_last_error() === JSON_ERROR_NONE) {
  302. $example = $decoded;
  303. }
  304. }
  305. $entry['example'] = is_string($example) ? castToType($example, $entry['type']) : $example;
  306. $rest = trim(str_replace($x[0], '', $rest));
  307. }
  308. // trim() 按字节裁剪会把末尾的中文字符截断成非法 UTF-8,这里用 /u 正则
  309. $entry['description'] = preg_replace('/^\s+|[\s.。]+$/u', '', $rest);
  310. $result['params'][$name] = $entry;
  311. }
  312. return $result;
  313. }
  314. function normalizeType(string $type): string
  315. {
  316. return match (strtolower($type)) {
  317. 'int', 'integer' => 'integer',
  318. 'float', 'double', 'number' => 'number',
  319. 'bool', 'boolean' => 'boolean',
  320. 'array', 'string[]', 'int[]' => 'array',
  321. 'object' => 'object',
  322. default => 'string',
  323. };
  324. }
  325. /** 验证规则数组 → [字段 => ['required'=>bool,'type'=>string,'enum'=>[]]] */
  326. function rulesFromArray(Node\Expr\Array_ $array): array
  327. {
  328. $rules = [];
  329. foreach ($array->items as $item) {
  330. if (! $item || ! $item->key instanceof Node\Scalar\String_) {
  331. continue;
  332. }
  333. $raw = null;
  334. if ($item->value instanceof Node\Scalar\String_) {
  335. $raw = $item->value->value;
  336. } elseif ($item->value instanceof Node\Expr\Array_) {
  337. $parts = [];
  338. foreach ($item->value->items as $r) {
  339. if ($r && $r->value instanceof Node\Scalar\String_) {
  340. $parts[] = $r->value->value;
  341. }
  342. }
  343. $raw = implode('|', $parts);
  344. }
  345. if ($raw === null) {
  346. continue;
  347. }
  348. $tokens = explode('|', $raw);
  349. $rule = ['required' => in_array('required', $tokens, true), 'type' => 'string', 'raw' => $raw];
  350. foreach ($tokens as $t) {
  351. if ($t === 'integer' || $t === 'numeric') {
  352. $rule['type'] = $t === 'integer' ? 'integer' : 'number';
  353. } elseif ($t === 'boolean') {
  354. $rule['type'] = 'boolean';
  355. } elseif ($t === 'array') {
  356. $rule['type'] = 'array';
  357. } elseif (str_starts_with($t, 'in:')) {
  358. $rule['enum'] = explode(',', substr($t, 3));
  359. }
  360. }
  361. $rules[$item->key->value] = $rule;
  362. }
  363. return $rules;
  364. }
  365. /** Resource 类的 toArray 键 → schema properties */
  366. function resourceSchema(?string $class): ?array
  367. {
  368. global $api, $parser, $finder;
  369. if (! $class) {
  370. return null;
  371. }
  372. $class = ltrim($class, '\\');
  373. $file = $api.'/'.str_replace(['App\\', '\\'], ['app/', '/'], $class).'.php';
  374. // 控制器里通常写的是短类名(new ChannelResource(...)),按全名拼不出路径,
  375. // 回落到 app/Http/Resources 下同名文件
  376. if (! is_file($file) && ! str_contains($class, '\\')) {
  377. $file = $api.'/app/Http/Resources/'.$class.'.php';
  378. }
  379. if (! is_file($file)) {
  380. return null;
  381. }
  382. $ast = $parser->parse(file_get_contents($file));
  383. if (! $ast) {
  384. return null;
  385. }
  386. $props = [];
  387. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  388. if ($m->name->toString() !== 'toArray') {
  389. continue;
  390. }
  391. // 声明优先:toArray 上写了 @return array{...} 就用它,类型是真声明而非按字段名猜
  392. if ($doc = $m->getDocComment()) {
  393. if ($shape = parseArrayShape($doc->getText())) {
  394. return $shape;
  395. }
  396. }
  397. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  398. foreach ($array->items as $item) {
  399. if ($item && $item->key instanceof Node\Scalar\String_) {
  400. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  401. }
  402. }
  403. }
  404. // $data['x'] = …
  405. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  406. $var = $assign->var;
  407. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  408. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  409. }
  410. }
  411. }
  412. return $props ?: null;
  413. }
  414. /**
  415. * 解析 PHPDoc 里的 `@return array{uid: string, studio: array{...}|false, progress?: float}`。
  416. *
  417. * 支持嵌套 array{}、联合类型(取第一个具体类型,含 null/false 则标 nullable)、
  418. * `key?:` 表示该键只在部分口径下出现。解析不出形状时返回 null,调用方回落到按字段名猜。
  419. *
  420. * @return array<string, array>|null
  421. */
  422. function parseArrayShape(string $docText): ?array
  423. {
  424. if (! preg_match('/@return\s+array\s*\{/s', $docText, $m, PREG_OFFSET_CAPTURE)) {
  425. return null;
  426. }
  427. // 去掉每行开头的 * 再找花括号,避免注释前缀干扰
  428. $body = preg_replace('#^\s*\*\s?#m', '', $docText);
  429. if (! preg_match('/@return\s+array\s*\{(.*)/s', $body, $mm)) {
  430. return null;
  431. }
  432. $inner = extractBraced($mm[1]);
  433. return $inner === null ? null : shapeToProperties($inner);
  434. }
  435. /** 从 `{` 之后的文本里取出配平的内容 */
  436. function extractBraced(string $text): ?string
  437. {
  438. $depth = 1;
  439. $out = '';
  440. $len = strlen($text);
  441. for ($i = 0; $i < $len; $i++) {
  442. $ch = $text[$i];
  443. if ($ch === '{') {
  444. $depth++;
  445. } elseif ($ch === '}') {
  446. $depth--;
  447. if ($depth === 0) {
  448. return $out;
  449. }
  450. }
  451. $out .= $ch;
  452. }
  453. return null;
  454. }
  455. /** 按顶层逗号切分,忽略嵌套花括号与尖括号里的逗号 */
  456. function splitTopLevel(string $text): array
  457. {
  458. $parts = [];
  459. $buf = '';
  460. $depth = 0;
  461. $len = strlen($text);
  462. for ($i = 0; $i < $len; $i++) {
  463. $ch = $text[$i];
  464. if ($ch === '{' || $ch === '<') {
  465. $depth++;
  466. } elseif ($ch === '}' || $ch === '>') {
  467. $depth--;
  468. }
  469. if ($ch === ',' && $depth === 0) {
  470. $parts[] = $buf;
  471. $buf = '';
  472. continue;
  473. }
  474. $buf .= $ch;
  475. }
  476. if (trim($buf) !== '') {
  477. $parts[] = $buf;
  478. }
  479. return $parts;
  480. }
  481. /** array shape 的内容 → OpenAPI properties */
  482. function shapeToProperties(string $inner): array
  483. {
  484. $props = [];
  485. foreach (splitTopLevel($inner) as $part) {
  486. $part = trim($part);
  487. if ($part === '' || ! str_contains($part, ':')) {
  488. continue;
  489. }
  490. [$key, $type] = explode(':', $part, 2);
  491. $key = trim($key);
  492. $optional = str_ends_with($key, '?');
  493. $key = rtrim($key, '?');
  494. if ($key === '') {
  495. continue;
  496. }
  497. $schema = phpTypeToSchema(trim($type));
  498. if ($optional) {
  499. $schema['description'] = trim(($schema['description'] ?? '').' 仅在部分查询口径下返回。');
  500. }
  501. $props[$key] = $schema;
  502. }
  503. return $props;
  504. }
  505. /** PHPDoc 类型 → OpenAPI schema */
  506. function phpTypeToSchema(string $type): array
  507. {
  508. $type = trim($type);
  509. $nullable = false;
  510. if (str_starts_with($type, '?')) {
  511. $nullable = true;
  512. $type = substr($type, 1);
  513. }
  514. // 联合类型:null / false 视为可空,取第一个具体类型
  515. $members = splitTopLevel(str_replace('|', ',', preg_replace('/\|/', '|', $type)));
  516. if (count($members) > 1) {
  517. $concrete = [];
  518. foreach ($members as $mem) {
  519. $mem = trim($mem);
  520. if (in_array(strtolower($mem), ['null', 'false', 'true'], true)) {
  521. $nullable = true;
  522. continue;
  523. }
  524. $concrete[] = $mem;
  525. }
  526. $type = $concrete ? $concrete[0] : 'mixed';
  527. }
  528. $type = trim($type);
  529. // 嵌套 array{...}
  530. if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
  531. $innerText = extractBraced($m[1]);
  532. $schema = ['type' => 'object'];
  533. if ($innerText !== null && ($p = shapeToProperties($innerText))) {
  534. $schema['properties'] = $p;
  535. }
  536. if ($nullable) {
  537. $schema['nullable'] = true;
  538. }
  539. return $schema;
  540. }
  541. // 列表:array<T> / T[] / list<T>
  542. if (preg_match('/^(?:array|list)\s*<(.+)>$/s', $type, $m)) {
  543. $args = splitTopLevel($m[1]);
  544. $itemType = trim(end($args));
  545. $schema = ['type' => 'array', 'items' => phpTypeToSchema($itemType)];
  546. if ($nullable) {
  547. $schema['nullable'] = true;
  548. }
  549. return $schema;
  550. }
  551. if (str_ends_with($type, '[]')) {
  552. $schema = ['type' => 'array', 'items' => phpTypeToSchema(substr($type, 0, -2))];
  553. if ($nullable) {
  554. $schema['nullable'] = true;
  555. }
  556. return $schema;
  557. }
  558. $schema = match (strtolower($type)) {
  559. 'int', 'integer' => ['type' => 'integer'],
  560. 'float', 'double' => ['type' => 'number'],
  561. 'bool', 'boolean' => ['type' => 'boolean'],
  562. 'array' => ['type' => 'array', 'items' => ['type' => 'string']],
  563. 'object', 'mixed', '' => ['type' => 'object'],
  564. default => ['type' => 'string'],
  565. };
  566. if ($nullable) {
  567. $schema['nullable'] = true;
  568. }
  569. return $schema;
  570. }
  571. function guessType(string $field): string
  572. {
  573. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  574. return 'string';
  575. }
  576. if (preg_match('/^(is_|has_|can_)/', $field)) {
  577. return 'boolean';
  578. }
  579. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  580. return 'integer';
  581. }
  582. return 'string';
  583. }
  584. /**
  585. * v3 列表响应的 meta schema。
  586. *
  587. * 默认是 Eloquent 分页的 PaginationMeta;控制器 docblock 里写了 `@meta` 标签时
  588. * (手工分页,如游标式阅读接口),按声明生成专用 schema,字段名与类型都不再猜测。
  589. *
  590. * @param array $info parseController 的返回
  591. * @return array meta 的 OpenAPI schema
  592. */
  593. function metaSchema(array $info): array
  594. {
  595. $meta = $info['tags']['meta'] ?? [];
  596. if (empty($meta)) {
  597. return ['$ref' => '../../main.yaml#/components/schemas/PaginationMeta'];
  598. }
  599. $properties = [];
  600. foreach ($meta as $name => $field) {
  601. $property = ['type' => $field['type']];
  602. if (! empty($field['description'])) {
  603. $property['description'] = $field['description'];
  604. }
  605. $properties[$name] = $property;
  606. }
  607. return ['type' => 'object', 'properties' => $properties];
  608. }
  609. /* ------------------------------------------------------- 生成 operation */
  610. $listParams = Yaml::parseFile($protocol.'/resources/list_query.yaml');
  611. function buildOperation(array $route, string $httpMethod): array
  612. {
  613. global $listParams;
  614. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  615. $info = parseController($class, $method);
  616. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  617. $tag = tagOf($route['uri']);
  618. $op = [
  619. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  620. 'tags' => [$tag],
  621. 'operationId' => strtolower($httpMethod).'_'.preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  622. 'description' => trim(($info['description'] ?? '')."\n\n实现:`{$short}@{$method}`"),
  623. ];
  624. if (! empty($info['tags']['deprecated'])) {
  625. $op['deprecated'] = true;
  626. }
  627. $documented = $info['tags']['params'] ?? [];
  628. $params = [];
  629. // 路径参数
  630. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  631. foreach ($m[1] as $name) {
  632. $doc = $documented[$name] ?? null;
  633. $param = [
  634. 'name' => $name,
  635. 'in' => 'path',
  636. 'required' => true,
  637. 'schema' => ['type' => $doc['type'] ?? 'string'],
  638. ];
  639. if (! empty($doc['description'])) {
  640. $param['description'] = $doc['description'];
  641. }
  642. if (! empty($doc['enum'])) {
  643. $param['schema']['enum'] = $doc['enum'];
  644. }
  645. if (isset($doc['example'])) {
  646. $param['example'] = $doc['example'];
  647. }
  648. $params[] = $param;
  649. }
  650. }
  651. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  652. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  653. $names = array_keys($info['params']);
  654. foreach ($documented as $name => $doc) {
  655. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  656. $names[] = $name;
  657. }
  658. }
  659. foreach ($names as $name) {
  660. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  661. $doc = $documented[$name] ?? null;
  662. if (preg_match('/\{'.preg_quote($name, '/').'\??\}/', $route['uri'])) {
  663. continue;
  664. }
  665. // 文档注释把它标成 body 参数时,不再当查询参数输出
  666. if ($doc && $doc['in'] !== 'query') {
  667. continue;
  668. }
  669. if (! $isRead && ! $doc) {
  670. continue;
  671. }
  672. if (! $isRead) {
  673. continue;
  674. }
  675. $schema = ['type' => $doc['type'] ?? $p['type']];
  676. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  677. if ($enum) {
  678. $schema['enum'] = $enum;
  679. }
  680. $default = $doc['default'] ?? $p['default'] ?? null;
  681. if ($default !== null) {
  682. $schema['default'] = $default;
  683. }
  684. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  685. if (! empty($doc['description'])) {
  686. $param['description'] = $doc['description'];
  687. }
  688. if (! empty($doc['required'])) {
  689. $param['required'] = true;
  690. }
  691. if (isset($doc['example'])) {
  692. $param['example'] = $doc['example'];
  693. }
  694. $params[] = $param;
  695. }
  696. // v2 列表的通用参数(search/order/dir/limit/offset)只属于 v2;
  697. // v3 的分页是 page/per_page,且参数一律要在文档注释里写明,不做兜底注入
  698. if ($method === 'index' && $httpMethod === 'GET' && ! isV3($route['uri'])) {
  699. $known = array_column($params, 'name');
  700. foreach ($listParams as $lp) {
  701. if (! in_array($lp['name'], $known, true)) {
  702. $params[] = $lp;
  703. }
  704. }
  705. }
  706. if ($params) {
  707. $op['parameters'] = $params;
  708. }
  709. // 请求体
  710. if (! $isRead) {
  711. $props = [];
  712. $required = [];
  713. foreach ($info['validate'] as $field => $rule) {
  714. $schema = ['type' => $rule['type'], 'description' => '规则:'.$rule['raw']];
  715. if (! empty($rule['enum'])) {
  716. $schema['enum'] = $rule['enum'];
  717. }
  718. $props[$field] = $schema;
  719. if ($rule['required']) {
  720. $required[] = $field;
  721. }
  722. }
  723. foreach ($info['params'] as $name => $p) {
  724. if (isset($props[$name])) {
  725. continue;
  726. }
  727. $schema = ['type' => $p['type']];
  728. if (! empty($p['enum'])) {
  729. $schema['enum'] = $p['enum'];
  730. }
  731. if ($p['default'] !== null) {
  732. $schema['default'] = $p['default'];
  733. }
  734. $props[$name] = $schema;
  735. }
  736. // 文档注释里写明的字段最权威,覆盖推断结果
  737. foreach ($documented as $name => $doc) {
  738. if ($doc['in'] === 'path') {
  739. continue;
  740. }
  741. $schema = ['type' => $doc['type']];
  742. if (! empty($doc['description'])) {
  743. $schema['description'] = $doc['description'];
  744. }
  745. if (! empty($doc['enum'])) {
  746. $schema['enum'] = $doc['enum'];
  747. }
  748. if (isset($doc['default'])) {
  749. $schema['default'] = $doc['default'];
  750. }
  751. if (isset($doc['example'])) {
  752. $schema['example'] = $doc['example'];
  753. }
  754. $props[$name] = $schema;
  755. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  756. $required[] = $name;
  757. }
  758. }
  759. if ($props) {
  760. $body = ['type' => 'object', 'properties' => $props];
  761. if ($required) {
  762. $body['required'] = $required;
  763. }
  764. $op['requestBody'] = [
  765. 'required' => (bool) $required,
  766. 'content' => ['application/json' => ['schema' => $body]],
  767. ];
  768. }
  769. }
  770. // 响应。v2 与 v3 的信封不同:v2 是 {ok, message, data} 且业务失败也回 200,
  771. // v3 用真实状态码、Laravel 默认的 {data} 包装、错误体是 RFC 9457 Problem Details
  772. $data = ['type' => 'object'];
  773. if ($props = resourceSchema($info['resource'])) {
  774. $data = ['type' => 'object', 'properties' => $props];
  775. }
  776. if (isV3($route['uri'])) {
  777. // v3 用 Laravel Resource 的原生形状:列表 {data: [...], meta: {...}},单个 {data: {...}}
  778. //
  779. // 判断依据是控制器返回的是不是 `::collection()`,不能只看方法名叫不叫 index:
  780. // 单动作控制器的方法名是 __invoke,照样可以返回集合。
  781. $isList = $method === 'index' || ! empty($info['collection']);
  782. $success = $isList
  783. ? [
  784. 'type' => 'object',
  785. 'properties' => [
  786. 'data' => ['type' => 'array', 'items' => $data],
  787. 'meta' => metaSchema($info),
  788. ],
  789. ]
  790. : ['type' => 'object', 'properties' => ['data' => $data]];
  791. // 声明了 204 就不再输出默认的 200——控制器 return response()->noContent()
  792. // 的端点没有 200 这个口径,留着会让前端以为可以读 body
  793. $declared = $info['tags']['responses'] ?? [];
  794. $responses = isset($declared[204]) ? [] : [
  795. '200' => [
  796. 'description' => '成功',
  797. 'content' => ['application/json' => ['schema' => $success]],
  798. ],
  799. ];
  800. // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
  801. if (empty($info['tags']['unauthenticated'])) {
  802. $responses['401'] = ['$ref' => '../../main.yaml#/components/responses/ProblemUnauthorized'];
  803. }
  804. // 有入参才可能 422
  805. if (! empty($op['parameters']) || ! empty($op['requestBody'])) {
  806. $responses['422'] = ['$ref' => '../../main.yaml#/components/responses/ProblemValidation'];
  807. }
  808. // @responseStatus 声明的额外状态码。2xx 是另一种成功口径(如 201 Created),
  809. // 响应体与 200 同形;其余是错误,响应体是 Problem Details。
  810. foreach ($declared as $code => $desc) {
  811. $isSuccess = $code >= 200 && $code < 300;
  812. // 204 / 205 按 RFC 9110 MUST NOT 带消息体,不给 content
  813. if ((int) $code === 204 || (int) $code === 205) {
  814. $responses[(string) $code] = ['description' => $desc !== '' ? $desc : '成功,无响应体'];
  815. continue;
  816. }
  817. $responses[(string) $code] = $isSuccess
  818. ? [
  819. 'description' => $desc !== '' ? $desc : '成功',
  820. 'content' => ['application/json' => ['schema' => $success]],
  821. ]
  822. : [
  823. 'description' => $desc !== '' ? $desc : 'Problem Details',
  824. 'content' => ['application/problem+json' => [
  825. 'schema' => ['$ref' => '../../main.yaml#/components/schemas/ProblemDetails'],
  826. ]],
  827. ];
  828. }
  829. ksort($responses);
  830. $op['responses'] = $responses;
  831. return $op;
  832. }
  833. if ($method === 'index') {
  834. $data = [
  835. 'type' => 'object',
  836. 'properties' => [
  837. 'rows' => ['type' => 'array', 'items' => $data],
  838. 'count' => ['type' => 'integer'],
  839. ],
  840. ];
  841. }
  842. $op['responses'] = [
  843. '200' => [
  844. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  845. 'content' => ['application/json' => ['schema' => [
  846. 'type' => 'object',
  847. 'properties' => [
  848. 'ok' => ['type' => 'boolean'],
  849. 'message' => ['type' => 'string'],
  850. 'data' => $data,
  851. ],
  852. ]]],
  853. ],
  854. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  855. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  856. ];
  857. return $op;
  858. }
  859. /** v3 路由用新契约:真实状态码 + {data} 包装 + Problem Details */
  860. function isV3(string $uri): bool
  861. {
  862. return str_starts_with($uri, 'api/v3/');
  863. }
  864. function defaultSummary(string $method, string $uri): string
  865. {
  866. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  867. return match ($method) {
  868. 'index' => "列出 {$res}",
  869. 'show' => "获取单个 {$res}",
  870. 'store' => "新建 {$res}",
  871. 'update' => "更新 {$res}",
  872. 'destroy' => "删除 {$res}",
  873. default => "{$method} {$res}",
  874. };
  875. }
  876. function tagOf(string $uri): string
  877. {
  878. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  879. $first = explode('/', $path)[0];
  880. return $first === '' ? 'misc' : $first;
  881. }
  882. /* ----------------------------------------------------------- 遍历路由 */
  883. $paths = [];
  884. foreach ($routes as $route) {
  885. $uri = $route['uri'];
  886. $action = (string) $route['action'];
  887. // 原来用「action 里有没有 @」当作「是不是控制器」,把**单动作控制器**
  888. // (invokable,action 就是类名、没有 @method)整条漏掉了,而且不报错。
  889. // buildOperation() 下游本来就有 __invoke 的兜底,这里放行即可。
  890. if (! str_starts_with($uri, 'api/') || $action === '' || $action === 'Closure') {
  891. continue;
  892. }
  893. if (! str_contains($action, '@') && ! str_contains($action, 'Controllers\\')) {
  894. continue;
  895. }
  896. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  897. continue;
  898. }
  899. foreach (explode('|', $route['method']) as $httpMethod) {
  900. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  901. continue;
  902. }
  903. $openapiPath = '/'.preg_replace('#^api/#', '', $uri);
  904. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  905. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  906. }
  907. }
  908. ksort($paths);
  909. /* --------------------------------------------------------- 合并 override */
  910. function deepMerge(array $base, array $over): array
  911. {
  912. foreach ($over as $k => $v) {
  913. // 列表值整体替换;含 $ref / oneOf / anyOf / allOf 的 schema 也整体替换,
  914. // 否则自动结果里的 `type: object` 会与 oneOf 并存,变成不合法 schema
  915. $replace = ! is_array($v)
  916. || array_is_list($v)
  917. || array_intersect(['$ref', 'oneOf', 'anyOf', 'allOf'], array_keys($v)) !== [];
  918. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! $replace)
  919. ? deepMerge($base[$k], $v)
  920. : $v;
  921. }
  922. return $base;
  923. }
  924. function pathSlug(string $path): string
  925. {
  926. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  927. }
  928. $overridden = 0;
  929. foreach ($paths as $path => $ops) {
  930. $file = $overrideDir.'/'.pathSlug($path).'.yaml';
  931. if (is_file($file)) {
  932. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  933. $overridden++;
  934. }
  935. }
  936. /* ------------------------------------------------------------- 写文件 */
  937. foreach (glob($autoDir.'/*.yaml') ?: [] as $stale) {
  938. unlink($stale);
  939. }
  940. @mkdir($autoDir, 0o755, true);
  941. @mkdir($overrideDir, 0o755, true);
  942. $refs = [];
  943. foreach ($paths as $path => $ops) {
  944. $name = pathSlug($path).'.yaml';
  945. file_put_contents(
  946. $autoDir.'/'.$name,
  947. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n".
  948. Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK)
  949. );
  950. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  951. }
  952. $main = [
  953. 'openapi' => '3.0.3',
  954. 'info' => [
  955. 'title' => 'MINT API',
  956. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n".
  957. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n".
  958. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  959. 'version' => date('Y.n.j'),
  960. ],
  961. // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
  962. 'servers' => [
  963. ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
  964. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
  965. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  966. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  967. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  968. ],
  969. 'components' => [
  970. 'securitySchemes' => [
  971. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  972. ],
  973. 'responses' => [
  974. 'Unauthorized' => [
  975. 'description' => '未登录或无权限',
  976. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  977. ],
  978. 'ProblemUnauthorized' => [
  979. 'description' => '未登录或无权限(v3)',
  980. 'content' => ['application/problem+json' => [
  981. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  982. ]],
  983. ],
  984. 'ProblemValidation' => [
  985. 'description' => '参数校验失败(v3)',
  986. 'content' => ['application/problem+json' => [
  987. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  988. ]],
  989. ],
  990. 'ValidationError' => [
  991. 'description' => '参数校验失败',
  992. 'content' => ['application/json' => ['schema' => [
  993. 'type' => 'object',
  994. 'properties' => [
  995. 'message' => ['type' => 'string'],
  996. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  997. ],
  998. ]]],
  999. ],
  1000. ],
  1001. 'schemas' => [
  1002. 'ProblemDetails' => [
  1003. 'type' => 'object',
  1004. 'description' => "RFC 9457 Problem Details,v3 端点的错误响应体。\n".
  1005. "由 bootstrap/app.php 的异常处理器统一渲染,控制器不自己拼。\n".
  1006. 'media type 是 application/problem+json。',
  1007. 'properties' => [
  1008. 'type' => ['type' => 'string', 'description' => '问题类型标识,形如 urn:problem:not-found', 'example' => 'urn:problem:not-found'],
  1009. 'title' => ['type' => 'string', 'description' => '稳定的英文摘要,同类问题恒定,供机器识别'],
  1010. 'status' => ['type' => 'integer'],
  1011. 'detail' => ['type' => 'string', 'description' => '面向人的文案,已本地化;5xx 在生产环境会省略以免泄露内部信息'],
  1012. 'instance' => ['type' => 'string', 'description' => '出问题的请求 URI'],
  1013. 'errors' => [
  1014. 'type' => 'object',
  1015. 'description' => '字段级校验错误,仅 422 时出现',
  1016. 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']],
  1017. ],
  1018. ],
  1019. 'required' => ['type', 'title', 'status'],
  1020. ],
  1021. 'PaginationMeta' => [
  1022. 'type' => 'object',
  1023. 'description' => "v3 列表接口的分页信息,由 Laravel paginator 生成。\n".
  1024. "刻意不含 links / path:那些是 APP_URL 拼出的绝对地址,反代下会拼错,前端也用不到。\n".
  1025. '手工分页的接口会附加自己的字段(如 has_more / first_para / page_size)。',
  1026. 'properties' => [
  1027. 'current_page' => ['type' => 'integer'],
  1028. 'per_page' => ['type' => 'integer'],
  1029. 'total' => ['type' => 'integer'],
  1030. 'last_page' => ['type' => 'integer'],
  1031. 'from' => ['type' => 'integer', 'nullable' => true],
  1032. 'to' => ['type' => 'integer', 'nullable' => true],
  1033. ],
  1034. // 手工分页的接口未必有 per_page(例如按字节切页的阅读接口用 page_size)
  1035. 'required' => ['current_page', 'total'],
  1036. ],
  1037. 'Envelope' => [
  1038. 'type' => 'object',
  1039. 'properties' => [
  1040. 'ok' => ['type' => 'boolean'],
  1041. 'message' => ['type' => 'string'],
  1042. 'data' => ['description' => '业务数据,形状随接口而定'],
  1043. ],
  1044. ],
  1045. ],
  1046. ],
  1047. 'security' => [['bearerAuth' => []]],
  1048. 'paths' => $refs,
  1049. ];
  1050. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  1051. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  1052. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  1053. file_put_contents(
  1054. $protocol.'/main.yaml',
  1055. "# 由 openapi/scripts/generate.php 生成,请勿手改\n".$mainYaml
  1056. );
  1057. printf("生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  1058. count($paths),
  1059. array_sum(array_map('count', $paths)),
  1060. $overridden
  1061. );