generate.php 44 KB

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