generate.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222
  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. // 全是字符串字面量('question'|'term'|…)→ 字符串枚举
  561. $literals = array_filter($concrete, fn ($m) => preg_match("/^'[^']*'$/", $m));
  562. if ($concrete && count($literals) === count($concrete)) {
  563. $schema = ['type' => 'string', 'enum' => array_map(fn ($m) => trim($m, "'"), array_values($concrete))];
  564. if ($nullable) {
  565. $schema['nullable'] = true;
  566. }
  567. return $schema;
  568. }
  569. $type = $concrete ? $concrete[0] : 'mixed';
  570. }
  571. $type = trim($type);
  572. // 嵌套 array{...}
  573. if (preg_match('/^array\s*\{(.*)$/s', $type, $m)) {
  574. $innerText = extractBraced($m[1]);
  575. $schema = ['type' => 'object'];
  576. if ($innerText !== null && ($p = shapeToProperties($innerText))) {
  577. $schema['properties'] = $p;
  578. }
  579. if ($nullable) {
  580. $schema['nullable'] = true;
  581. }
  582. return $schema;
  583. }
  584. // 列表:array<T> / T[] / list<T>
  585. if (preg_match('/^(?:array|list)\s*<(.+)>$/s', $type, $m)) {
  586. $args = splitTopLevel($m[1]);
  587. $itemType = trim(end($args));
  588. $schema = ['type' => 'array', 'items' => phpTypeToSchema($itemType)];
  589. if ($nullable) {
  590. $schema['nullable'] = true;
  591. }
  592. return $schema;
  593. }
  594. if (str_ends_with($type, '[]')) {
  595. $schema = ['type' => 'array', 'items' => phpTypeToSchema(substr($type, 0, -2))];
  596. if ($nullable) {
  597. $schema['nullable'] = true;
  598. }
  599. return $schema;
  600. }
  601. $schema = match (strtolower($type)) {
  602. 'int', 'integer' => ['type' => 'integer'],
  603. 'float', 'double' => ['type' => 'number'],
  604. 'bool', 'boolean' => ['type' => 'boolean'],
  605. 'array' => ['type' => 'array', 'items' => ['type' => 'string']],
  606. 'object', 'mixed', '' => ['type' => 'object'],
  607. default => ['type' => 'string'],
  608. };
  609. if ($nullable) {
  610. $schema['nullable'] = true;
  611. }
  612. return $schema;
  613. }
  614. function guessType(string $field): string
  615. {
  616. if (str_ends_with($field, '_at') || $field === 'created' || $field === 'updated') {
  617. return 'string';
  618. }
  619. if (preg_match('/^(is_|has_|can_)/', $field)) {
  620. return 'boolean';
  621. }
  622. if (preg_match('/(_id|_count|_number|^count$|^id$|^status$|^type$|^level$|^progress$)$/', $field)) {
  623. return 'integer';
  624. }
  625. return 'string';
  626. }
  627. /**
  628. * v3 列表响应的 meta schema。
  629. *
  630. * 默认是 Eloquent 分页的 PaginationMeta;控制器 docblock 里写了 `@meta` 标签时
  631. * (手工分页,如游标式阅读接口),按声明生成专用 schema,字段名与类型都不再猜测。
  632. *
  633. * @param array $info parseController 的返回
  634. * @return array meta 的 OpenAPI schema
  635. */
  636. function metaSchema(array $info): array
  637. {
  638. $meta = $info['tags']['meta'] ?? [];
  639. if (empty($meta)) {
  640. return ['$ref' => '../../main.yaml#/components/schemas/PaginationMeta'];
  641. }
  642. $properties = [];
  643. foreach ($meta as $name => $field) {
  644. $property = ['type' => $field['type']];
  645. if (! empty($field['description'])) {
  646. $property['description'] = $field['description'];
  647. }
  648. $properties[$name] = $property;
  649. }
  650. return ['type' => 'object', 'properties' => $properties];
  651. }
  652. /* ------------------------------------------------------- 生成 operation */
  653. $listParams = Yaml::parseFile($protocol . '/resources/list_query.yaml');
  654. function buildOperation(array $route, string $httpMethod): array
  655. {
  656. global $listParams;
  657. [$class, $method] = array_pad(explode('@', $route['action']), 2, '__invoke');
  658. $info = parseController($class, $method);
  659. $short = preg_replace('/^App\\\\Http\\\\Controllers\\\\/', '', $class);
  660. $tag = tagOf($route['uri']);
  661. $op = [
  662. 'summary' => $info['summary'] ?: defaultSummary($method, $route['uri']),
  663. 'tags' => [$tag],
  664. 'operationId' => strtolower($httpMethod) . '_' . preg_replace('/[^a-zA-Z0-9]+/', '_', $route['uri']),
  665. 'description' => trim(($info['description'] ?? '') . "\n\n实现:`{$short}@{$method}`"),
  666. ];
  667. if (! empty($info['tags']['deprecated'])) {
  668. $op['deprecated'] = true;
  669. }
  670. // v3 的鉴权按路由中间件逐个写准(v2 沿用全局 security,不动):
  671. // 挂了 auth.v3 → 必须带 token;没挂 → 匿名可用,带了 token 就按登录用户处理
  672. // (讨论列表的可见性、tally 的「我点过没有」),所以是「可选」。生成的客户端据此
  673. // 决定发不发 Authorization——同一路径读公开、写要登录(middlewareFor)也能分清。
  674. if (str_starts_with($route['uri'], 'api/v3/')) {
  675. $op['security'] = in_array('auth.v3', $route['middleware'] ?? [], true)
  676. ? [['bearerAuth' => []]]
  677. : [[], ['bearerAuth' => []]];
  678. }
  679. $documented = $info['tags']['params'] ?? [];
  680. $params = [];
  681. // 路径参数
  682. if (preg_match_all('/\{(\w+)\??\}/', $route['uri'], $m)) {
  683. foreach ($m[1] as $name) {
  684. $doc = $documented[$name] ?? null;
  685. $param = [
  686. 'name' => $name,
  687. 'in' => 'path',
  688. 'required' => true,
  689. 'schema' => ['type' => $doc['type'] ?? 'string'],
  690. ];
  691. if (! empty($doc['description'])) {
  692. $param['description'] = $doc['description'];
  693. }
  694. if (! empty($doc['enum'])) {
  695. $param['schema']['enum'] = $doc['enum'];
  696. }
  697. if (isset($doc['example'])) {
  698. $param['example'] = $doc['example'];
  699. }
  700. $params[] = $param;
  701. }
  702. }
  703. // 查询参数:文档注释里写明的优先,其余由控制器源码推断
  704. $isRead = in_array($httpMethod, ['GET', 'DELETE'], true);
  705. $names = array_keys($info['params']);
  706. foreach ($documented as $name => $doc) {
  707. if ($doc['in'] === 'query' && ! in_array($name, $names, true)) {
  708. $names[] = $name;
  709. }
  710. }
  711. foreach ($names as $name) {
  712. $p = $info['params'][$name] ?? ['type' => 'string', 'default' => null];
  713. $doc = $documented[$name] ?? null;
  714. if (preg_match('/\{' . preg_quote($name, '/') . '\??\}/', $route['uri'])) {
  715. continue;
  716. }
  717. // 文档注释把它标成 body 参数时,不再当查询参数输出
  718. if ($doc && $doc['in'] !== 'query') {
  719. continue;
  720. }
  721. if (! $isRead && ! $doc) {
  722. continue;
  723. }
  724. if (! $isRead) {
  725. continue;
  726. }
  727. $schema = ['type' => $doc['type'] ?? $p['type']];
  728. $enum = $doc['enum'] ?? $p['enum'] ?? null;
  729. if ($enum) {
  730. $schema['enum'] = $enum;
  731. }
  732. $default = $doc['default'] ?? $p['default'] ?? null;
  733. if ($default !== null) {
  734. $schema['default'] = $default;
  735. }
  736. $param = ['name' => $name, 'in' => 'query', 'schema' => $schema];
  737. if (! empty($doc['description'])) {
  738. $param['description'] = $doc['description'];
  739. }
  740. if (! empty($doc['required'])) {
  741. $param['required'] = true;
  742. }
  743. if (isset($doc['example'])) {
  744. $param['example'] = $doc['example'];
  745. }
  746. $params[] = $param;
  747. }
  748. // v2 列表的通用参数(search/order/dir/limit/offset)只属于 v2;
  749. // v3 的分页是 page/per_page,且参数一律要在文档注释里写明,不做兜底注入
  750. if ($method === 'index' && $httpMethod === 'GET' && ! isV3($route['uri'])) {
  751. $known = array_column($params, 'name');
  752. foreach ($listParams as $lp) {
  753. if (! in_array($lp['name'], $known, true)) {
  754. $params[] = $lp;
  755. }
  756. }
  757. }
  758. if ($params) {
  759. $op['parameters'] = $params;
  760. }
  761. // 请求体
  762. if (! $isRead) {
  763. $props = [];
  764. $required = [];
  765. foreach ($info['validate'] as $field => $rule) {
  766. $schema = ['type' => $rule['type'], 'description' => '规则:' . $rule['raw']];
  767. if (! empty($rule['enum'])) {
  768. $schema['enum'] = $rule['enum'];
  769. }
  770. $props[$field] = $schema;
  771. if ($rule['required']) {
  772. $required[] = $field;
  773. }
  774. }
  775. foreach ($info['params'] as $name => $p) {
  776. if (isset($props[$name])) {
  777. continue;
  778. }
  779. $schema = ['type' => $p['type']];
  780. if (! empty($p['enum'])) {
  781. $schema['enum'] = $p['enum'];
  782. }
  783. if ($p['default'] !== null) {
  784. $schema['default'] = $p['default'];
  785. }
  786. $props[$name] = $schema;
  787. }
  788. // 文档注释里写明的字段最权威,覆盖推断结果
  789. foreach ($documented as $name => $doc) {
  790. if ($doc['in'] === 'path') {
  791. continue;
  792. }
  793. $schema = ['type' => $doc['type']];
  794. if (! empty($doc['description'])) {
  795. $schema['description'] = $doc['description'];
  796. }
  797. if (! empty($doc['enum'])) {
  798. $schema['enum'] = $doc['enum'];
  799. }
  800. if (isset($doc['default'])) {
  801. $schema['default'] = $doc['default'];
  802. }
  803. if (isset($doc['example'])) {
  804. $schema['example'] = $doc['example'];
  805. }
  806. $props[$name] = $schema;
  807. if (! empty($doc['required']) && ! in_array($name, $required, true)) {
  808. $required[] = $name;
  809. }
  810. }
  811. [$props, $required] = nestDotted($props, $required);
  812. if ($props) {
  813. $body = ['type' => 'object', 'properties' => $props];
  814. if ($required) {
  815. $body['required'] = $required;
  816. }
  817. $op['requestBody'] = [
  818. 'required' => (bool) $required,
  819. 'content' => ['application/json' => ['schema' => $body]],
  820. ];
  821. }
  822. }
  823. // 响应。v2 与 v3 的信封不同:v2 是 {ok, message, data} 且业务失败也回 200,
  824. // v3 用真实状态码、Laravel 默认的 {data} 包装、错误体是 RFC 9457 Problem Details
  825. $data = ['type' => 'object'];
  826. if ($props = resourceSchema($info['resource'])) {
  827. $data = ['type' => 'object', 'properties' => $props];
  828. }
  829. if (isV3($route['uri'])) {
  830. // v3 用 Laravel Resource 的原生形状:列表 {data: [...], meta: {...}},单个 {data: {...}}
  831. //
  832. // 判断依据是控制器返回的是不是 `::collection()`,不能只看方法名叫不叫 index:
  833. // 单动作控制器的方法名是 __invoke,照样可以返回集合。
  834. $isList = $method === 'index' || ! empty($info['collection']);
  835. $success = $isList
  836. ? [
  837. 'type' => 'object',
  838. 'properties' => [
  839. 'data' => ['type' => 'array', 'items' => $data],
  840. 'meta' => metaSchema($info),
  841. ],
  842. ]
  843. : ['type' => 'object', 'properties' => ['data' => $data]];
  844. // 声明了 204 就不再输出默认的 200——控制器 return response()->noContent()
  845. // 的端点没有 200 这个口径,留着会让前端以为可以读 body
  846. $declared = $info['tags']['responses'] ?? [];
  847. $responses = isset($declared[204]) ? [] : [
  848. '200' => [
  849. 'description' => '成功',
  850. 'content' => ['application/json' => ['schema' => $success]],
  851. ],
  852. ];
  853. // 无鉴权的端点用 @unauthenticated 标注,就不再挂 401
  854. if (empty($info['tags']['unauthenticated'])) {
  855. $responses['401'] = ['$ref' => '../../main.yaml#/components/responses/ProblemUnauthorized'];
  856. }
  857. // 有入参才可能 422
  858. if (! empty($op['parameters']) || ! empty($op['requestBody'])) {
  859. $responses['422'] = ['$ref' => '../../main.yaml#/components/responses/ProblemValidation'];
  860. }
  861. // @responseStatus 声明的额外状态码。2xx 是另一种成功口径(如 201 Created),
  862. // 响应体与 200 同形;其余是错误,响应体是 Problem Details。
  863. foreach ($declared as $code => $desc) {
  864. $isSuccess = $code >= 200 && $code < 300;
  865. // 204 / 205 按 RFC 9110 MUST NOT 带消息体,不给 content
  866. if ((int) $code === 204 || (int) $code === 205) {
  867. $responses[(string) $code] = ['description' => $desc !== '' ? $desc : '成功,无响应体'];
  868. continue;
  869. }
  870. $responses[(string) $code] = $isSuccess
  871. ? [
  872. 'description' => $desc !== '' ? $desc : '成功',
  873. 'content' => ['application/json' => ['schema' => $success]],
  874. ]
  875. : [
  876. 'description' => $desc !== '' ? $desc : 'Problem Details',
  877. 'content' => ['application/problem+json' => [
  878. 'schema' => ['$ref' => '../../main.yaml#/components/schemas/ProblemDetails'],
  879. ]],
  880. ];
  881. }
  882. ksort($responses);
  883. $op['responses'] = $responses;
  884. return $op;
  885. }
  886. if ($method === 'index') {
  887. $data = [
  888. 'type' => 'object',
  889. 'properties' => [
  890. 'rows' => ['type' => 'array', 'items' => $data],
  891. 'count' => ['type' => 'integer'],
  892. ],
  893. ];
  894. }
  895. $op['responses'] = [
  896. '200' => [
  897. 'description' => '成功。业务失败时 HTTP 仍可能为 200,以 ok 字段为准。',
  898. 'content' => ['application/json' => ['schema' => [
  899. 'type' => 'object',
  900. 'properties' => [
  901. 'ok' => ['type' => 'boolean'],
  902. 'message' => ['type' => 'string'],
  903. 'data' => $data,
  904. ],
  905. ]]],
  906. ],
  907. '401' => ['$ref' => '../../main.yaml#/components/responses/Unauthorized'],
  908. '422' => ['$ref' => '../../main.yaml#/components/responses/ValidationError'],
  909. ];
  910. return $op;
  911. }
  912. /** v3 路由用新契约:真实状态码 + {data} 包装 + Problem Details */
  913. function isV3(string $uri): bool
  914. {
  915. return str_starts_with($uri, 'api/v3/');
  916. }
  917. function defaultSummary(string $method, string $uri): string
  918. {
  919. $res = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  920. return match ($method) {
  921. 'index' => "列出 {$res}",
  922. 'show' => "获取单个 {$res}",
  923. 'store' => "新建 {$res}",
  924. 'update' => "更新 {$res}",
  925. 'destroy' => "删除 {$res}",
  926. default => "{$method} {$res}",
  927. };
  928. }
  929. /**
  930. * 取路径第一段当 tag。openapi-generator 按第一个 tag 分 Api 类,
  931. * 所以 tag 必须是资源名:`me/` 只是「当前用户」这个主体,要剥掉,
  932. * 否则 /v3/me/reactions、/v3/me/discussions 会全挤进一个 MeApi。
  933. * 单独的 /v3/me(当前用户档案)剥完为空,仍归 me。
  934. */
  935. function tagOf(string $uri): string
  936. {
  937. $path = preg_replace('#^api/(v2|v3|ops)/#', '', $uri);
  938. $path = preg_replace('#^me/(?=.)#', '', $path);
  939. $first = explode('/', $path)[0];
  940. return $first === '' ? 'misc' : $first;
  941. }
  942. /* ----------------------------------------------------------- 遍历路由 */
  943. $paths = [];
  944. foreach ($routes as $route) {
  945. $uri = $route['uri'];
  946. $action = (string) $route['action'];
  947. // 原来用「action 里有没有 @」当作「是不是控制器」,把**单动作控制器**
  948. // (invokable,action 就是类名、没有 @method)整条漏掉了,而且不报错。
  949. // buildOperation() 下游本来就有 __invoke 的兜底,这里放行即可。
  950. if (! str_starts_with($uri, 'api/') || $action === '' || $action === 'Closure') {
  951. continue;
  952. }
  953. if (! str_contains($action, '@') && ! str_contains($action, 'Controllers\\')) {
  954. continue;
  955. }
  956. if (str_contains($route['action'], 'Laravel\\') || str_contains($route['uri'], 'sanctum')) {
  957. continue;
  958. }
  959. foreach (explode('|', $route['method']) as $httpMethod) {
  960. if (in_array($httpMethod, ['HEAD', 'OPTIONS'], true)) {
  961. continue;
  962. }
  963. $openapiPath = '/' . preg_replace('#^api/#', '', $uri);
  964. $openapiPath = preg_replace('/\{(\w+)\?\}/', '{$1}', $openapiPath);
  965. $paths[$openapiPath][strtolower($httpMethod)] = buildOperation($route, $httpMethod);
  966. }
  967. }
  968. ksort($paths);
  969. /* --------------------------------------------------------- 合并 override */
  970. function deepMerge(array $base, array $over): array
  971. {
  972. foreach ($over as $k => $v) {
  973. // 列表值整体替换;含 $ref / oneOf / anyOf / allOf 的 schema 也整体替换,
  974. // 否则自动结果里的 `type: object` 会与 oneOf 并存,变成不合法 schema
  975. $replace = ! is_array($v)
  976. || array_is_list($v)
  977. || array_intersect(['$ref', 'oneOf', 'anyOf', 'allOf'], array_keys($v)) !== [];
  978. $base[$k] = (is_array($v) && isset($base[$k]) && is_array($base[$k]) && ! $replace)
  979. ? deepMerge($base[$k], $v)
  980. : $v;
  981. }
  982. return $base;
  983. }
  984. function pathSlug(string $path): string
  985. {
  986. return trim(preg_replace('/[^a-zA-Z0-9]+/', '-', $path), '-') ?: 'root';
  987. }
  988. $overridden = 0;
  989. foreach ($paths as $path => $ops) {
  990. $file = $overrideDir . '/' . pathSlug($path) . '.yaml';
  991. if (is_file($file)) {
  992. $paths[$path] = deepMerge($ops, Yaml::parseFile($file) ?: []);
  993. $overridden++;
  994. }
  995. }
  996. /* ------------------------------------------------------------- 写文件 */
  997. foreach (glob($autoDir . '/*.yaml') ?: [] as $stale) {
  998. unlink($stale);
  999. }
  1000. @mkdir($autoDir, 0o755, true);
  1001. @mkdir($overrideDir, 0o755, true);
  1002. $refs = [];
  1003. foreach ($paths as $path => $ops) {
  1004. $name = pathSlug($path) . '.yaml';
  1005. file_put_contents(
  1006. $autoDir . '/' . $name,
  1007. "# 由 openapi/scripts/generate.php 生成,请勿手改;补充写到 overrides/{$name}\n" .
  1008. // 同 main.yaml:security requirement 的值必须是数组,空数组会被 dump 成 { }
  1009. str_replace('bearerAuth: { }', 'bearerAuth: []', Yaml::dump($ops, 12, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK))
  1010. );
  1011. $refs[$path] = ['$ref' => "./resources/auto/{$name}"];
  1012. }
  1013. $main = [
  1014. 'openapi' => '3.0.3',
  1015. 'info' => [
  1016. 'title' => 'MINT API',
  1017. 'description' => "International Academy Of Pali Tipitaka(国际巴利三藏学院)\n\n" .
  1018. "由 `php openapi/scripts/generate.php` 依据 api-v13 的路由与控制器源码生成。\n" .
  1019. "响应统一封装为 `{ok, message, data}`;`ok=false` 时 `message` 为错误信息。",
  1020. // 固定值,不要用日期或提交号:规格完全由代码决定,「哪一版」看 git 就够了。
  1021. // 曾用 date('Y.n.j'),结果隔天重跑就让 main.yaml 与 api-test 生成客户端的 160 个文件
  1022. // 全部出现只改版本行的 diff,CI 的 `generate.php && git diff --exit-code` 也会无故失败。
  1023. 'version' => '1.0.0',
  1024. ],
  1025. // 第一项是 Swagger UI 的默认选择,放同源代理,避免 Try it out 误打生产
  1026. 'servers' => [
  1027. ['url' => '/api', 'description' => '同源(预览页里 Try it out 走 vite 代理,避免跨域)'],
  1028. ['url' => 'http://127.0.0.1:8000/api', 'description' => '本地开发(直连,浏览器里会被 CORS 挡住)'],
  1029. ['url' => 'https://staging.wikipali.org/api', 'description' => '测试'],
  1030. ['url' => 'https://next.wikipali.org/api', 'description' => '生产预览'],
  1031. ['url' => 'https://www.wikipali.org/api', 'description' => '生产'],
  1032. ['url' => 'https://next.wikipali.cc/api', 'description' => '生产预览(中国)'],
  1033. ['url' => 'https://www.wikipali.cc/api', 'description' => '生产(中国)'],
  1034. ],
  1035. 'components' => [
  1036. 'securitySchemes' => [
  1037. 'bearerAuth' => ['type' => 'http', 'scheme' => 'bearer', 'description' => '用户 token 或 access token'],
  1038. ],
  1039. 'responses' => [
  1040. 'Unauthorized' => [
  1041. 'description' => '未登录或无权限',
  1042. 'content' => ['application/json' => ['schema' => ['$ref' => '#/components/schemas/Envelope']]],
  1043. ],
  1044. 'ProblemUnauthorized' => [
  1045. 'description' => '未登录或无权限(v3)',
  1046. 'content' => ['application/problem+json' => [
  1047. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  1048. ]],
  1049. ],
  1050. 'ProblemValidation' => [
  1051. 'description' => '参数校验失败(v3)',
  1052. 'content' => ['application/problem+json' => [
  1053. 'schema' => ['$ref' => '#/components/schemas/ProblemDetails'],
  1054. ]],
  1055. ],
  1056. 'ValidationError' => [
  1057. 'description' => '参数校验失败',
  1058. 'content' => ['application/json' => ['schema' => [
  1059. 'type' => 'object',
  1060. 'properties' => [
  1061. 'message' => ['type' => 'string'],
  1062. 'errors' => ['type' => 'object', 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']]],
  1063. ],
  1064. ]]],
  1065. ],
  1066. ],
  1067. 'schemas' => [
  1068. 'ProblemDetails' => [
  1069. 'type' => 'object',
  1070. 'description' => "RFC 9457 Problem Details,v3 端点的错误响应体。\n" .
  1071. "由 bootstrap/app.php 的异常处理器统一渲染,控制器不自己拼。\n" .
  1072. 'media type 是 application/problem+json。',
  1073. 'properties' => [
  1074. 'type' => ['type' => 'string', 'description' => '问题类型标识,形如 urn:problem:not-found', 'example' => 'urn:problem:not-found'],
  1075. 'title' => ['type' => 'string', 'description' => '稳定的英文摘要,同类问题恒定,供机器识别'],
  1076. 'status' => ['type' => 'integer'],
  1077. 'detail' => ['type' => 'string', 'description' => '面向人的文案,已本地化;5xx 在生产环境会省略以免泄露内部信息'],
  1078. 'instance' => ['type' => 'string', 'description' => '出问题的请求 URI'],
  1079. 'errors' => [
  1080. 'type' => 'object',
  1081. 'description' => '字段级校验错误,仅 422 时出现',
  1082. 'additionalProperties' => ['type' => 'array', 'items' => ['type' => 'string']],
  1083. ],
  1084. ],
  1085. 'required' => ['type', 'title', 'status'],
  1086. ],
  1087. 'PaginationMeta' => [
  1088. 'type' => 'object',
  1089. 'description' => "v3 列表接口的分页信息,由 Laravel paginator 生成。\n" .
  1090. "刻意不含 links / path:那些是 APP_URL 拼出的绝对地址,反代下会拼错,前端也用不到。\n" .
  1091. '手工分页的接口会附加自己的字段(如 has_more / first_para / page_size)。',
  1092. 'properties' => [
  1093. 'current_page' => ['type' => 'integer'],
  1094. 'per_page' => ['type' => 'integer'],
  1095. 'total' => ['type' => 'integer'],
  1096. 'last_page' => ['type' => 'integer'],
  1097. 'from' => ['type' => 'integer', 'nullable' => true],
  1098. 'to' => ['type' => 'integer', 'nullable' => true],
  1099. ],
  1100. // 手工分页的接口未必有 per_page(例如按字节切页的阅读接口用 page_size)
  1101. 'required' => ['current_page', 'total'],
  1102. ],
  1103. 'Envelope' => [
  1104. 'type' => 'object',
  1105. 'properties' => [
  1106. 'ok' => ['type' => 'boolean'],
  1107. 'message' => ['type' => 'string'],
  1108. 'data' => ['description' => '业务数据,形状随接口而定'],
  1109. ],
  1110. ],
  1111. ],
  1112. ],
  1113. 'security' => [['bearerAuth' => []]],
  1114. 'paths' => $refs,
  1115. ];
  1116. $mainYaml = Yaml::dump($main, 8, 2, Yaml::DUMP_MULTI_LINE_LITERAL_BLOCK);
  1117. // 空数组被 dump 成 { },而 security requirement 的值必须是数组
  1118. $mainYaml = str_replace('bearerAuth: { }', 'bearerAuth: []', $mainYaml);
  1119. file_put_contents(
  1120. $protocol . '/main.yaml',
  1121. "# 由 openapi/scripts/generate.php 生成,请勿手改\n" . $mainYaml
  1122. );
  1123. printf(
  1124. "生成 %d 个 path,%d 个 operation,%d 个 path 应用了 overrides\n",
  1125. count($paths),
  1126. array_sum(array_map('count', $paths)),
  1127. $overridden
  1128. );