2
0

generate.php 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  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. /**
  326. * 把点号写法的数组元素字段(`targets.*.id`、`ids.*`)折进父字段的 items。
  327. *
  328. * Laravel 的校验规则和文档注释都用这种写法;不折的话它们会变成名字里带点的顶层字段,
  329. * 前端类型与生成的客户端都对不上。只处理一层(`a.*` / `a.*.b`),更深的嵌套原样留着。
  330. *
  331. * @param array<string, array> $props
  332. * @param list<string> $required
  333. * @return array{0: array<string, array>, 1: list<string>}
  334. */
  335. function nestDotted(array $props, array $required): array
  336. {
  337. foreach (array_keys($props) as $key) {
  338. if (! preg_match('/^([^.]+)\.\*(?:\.([^.*]+))?$/', $key, $m)) {
  339. continue;
  340. }
  341. [$parent, $child] = [$m[1], $m[2] ?? null];
  342. $schema = $props[$key];
  343. unset($props[$key]);
  344. $props[$parent] = ($props[$parent] ?? []) + ['type' => 'array'];
  345. $props[$parent]['type'] = 'array';
  346. if ($child === null) {
  347. $props[$parent]['items'] = $schema;
  348. } else {
  349. $props[$parent]['items'] ??= ['type' => 'object', 'properties' => []];
  350. $props[$parent]['items']['properties'][$child] = $schema;
  351. if (in_array($key, $required, true)) {
  352. $props[$parent]['items']['required'][] = $child;
  353. }
  354. }
  355. $required = array_values(array_filter($required, fn ($name) => $name !== $key));
  356. }
  357. return [$props, $required];
  358. }
  359. /** 验证规则数组 → [字段 => ['required'=>bool,'type'=>string,'enum'=>[]]] */
  360. function rulesFromArray(Node\Expr\Array_ $array): array
  361. {
  362. $rules = [];
  363. foreach ($array->items as $item) {
  364. if (! $item || ! $item->key instanceof Node\Scalar\String_) {
  365. continue;
  366. }
  367. $raw = null;
  368. if ($item->value instanceof Node\Scalar\String_) {
  369. $raw = $item->value->value;
  370. } elseif ($item->value instanceof Node\Expr\Array_) {
  371. $parts = [];
  372. foreach ($item->value->items as $r) {
  373. if ($r && $r->value instanceof Node\Scalar\String_) {
  374. $parts[] = $r->value->value;
  375. }
  376. }
  377. $raw = implode('|', $parts);
  378. }
  379. if ($raw === null) {
  380. continue;
  381. }
  382. $tokens = explode('|', $raw);
  383. $rule = ['required' => in_array('required', $tokens, true), 'type' => 'string', 'raw' => $raw];
  384. foreach ($tokens as $t) {
  385. if ($t === 'integer' || $t === 'numeric') {
  386. $rule['type'] = $t === 'integer' ? 'integer' : 'number';
  387. } elseif ($t === 'boolean') {
  388. $rule['type'] = 'boolean';
  389. } elseif ($t === 'array') {
  390. $rule['type'] = 'array';
  391. } elseif (str_starts_with($t, 'in:')) {
  392. $rule['enum'] = explode(',', substr($t, 3));
  393. }
  394. }
  395. $rules[$item->key->value] = $rule;
  396. }
  397. return $rules;
  398. }
  399. /** Resource 类的 toArray 键 → schema properties */
  400. function resourceSchema(?string $class): ?array
  401. {
  402. global $api, $parser, $finder;
  403. if (! $class) {
  404. return null;
  405. }
  406. $class = ltrim($class, '\\');
  407. $file = $api . '/' . str_replace(['App\\', '\\'], ['app/', '/'], $class) . '.php';
  408. // 控制器里通常写的是短类名(new ChannelResource(...)),按全名拼不出路径,
  409. // 回落到 app/Http/Resources 下同名文件
  410. if (! is_file($file) && ! str_contains($class, '\\')) {
  411. $file = $api . '/app/Http/Resources/' . $class . '.php';
  412. }
  413. if (! is_file($file)) {
  414. return null;
  415. }
  416. $ast = $parser->parse(file_get_contents($file));
  417. if (! $ast) {
  418. return null;
  419. }
  420. $props = [];
  421. foreach ($finder->findInstanceOf($ast, Node\Stmt\ClassMethod::class) as $m) {
  422. if ($m->name->toString() !== 'toArray') {
  423. continue;
  424. }
  425. // 声明优先:toArray 上写了 @return array{...} 就用它,类型是真声明而非按字段名猜
  426. if ($doc = $m->getDocComment()) {
  427. if ($shape = parseArrayShape($doc->getText())) {
  428. return $shape;
  429. }
  430. }
  431. foreach ($finder->findInstanceOf($m, Node\Expr\Array_::class) as $array) {
  432. foreach ($array->items as $item) {
  433. if ($item && $item->key instanceof Node\Scalar\String_) {
  434. $props[$item->key->value] = ['type' => guessType($item->key->value)];
  435. }
  436. }
  437. }
  438. // $data['x'] = …
  439. foreach ($finder->findInstanceOf($m, Node\Expr\Assign::class) as $assign) {
  440. $var = $assign->var;
  441. if ($var instanceof Node\Expr\ArrayDimFetch && $var->dim instanceof Node\Scalar\String_) {
  442. $props[$var->dim->value] = ['type' => guessType($var->dim->value)];
  443. }
  444. }
  445. }
  446. return $props ?: null;
  447. }
  448. /**
  449. * 解析 PHPDoc 里的 `@return array{uid: string, studio: array{...}|false, progress?: float}`。
  450. *
  451. * 支持嵌套 array{}、联合类型(取第一个具体类型,含 null/false 则标 nullable)、
  452. * `key?:` 表示该键只在部分口径下出现。解析不出形状时返回 null,调用方回落到按字段名猜。
  453. *
  454. * @return array<string, array>|null
  455. */
  456. function parseArrayShape(string $docText): ?array
  457. {
  458. if (! preg_match('/@return\s+array\s*\{/s', $docText, $m, PREG_OFFSET_CAPTURE)) {
  459. return null;
  460. }
  461. // 去掉每行开头的 * 再找花括号,避免注释前缀干扰
  462. $body = preg_replace('#^\s*\*\s?#m', '', $docText);
  463. if (! preg_match('/@return\s+array\s*\{(.*)/s', $body, $mm)) {
  464. return null;
  465. }
  466. $inner = extractBraced($mm[1]);
  467. return $inner === null ? null : shapeToProperties($inner);
  468. }
  469. /** 从 `{` 之后的文本里取出配平的内容 */
  470. function extractBraced(string $text): ?string
  471. {
  472. $depth = 1;
  473. $out = '';
  474. $len = strlen($text);
  475. for ($i = 0; $i < $len; $i++) {
  476. $ch = $text[$i];
  477. if ($ch === '{') {
  478. $depth++;
  479. } elseif ($ch === '}') {
  480. $depth--;
  481. if ($depth === 0) {
  482. return $out;
  483. }
  484. }
  485. $out .= $ch;
  486. }
  487. return null;
  488. }
  489. /** 按顶层逗号切分,忽略嵌套花括号与尖括号里的逗号 */
  490. function splitTopLevel(string $text): array
  491. {
  492. $parts = [];
  493. $buf = '';
  494. $depth = 0;
  495. $len = strlen($text);
  496. for ($i = 0; $i < $len; $i++) {
  497. $ch = $text[$i];
  498. if ($ch === '{' || $ch === '<') {
  499. $depth++;
  500. } elseif ($ch === '}' || $ch === '>') {
  501. $depth--;
  502. }
  503. if ($ch === ',' && $depth === 0) {
  504. $parts[] = $buf;
  505. $buf = '';
  506. continue;
  507. }
  508. $buf .= $ch;
  509. }
  510. if (trim($buf) !== '') {
  511. $parts[] = $buf;
  512. }
  513. return $parts;
  514. }
  515. /** array shape 的内容 → OpenAPI properties */
  516. function shapeToProperties(string $inner): array
  517. {
  518. $props = [];
  519. foreach (splitTopLevel($inner) as $part) {
  520. $part = trim($part);
  521. if ($part === '' || ! str_contains($part, ':')) {
  522. continue;
  523. }
  524. [$key, $type] = explode(':', $part, 2);
  525. $key = trim($key);
  526. $optional = str_ends_with($key, '?');
  527. $key = rtrim($key, '?');
  528. if ($key === '') {
  529. continue;
  530. }
  531. $schema = phpTypeToSchema(trim($type));
  532. if ($optional) {
  533. $schema['description'] = trim(($schema['description'] ?? '') . ' 仅在部分查询口径下返回。');
  534. }
  535. $props[$key] = $schema;
  536. }
  537. return $props;
  538. }
  539. /** PHPDoc 类型 → OpenAPI schema */
  540. function phpTypeToSchema(string $type): array
  541. {
  542. $type = trim($type);
  543. $nullable = false;
  544. if (str_starts_with($type, '?')) {
  545. $nullable = true;
  546. $type = substr($type, 1);
  547. }
  548. // 联合类型:null / false 视为可空,取第一个具体类型
  549. $members = splitTopLevel(str_replace('|', ',', preg_replace('/\|/', '|', $type)));
  550. if (count($members) > 1) {
  551. $concrete = [];
  552. foreach ($members as $mem) {
  553. $mem = trim($mem);
  554. if (in_array(strtolower($mem), ['null', 'false', 'true'], true)) {
  555. $nullable = true;
  556. continue;
  557. }
  558. $concrete[] = $mem;
  559. }
  560. $type = $concrete ? $concrete[0] : 'mixed';
  561. }
  562. $type = trim($type);
  563. // 嵌套 array{...}
  564. if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
  565. $innerText = extractBraced($m[1]);
  566. $schema = ['type' => 'object'];
  567. if ($innerText !== null && ($p = shapeToProperties($innerText))) {
  568. $schema['properties'] = $p;
  569. }
  570. if ($nullable) {
  571. $schema['nullable'] = true;
  572. }
  573. return $schema;
  574. }
  575. // 列表:array<T> / T[] / list<T>
  576. if (preg_match('/^(?:array|list)\s*<(.+)>$/s', $type, $m)) {
  577. $args = splitTopLevel($m[1]);
  578. $itemType = trim(end($args));
  579. $schema = ['type' => 'array', 'items' => phpTypeToSchema($itemType)];
  580. if ($nullable) {
  581. $schema['nullable'] = true;
  582. }
  583. return $schema;
  584. }
  585. if (str_ends_with($type, '[]')) {
  586. $schema = ['type' => 'array', 'items' => phpTypeToSchema(substr($type, 0, -2))];
  587. if ($nullable) {
  588. $schema['nullable'] = true;
  589. }
  590. return $schema;
  591. }
  592. $schema = match (strtolower($type)) {
  593. 'int', 'integer' => ['type' => 'integer'],
  594. 'float', 'double' => ['type' => 'number'],
  595. 'bool', 'boolean' => ['type' => 'boolean'],
  596. 'array' => ['type' => 'array', 'items' => ['type' => 'string']],
  597. 'object', 'mixed', '' => ['type' => 'object'],
  598. default => ['type' => 'string'],
  599. };
  600. if ($nullable) {
  601. $schema['nullable'] = true;
  602. }
  603. return $schema;
  604. }
  605. function guessType(string $field): string
  606. {
  607. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  608. return 'string';
  609. }
  610. if (preg_match('/^(is_|has_|can_)/', $field)) {
  611. return 'boolean';
  612. }
  613. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  614. return 'integer';
  615. }
  616. return 'string';
  617. }
  618. /**
  619. * v3 列表响应的 meta schema。
  620. *
  621. * 默认是 Eloquent 分页的 PaginationMeta;控制器 docblock 里写了 `@meta` 标签时
  622. * (手工分页,如游标式阅读接口),按声明生成专用 schema,字段名与类型都不再猜测。
  623. *
  624. * @param array $info parseController 的返回
  625. * @return array meta 的 OpenAPI schema
  626. */
  627. function metaSchema(array $info): array
  628. {
  629. $meta = $info['tags']['meta'] ?? [];
  630. if (empty($meta)) {
  631. return ['$ref' => '../../main.yaml#/components/schemas/PaginationMeta'];
  632. }
  633. $properties = [];
  634. foreach ($meta as $name => $field) {
  635. $property = ['type' => $field['type']];
  636. if (! empty($field['description'])) {
  637. $property['description'] = $field['description'];
  638. }
  639. $properties[$name] = $property;
  640. }
  641. return ['type' => 'object', 'properties' => $properties];
  642. }
  643. /* ------------------------------------------------------- 生成 operation */
  644. $listParams = Yaml::parseFile($protocol . '/resources/list_query.yaml');
  645. function buildOperation(array $route, string $httpMethod): array
  646. {
  647. global $listParams;
  648. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  649. $info = parseController($class, $method);
  650. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  651. $tag = tagOf($route['uri']);
  652. $op = [
  653. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  654. 'tags' => [$tag],
  655. 'operationId' => strtolower($httpMethod) . '_' . preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  656. 'description' => trim(($info['description'] ?? '') . "\n\n实现:`{$short}@{$method}`"),
  657. ];
  658. if (! empty($info['tags']['deprecated'])) {
  659. $op['deprecated'] = true;
  660. }
  661. // v3 的鉴权按路由中间件逐个写准(v2 沿用全局 security,不动):
  662. // 挂了 auth.v3 → 必须带 token;没挂 → 匿名可用,带了 token 就按登录用户处理
  663. // (讨论列表的可见性、tally 的「我点过没有」),所以是「可选」。生成的客户端据此
  664. // 决定发不发 Authorization——同一路径读公开、写要登录(middlewareFor)也能分清。
  665. if (str_starts_with($route['uri'], 'api/v3/')) {
  666. $op['security'] = in_array('auth.v3', $route['middleware'] ?? [], true)
  667. ? [['bearerAuth' => []]]
  668. : [[], ['bearerAuth' => []]];
  669. }
  670. $documented = $info['tags']['params'] ?? [];
  671. $params = [];
  672. // 路径参数
  673. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  674. foreach ($m[1] as $name) {
  675. $doc = $documented[$name] ?? null;
  676. $param = [
  677. 'name' => $name,
  678. 'in' => 'path',
  679. 'required' => true,
  680. 'schema' => ['type' => $doc['type'] ?? 'string'],
  681. ];
  682. if (! empty($doc['description'])) {
  683. $param['description'] = $doc['description'];
  684. }
  685. if (! empty($doc['enum'])) {
  686. $param['schema']['enum'] = $doc['enum'];
  687. }
  688. if (isset($doc['example'])) {
  689. $param['example'] = $doc['example'];
  690. }
  691. $params[] = $param;
  692. }
  693. }
  694. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  695. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  696. $names = array_keys($info['params']);
  697. foreach ($documented as $name => $doc) {
  698. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  699. $names[] = $name;
  700. }
  701. }
  702. foreach ($names as $name) {
  703. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  704. $doc = $documented[$name] ?? null;
  705. if (preg_match('/\{' . preg_quote($name, '/') . '\??\}/', $route['uri'])) {
  706. continue;
  707. }
  708. // 文档注释把它标成 body 参数时,不再当查询参数输出
  709. if ($doc && $doc['in'] !== 'query') {
  710. continue;
  711. }
  712. if (! $isRead && ! $doc) {
  713. continue;
  714. }
  715. if (! $isRead) {
  716. continue;
  717. }
  718. $schema = ['type' => $doc['type'] ?? $p['type']];
  719. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  720. if ($enum) {
  721. $schema['enum'] = $enum;
  722. }
  723. $default = $doc['default'] ?? $p['default'] ?? null;
  724. if ($default !== null) {
  725. $schema['default'] = $default;
  726. }
  727. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  728. if (! empty($doc['description'])) {
  729. $param['description'] = $doc['description'];
  730. }
  731. if (! empty($doc['required'])) {
  732. $param['required'] = true;
  733. }
  734. if (isset($doc['example'])) {
  735. $param['example'] = $doc['example'];
  736. }
  737. $params[] = $param;
  738. }
  739. // v2 列表的通用参数(search/order/dir/limit/offset)只属于 v2;
  740. // v3 的分页是 page/per_page,且参数一律要在文档注释里写明,不做兜底注入
  741. if ($method === 'index' && $httpMethod === 'GET' && ! isV3($route['uri'])) {
  742. $known = array_column($params, 'name');
  743. foreach ($listParams as $lp) {
  744. if (! in_array($lp['name'], $known, true)) {
  745. $params[] = $lp;
  746. }
  747. }
  748. }
  749. if ($params) {
  750. $op['parameters'] = $params;
  751. }
  752. // 请求体
  753. if (! $isRead) {
  754. $props = [];
  755. $required = [];
  756. foreach ($info['validate'] as $field => $rule) {
  757. $schema = ['type' => $rule['type'], 'description' => '规则:' . $rule['raw']];
  758. if (! empty($rule['enum'])) {
  759. $schema['enum'] = $rule['enum'];
  760. }
  761. $props[$field] = $schema;
  762. if ($rule['required']) {
  763. $required[] = $field;
  764. }
  765. }
  766. foreach ($info['params'] as $name => $p) {
  767. if (isset($props[$name])) {
  768. continue;
  769. }
  770. $schema = ['type' => $p['type']];
  771. if (! empty($p['enum'])) {
  772. $schema['enum'] = $p['enum'];
  773. }
  774. if ($p['default'] !== null) {
  775. $schema['default'] = $p['default'];
  776. }
  777. $props[$name] = $schema;
  778. }
  779. // 文档注释里写明的字段最权威,覆盖推断结果
  780. foreach ($documented as $name => $doc) {
  781. if ($doc['in'] === 'path') {
  782. continue;
  783. }
  784. $schema = ['type' => $doc['type']];
  785. if (! empty($doc['description'])) {
  786. $schema['description'] = $doc['description'];
  787. }
  788. if (! empty($doc['enum'])) {
  789. $schema['enum'] = $doc['enum'];
  790. }
  791. if (isset($doc['default'])) {
  792. $schema['default'] = $doc['default'];
  793. }
  794. if (isset($doc['example'])) {
  795. $schema['example'] = $doc['example'];
  796. }
  797. $props[$name] = $schema;
  798. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  799. $required[] = $name;
  800. }
  801. }
  802. [$props, $required] = nestDotted($props, $required);
  803. if ($props) {
  804. $body = ['type' => 'object', 'properties' => $props];
  805. if ($required) {
  806. $body['required'] = $required;
  807. }
  808. $op['requestBody'] = [
  809. 'required' => (bool) $required,
  810. 'content' => ['application/json' => ['schema' => $body]],
  811. ];
  812. }
  813. }
  814. // 响应。v2 与 v3 的信封不同:v2 是 {ok, message, data} 且业务失败也回 200,
  815. // v3 用真实状态码、Laravel 默认的 {data} 包装、错误体是 RFC 9457 Problem Details
  816. $data = ['type' => 'object'];
  817. if ($props = resourceSchema($info['resource'])) {
  818. $data = ['type' => 'object', 'properties' => $props];
  819. }
  820. if (isV3($route['uri'])) {
  821. // v3 用 Laravel Resource 的原生形状:列表 {data: [...], meta: {...}},单个 {data: {...}}
  822. //
  823. // 判断依据是控制器返回的是不是 `::collection()`,不能只看方法名叫不叫 index:
  824. // 单动作控制器的方法名是 __invoke,照样可以返回集合。
  825. $isList = $method === 'index' || ! empty($info['collection']);
  826. $success = $isList
  827. ? [
  828. 'type' => 'object',
  829. 'properties' => [
  830. 'data' => ['type' => 'array', 'items' => $data],
  831. 'meta' => metaSchema($info),
  832. ],
  833. ]
  834. : ['type' => 'object', 'properties' => ['data' => $data]];
  835. // 声明了 204 就不再输出默认的 200——控制器 return response()->noContent()
  836. // 的端点没有 200 这个口径,留着会让前端以为可以读 body
  837. $declared = $info['tags']['responses'] ?? [];
  838. $responses = isset($declared[204]) ? [] : [
  839. '200' => [
  840. 'description' => '成功',
  841. 'content' => ['application/json' => ['schema' => $success]],
  842. ],
  843. ];
  844. // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
  845. if (empty($info['tags']['unauthenticated'])) {
  846. $responses['401'] = ['$ref' => '../../main.yaml#/components/responses/ProblemUnauthorized'];
  847. }
  848. // 有入参才可能 422
  849. if (! empty($op['parameters']) || ! empty($op['requestBody'])) {
  850. $responses['422'] = ['$ref' => '../../main.yaml#/components/responses/ProblemValidation'];
  851. }
  852. // @responseStatus 声明的额外状态码。2xx 是另一种成功口径(如 201 Created),
  853. // 响应体与 200 同形;其余是错误,响应体是 Problem Details。
  854. foreach ($declared as $code => $desc) {
  855. $isSuccess = $code >= 200 && $code < 300;
  856. // 204 / 205 按 RFC 9110 MUST NOT 带消息体,不给 content
  857. if ((int) $code === 204 || (int) $code === 205) {
  858. $responses[(string) $code] = ['description' => $desc !== '' ? $desc : '成功,无响应体'];
  859. continue;
  860. }
  861. $responses[(string) $code] = $isSuccess
  862. ? [
  863. 'description' => $desc !== '' ? $desc : '成功',
  864. 'content' => ['application/json' => ['schema' => $success]],
  865. ]
  866. : [
  867. 'description' => $desc !== '' ? $desc : 'Problem Details',
  868. 'content' => ['application/problem+json' => [
  869. 'schema' => ['$ref' => '../../main.yaml#/components/schemas/ProblemDetails'],
  870. ]],
  871. ];
  872. }
  873. ksort($responses);
  874. $op['responses'] = $responses;
  875. return $op;
  876. }
  877. if ($method === 'index') {
  878. $data = [
  879. 'type' => 'object',
  880. 'properties' => [
  881. 'rows' => ['type' => 'array', 'items' => $data],
  882. 'count' => ['type' => 'integer'],
  883. ],
  884. ];
  885. }
  886. $op['responses'] = [
  887. '200' => [
  888. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  889. 'content' => ['application/json' => ['schema' => [
  890. 'type' => 'object',
  891. 'properties' => [
  892. 'ok' => ['type' => 'boolean'],
  893. 'message' => ['type' => 'string'],
  894. 'data' => $data,
  895. ],
  896. ]]],
  897. ],
  898. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  899. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  900. ];
  901. return $op;
  902. }
  903. /** v3 路由用新契约:真实状态码 + {data} 包装 + Problem Details */
  904. function isV3(string $uri): bool
  905. {
  906. return str_starts_with($uri, 'api/v3/');
  907. }
  908. function defaultSummary(string $method, string $uri): string
  909. {
  910. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  911. return match ($method) {
  912. 'index' => "列出 {$res}",
  913. 'show' => "获取单个 {$res}",
  914. 'store' => "新建 {$res}",
  915. 'update' => "更新 {$res}",
  916. 'destroy' => "删除 {$res}",
  917. default => "{$method} {$res}",
  918. };
  919. }
  920. /**
  921. * 取路径第一段当 tag。openapi-generator 按第一个 tag 分 Api 类,
  922. * 所以 tag 必须是资源名:`me/` 只是「当前用户」这个主体,要剥掉,
  923. * 否则 /v3/me/reactions、/v3/me/discussions 会全挤进一个 MeApi。
  924. * 单独的 /v3/me(当前用户档案)剥完为空,仍归 me。
  925. */
  926. function tagOf(string $uri): string
  927. {
  928. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  929. $path = preg_replace('#^me/(?=.)#', '', $path);
  930. $first = explode('/', $path)[0];
  931. return $first === '' ? 'misc' : $first;
  932. }
  933. /* ----------------------------------------------------------- 遍历路由 */
  934. $paths = [];
  935. foreach ($routes as $route) {
  936. $uri = $route['uri'];
  937. $action = (string) $route['action'];
  938. // 原来用「action 里有没有 @」当作「是不是控制器」,把**单动作控制器**
  939. // (invokable,action 就是类名、没有 @method)整条漏掉了,而且不报错。
  940. // buildOperation() 下游本来就有 __invoke 的兜底,这里放行即可。
  941. if (! str_starts_with($uri, 'api/') || $action === '' || $action === 'Closure') {
  942. continue;
  943. }
  944. if (! str_contains($action, '@') && ! str_contains($action, 'Controllers\\')) {
  945. continue;
  946. }
  947. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  948. continue;
  949. }
  950. foreach (explode('|', $route['method']) as $httpMethod) {
  951. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  952. continue;
  953. }
  954. $openapiPath = '/' . preg_replace('#^api/#', '', $uri);
  955. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  956. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  957. }
  958. }
  959. ksort($paths);
  960. /* --------------------------------------------------------- 合并 override */
  961. function deepMerge(array $base, array $over): array
  962. {
  963. foreach ($over as $k => $v) {
  964. // 列表值整体替换;含 $ref / oneOf / anyOf / allOf 的 schema 也整体替换,
  965. // 否则自动结果里的 `type: object` 会与 oneOf 并存,变成不合法 schema
  966. $replace = ! is_array($v)
  967. || array_is_list($v)
  968. || array_intersect(['$ref', 'oneOf', 'anyOf', 'allOf'], array_keys($v)) !== [];
  969. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! $replace)
  970. ? deepMerge($base[$k], $v)
  971. : $v;
  972. }
  973. return $base;
  974. }
  975. function pathSlug(string $path): string
  976. {
  977. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  978. }
  979. $overridden = 0;
  980. foreach ($paths as $path => $ops) {
  981. $file = $overrideDir . '/' . pathSlug($path) . '.yaml';
  982. if (is_file($file)) {
  983. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  984. $overridden++;
  985. }
  986. }
  987. /* ------------------------------------------------------------- 写文件 */
  988. foreach (glob($autoDir . '/*.yaml') ?: [] as $stale) {
  989. unlink($stale);
  990. }
  991. @mkdir($autoDir, 0o755, true);
  992. @mkdir($overrideDir, 0o755, true);
  993. $refs = [];
  994. foreach ($paths as $path => $ops) {
  995. $name = pathSlug($path) . '.yaml';
  996. file_put_contents(
  997. $autoDir . '/' . $name,
  998. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n" .
  999. // 同 main.yaml:security requirement 的值必须是数组,空数组会被 dump 成 { }
  1000. str_replace('bearerAuth: { }', 'bearerAuth: []', Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK))
  1001. );
  1002. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  1003. }
  1004. $main = [
  1005. 'openapi' => '3.0.3',
  1006. 'info' => [
  1007. 'title' => 'MINT API',
  1008. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n" .
  1009. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n" .
  1010. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  1011. 'version' => date('Y.n.j'),
  1012. ],
  1013. // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
  1014. 'servers' => [
  1015. ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
  1016. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
  1017. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  1018. ['url' => 'https://next.wikipali.org/api', 'description' => '生产预览'],
  1019. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  1020. ['url' => 'https://next.wikipali.cc/api', 'description' => '生产预览(中国)'],
  1021. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  1022. ],
  1023. 'components' => [
  1024. 'securitySchemes' => [
  1025. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  1026. ],
  1027. 'responses' => [
  1028. 'Unauthorized' => [
  1029. 'description' => '未登录或无权限',
  1030. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  1031. ],
  1032. 'ProblemUnauthorized' => [
  1033. 'description' => '未登录或无权限(v3)',
  1034. 'content' => ['application/problem+json' => [
  1035. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  1036. ]],
  1037. ],
  1038. 'ProblemValidation' => [
  1039. 'description' => '参数校验失败(v3)',
  1040. 'content' => ['application/problem+json' => [
  1041. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  1042. ]],
  1043. ],
  1044. 'ValidationError' => [
  1045. 'description' => '参数校验失败',
  1046. 'content' => ['application/json' => ['schema' => [
  1047. 'type' => 'object',
  1048. 'properties' => [
  1049. 'message' => ['type' => 'string'],
  1050. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  1051. ],
  1052. ]]],
  1053. ],
  1054. ],
  1055. 'schemas' => [
  1056. 'ProblemDetails' => [
  1057. 'type' => 'object',
  1058. 'description' => "RFC 9457 Problem Details,v3 端点的错误响应体。\n" .
  1059. "由 bootstrap/app.php 的异常处理器统一渲染,控制器不自己拼。\n" .
  1060. 'media type 是 application/problem+json。',
  1061. 'properties' => [
  1062. 'type' => ['type' => 'string', 'description' => '问题类型标识,形如 urn:problem:not-found', 'example' => 'urn:problem:not-found'],
  1063. 'title' => ['type' => 'string', 'description' => '稳定的英文摘要,同类问题恒定,供机器识别'],
  1064. 'status' => ['type' => 'integer'],
  1065. 'detail' => ['type' => 'string', 'description' => '面向人的文案,已本地化;5xx 在生产环境会省略以免泄露内部信息'],
  1066. 'instance' => ['type' => 'string', 'description' => '出问题的请求 URI'],
  1067. 'errors' => [
  1068. 'type' => 'object',
  1069. 'description' => '字段级校验错误,仅 422 时出现',
  1070. 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']],
  1071. ],
  1072. ],
  1073. 'required' => ['type', 'title', 'status'],
  1074. ],
  1075. 'PaginationMeta' => [
  1076. 'type' => 'object',
  1077. 'description' => "v3 列表接口的分页信息,由 Laravel paginator 生成。\n" .
  1078. "刻意不含 links / path:那些是 APP_URL 拼出的绝对地址,反代下会拼错,前端也用不到。\n" .
  1079. '手工分页的接口会附加自己的字段(如 has_more / first_para / page_size)。',
  1080. 'properties' => [
  1081. 'current_page' => ['type' => 'integer'],
  1082. 'per_page' => ['type' => 'integer'],
  1083. 'total' => ['type' => 'integer'],
  1084. 'last_page' => ['type' => 'integer'],
  1085. 'from' => ['type' => 'integer', 'nullable' => true],
  1086. 'to' => ['type' => 'integer', 'nullable' => true],
  1087. ],
  1088. // 手工分页的接口未必有 per_page(例如按字节切页的阅读接口用 page_size)
  1089. 'required' => ['current_page', 'total'],
  1090. ],
  1091. 'Envelope' => [
  1092. 'type' => 'object',
  1093. 'properties' => [
  1094. 'ok' => ['type' => 'boolean'],
  1095. 'message' => ['type' => 'string'],
  1096. 'data' => ['description' => '业务数据,形状随接口而定'],
  1097. ],
  1098. ],
  1099. ],
  1100. ],
  1101. 'security' => [['bearerAuth' => []]],
  1102. 'paths' => $refs,
  1103. ];
  1104. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  1105. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  1106. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  1107. file_put_contents(
  1108. $protocol . '/main.yaml',
  1109. "# 由 openapi/scripts/generate.php 生成,请勿手改\n" . $mainYaml
  1110. );
  1111. printf(
  1112. "生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  1113. count($paths),
  1114. array_sum(array_map('count', $paths)),
  1115. $overridden
  1116. );