2
0

generate.php 47 KB

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