generate.php 49 KB

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