diff --git a/CLAUDE.md b/CLAUDE.md index b02f07d..bd1ef60 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,7 +15,7 @@ composer analyse # PHPStan 静态分析(-l 0,仅 src/) composer cs-fix # php-cs-fixer 格式化 src 和 tests ``` -CI 矩阵为 PHP 8.2/8.3/8.4 + Hyperf 3.2(pin `hyperf/di:3.2.*` + `tangwei/dto:dev-master`)。本包通过 `tangwei/dto ~3.2` 传递依赖 Hyperf ~3.2,不兼容 Hyperf 3.1。 +CI 矩阵覆盖 PHP 8.1/8.2/8.3/8.4 + Hyperf 3.1,以及 PHP 8.2/8.3/8.4 + Hyperf 3.2(pin 对应 `hyperf/di` + `tangwei/dto:dev-master`)。本包通过 `tangwei/dto ~4.0.0` 传递依赖 Hyperf 3.1/3.2。 ## 架构核心 diff --git a/README.md b/README.md index 1177b95..e4f4e8b 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ [![Latest Stable Version](https://img.shields.io/packagist/v/tangwei/apidocs)](https://packagist.org/packages/tangwei/apidocs) [![Total Downloads](https://img.shields.io/packagist/dt/tangwei/apidocs)](https://packagist.org/packages/tangwei/apidocs) [![License](https://img.shields.io/packagist/l/tangwei/apidocs)](https://github.com/tw2066/api-docs) -[![PHP Version](https://img.shields.io/badge/php-%3E%3D8.2-blue)](https://www.php.net) +[![PHP Version](https://img.shields.io/badge/php-%3E%3D8.1-blue)](https://www.php.net) [English](./README_EN.md) | 中文 @@ -22,14 +22,18 @@ ## 📋 环境要求 -- PHP >= 8.2 -- Hyperf ~3.2 +- PHP >= 8.1 +- Hyperf ~3.1 或 ~3.2 +- DTO ~4.0.0 - Swoole >= 5.0 或 Swow ## 💡 使用须知 - 控制器方法尽可能返回具体的类(包含简单类型),这样能更好地生成文档 - 当返回类无法满足需求时,可使用 `#[ApiResponse]` 注解补充 +- DTO 4.0 输入只接受字段 primaryKey:有 `#[JSONField]` 时使用其外部别名,否则使用 PHP 属性名;private/protected 属性需要正常业务 setter 才能接收输入,readonly/static 属性不参与输入映射。带 `#[Required]` 的字段例外:验证先于映射执行,文档仍将其列为请求必填字段 +- 接口属性建议通过 DTO `classMap` 指定具体类;未指定或运行时动态映射时,文档降级为通用 `object` +- 升级到 DTO 4.0 后,建议清理并重新生成 `runtime/container/proxy/` 中的代理文件 ## 📦 安装 diff --git a/README_EN.md b/README_EN.md index 0cab9c6..c3c49e2 100644 --- a/README_EN.md +++ b/README_EN.md @@ -3,7 +3,7 @@ [![Latest Stable Version](https://img.shields.io/packagist/v/tangwei/apidocs)](https://packagist.org/packages/tangwei/apidocs) [![Total Downloads](https://img.shields.io/packagist/dt/tangwei/apidocs)](https://packagist.org/packages/tangwei/apidocs) [![License](https://img.shields.io/packagist/l/tangwei/apidocs)](https://github.com/tw2066/api-docs) -[![PHP Version](https://img.shields.io/badge/php-%3E%3D8.2-blue)](https://www.php.net) +[![PHP Version](https://img.shields.io/badge/php-%3E%3D8.1-blue)](https://www.php.net) English | [中文](./README.md) @@ -22,8 +22,9 @@ Automatic Swagger/OpenAPI documentation generator for the [Hyperf](https://githu ## 📋 Requirements -- PHP >= 8.2 -- Hyperf ~3.2 +- PHP >= 8.1 +- Hyperf ~3.1 or ~3.2 +- DTO ~4.0.0 - Swoole >= 5.0 or Swow ## 💡 Important Notes @@ -31,6 +32,9 @@ Automatic Swagger/OpenAPI documentation generator for the [Hyperf](https://githu - Union types are not supported for parameter mapping to PHP classes - Controller methods should return specific types (including simple types) for better documentation generation - Use `#[ApiResponse]` annotation when return types cannot fully express the response structure +- DTO 4.0 input uses each field's primaryKey: the external alias when `#[JSONField]` is present, otherwise the PHP property name; private/protected properties require a regular business setter, while readonly/static properties are excluded from input mapping. Fields marked `#[Required]` are the exception: validation runs before mapping, so they remain required request fields in the documentation +- For interface properties, configure a concrete class through the DTO `classMap`; unresolved or runtime-dynamic mappings fall back to a generic `object` schema +- After upgrading to DTO 4.0, clear and regenerate the proxy files in `runtime/container/proxy/` ## 📦 Installation diff --git a/example/Controller/DemoController.php b/example/Controller/DemoController.php index a349c33..0079517 100644 --- a/example/Controller/DemoController.php +++ b/example/Controller/DemoController.php @@ -4,18 +4,12 @@ namespace HyperfExample\ApiDocs\Controller; -use App\Annotation\TestAnnotation; -use App\DTO\Response\DemoResponse; -use App\DTO\User; -use App\Model\Activity; -use App\Service\GoodsInfoService; use Hyperf\ApiDocs\Annotation\Api; use Hyperf\ApiDocs\Annotation\ApiFormData; use Hyperf\ApiDocs\Annotation\ApiHeader; use Hyperf\ApiDocs\Annotation\ApiOperation; use Hyperf\ApiDocs\Annotation\ApiResponse; use Hyperf\ApiDocs\Annotation\ApiSecurity; -use Hyperf\Database\Model\Relations\HasOne; use Hyperf\DTO\Annotation\Contracts\RequestBody; use Hyperf\DTO\Annotation\Contracts\RequestFormData; use Hyperf\DTO\Annotation\Contracts\RequestHeader; @@ -28,9 +22,7 @@ use Hyperf\HttpServer\Annotation\PatchMapping; use Hyperf\HttpServer\Annotation\PostMapping; use Hyperf\HttpServer\Annotation\PutMapping; -use Hyperf\HttpServer\Contract\RequestInterface; use HyperfExample\ApiDocs\DTO\Address; -use HyperfExample\ApiDocs\DTO\Address_1; use HyperfExample\ApiDocs\DTO\DataType; use HyperfExample\ApiDocs\DTO\Header\DemoToken; use HyperfExample\ApiDocs\DTO\PageQuery; @@ -43,25 +35,17 @@ use HyperfExample\ApiDocs\DTO\Response\CodeResponse; use HyperfExample\ApiDocs\DTO\Response\Contact; use HyperfExample\ApiDocs\DTO\Response\Page; +use HyperfExample\ApiDocs\DTO\Response\ReadonlyResponse; #[Controller(prefix: '/exampleDemo')] #[Api(tags: 'demo管理', position: 1)] -#[ApiHeader('apiHeader')] +#[ApiHeader(name: 'apiHeader')] class DemoController { - public int $a = 1; - - public array $a2 = []; - - public function __construct(protected RequestInterface $request) - { - } - #[ApiOperation(summary: '查询测试')] - #[GetMapping(path: 'api')] - public function api(#[RequestQuery] #[Valid] DemoQuery $request): DataType + #[GetMapping(path: 'detail')] + public function detail(#[RequestQuery] #[Valid] DemoQuery $request): DataType { - dump($request); return new DataType(); } @@ -69,169 +53,151 @@ public function api(#[RequestQuery] #[Valid] DemoQuery $request): DataType * @param DemoQuery[] $request */ #[ApiOperation(summary: '查询测试POST Arr')] - #[PostMapping(path: 'apiArr')] - public function apiArr(#[RequestBody] #[Valid] array $request, Address $address): array + #[PostMapping(path: 'list')] + public function list(#[RequestBody] #[Valid] array $request): array { - dump($request); return $request; } #[ApiOperation(summary: '查询测试POST')] - #[PostMapping(path: 'api')] + #[PostMapping(path: 'create')] #[ApiHeader(name: 'test', required: true, type: 'string')] - // #[ApiFormData(name: 'photo', required: true, format: 'binary')] - public function apiPost(#[RequestBody] #[Valid] DemoQuery $request): DemoQuery + public function create(#[RequestBody] #[Valid] DemoQuery $request): DemoQuery { - dump($request); return $request; } - #[ApiOperation('1:查询')] - #[PostMapping(path: 'query')] - public function query(#[RequestBody] #[Valid] DemoQuery $request): Contact + #[ApiOperation(summary: '1:查询')] + #[PostMapping(path: 'search')] + public function search(#[RequestBody] #[Valid] DemoQuery $request): Contact { - dump($request); return new Contact(); } - #[ApiOperation('2:提交body数据和get参数')] - #[PutMapping(path: 'add')] - public function add(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query): ActivityResponse + #[ApiOperation(summary: '2:提交body数据和get参数')] + #[PutMapping(path: 'save')] + public function save(#[RequestBody] #[Valid] DemoBodyRequest $request, #[RequestQuery] DemoQuery $query): ActivityResponse { - dump($request); - dump($query); return new ActivityResponse(); } /** - * @param DemoFormData $formData * @return Address[] */ - #[ApiOperation('3:表单提交')] - #[PostMapping(path: 'fromData')] + #[ApiOperation(summary: '3:表单提交')] + #[PostMapping(path: 'formData')] #[ApiFormData(name: 'photo', format: 'binary')] -// #[ApiResponse(new CodeResponse(new GoodsInfoService()))] -// #[TestAnnotation(new GoodsInfoService())] -// #[ApiResponse(new GoodsInfoService())] - public function fromData(#[RequestFormData] DemoFormData $formData): array - { - $file = $this->request->file('photo'); - dump($file); - var_dump($formData); + public function formData(#[RequestFormData] DemoFormData $formData): array + { return [new Address()]; } - #[ApiOperation('4:查询单条记录')] - #[GetMapping(path: 'find/{id}/and/{in}')] - #[ApiHeader('test2')] + #[ApiOperation(summary: '4:查询单条记录')] + #[GetMapping(path: 'find/{id}/rate/{rate}')] + #[ApiHeader(name: 'test2')] #[ApiResponse([PhpType::BOOL])] #[ApiResponse(Address::class, 201)] - #[ApiResponse(Address_1::class, 202)] #[ApiResponse([Address::class], 203)] #[ApiResponse([PhpType::INT], 204)] #[ApiResponse(new Page([Address::class]), 206)] - public function find666666666(int $id, float $in) + public function find(int $id, float $rate): array { - return ['$id' => $id, '$in' => $in]; + return ['id' => $id, 'rate' => $rate]; } - #[ApiOperation('5:分页')] + #[ApiOperation(summary: '5:分页')] #[GetMapping(path: 'page')] #[ApiResponse(new Page([new ActivityResponse()]))] public function page(#[RequestQuery] PageQuery $pageQuery): Page { - $activitys = Activity::with(['activityUser' => function ($query) { - /* @var HasOne $query */ - $query->orderBy('id', 'desc')->with(['case']); - }]) - ->paginate($pageQuery->getSize()); - $arr = []; - foreach ($activitys as $activity) { - $arr[] = ActivityResponse::from($activity); - } - dump(new ActivityResponse()); - return new Page($arr, $activitys->total()); + $activity = new ActivityResponse(); + $activity->id = '1'; + $activity->activityName = '示例活动'; + + return new Page([$activity], 1); } - #[ApiOperation('6:更新')] + #[ApiOperation(summary: '6:更新')] #[PutMapping(path: 'update/{id}')] public function update(int $id): int { return $id; } - #[ApiOperation('7:删除')] + #[ApiOperation(summary: '7:删除')] #[DeleteMapping(path: 'delete/{id}')] public function delete(int $id): bool { return true; } - #[ApiOperation('patch方法')] + #[ApiOperation(summary: 'patch方法')] #[PatchMapping(path: 'patch/{id}')] public function patch(int $id): int { return $id; } - #[ApiOperation('获取请求头')] - #[PostMapping(path: 'getHeader/{id}')] + #[ApiOperation(summary: '获取请求头')] + #[PostMapping(path: 'header/{id}')] #[ApiSecurity] - public function getHeader(#[RequestHeader] #[Valid] DemoToken $header) - { - dump($header); - return null; - } + public function header(#[RequestHeader] #[Valid] DemoToken $header): void {} - #[ApiOperation('返回 obj(弃用)', deprecated: true)] + #[ApiOperation(summary: '返回 obj(弃用)', deprecated: true)] #[GetMapping(path: 'obj')] public function obj(): object { return new Address(); } - #[ApiOperation('登录', security: false)] + #[ApiOperation(summary: '登录', security: false)] #[PostMapping(path: 'login')] public function login(#[RequestBody] #[Valid] DemoBodyRequest $request): DemoBodyRequest { return $request; } - #[ApiOperation('返回code统一格式:int')] + #[ApiOperation(summary: '返回code统一格式:int')] #[PostMapping(path: 'codeInt')] #[ApiResponse(new CodeResponse(PhpType::INT))] - public function codeInt() + public function codeInt(): CodeResponse { - $data = 1; - return new CodeResponse($data); + return new CodeResponse(1); } - #[ApiOperation('返回code统一格式:int+数组')] + #[ApiOperation(summary: '返回code统一格式:int+数组')] #[PostMapping(path: 'codeIntArr')] #[ApiResponse(new CodeResponse([PhpType::INT], [CityResponse::class]))] public function codeIntArr(): CodeResponse { - $data = 1; $cityResponse = new CityResponse(); $cityResponse->name = '小明'; - dump($cityResponse); - return new CodeResponse($data, [$cityResponse]); + return new CodeResponse(1, [$cityResponse]); } + #[ApiOperation(summary: 'Dto 字段转换')] #[PostMapping(path: 'city')] public function city(): CityResponse { $city = new CityResponse(); $city->name = 'name2'; $city->bodyName = [1, 2, 3]; - dump($city); + return $city; } - #[PostMapping(path: 'db')] - public function db(#[RequestBody] #[Valid] DemoDatabaseRequest $request): int + + #[ApiOperation(summary: '数据库验证')] + #[PostMapping(path: 'validateDatabase')] + public function validateDatabase(#[RequestBody] #[Valid] DemoDatabaseRequest $request): int { - dump($request); return 1; } + + #[ApiOperation(summary: '只读响应字段')] + #[GetMapping(path: 'readonly')] + public function readonly(): ReadonlyResponse + { + return new ReadonlyResponse('1', date('Y-m-d H:i:s')); + } } diff --git a/example/Controller/TestController.php b/example/Controller/TestController.php deleted file mode 100644 index df03757..0000000 --- a/example/Controller/TestController.php +++ /dev/null @@ -1,29 +0,0 @@ -case = $case; - } } diff --git a/example/DTO/Address.php b/example/DTO/Address.php index 35aef3e..de1e1a1 100644 --- a/example/DTO/Address.php +++ b/example/DTO/Address.php @@ -4,17 +4,20 @@ namespace HyperfExample\ApiDocs\DTO; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\DTO\Annotation\ArrayType; use Hyperf\DTO\Annotation\JSONField; use Hyperf\DTO\Annotation\Validation\Required; +#[ApiModel('地址')] class Address { - public string $street; + #[ApiModelProperty('街道')] + public string $street = ''; - #[ApiModelProperty('浮点数')] - public float $float; + #[ApiModelProperty('纬度')] + public float $latitude = 0.0; #[ApiModelProperty('城市')] #[Required] @@ -23,5 +26,5 @@ class Address #[ApiModelProperty('城市数组')] #[ArrayType(City::class)] #[JSONField('city_new')] - public array $cityArr; + public array $cityArr = []; } diff --git a/example/DTO/Address_1.php b/example/DTO/Address_1.php deleted file mode 100644 index 2d024e3..0000000 --- a/example/DTO/Address_1.php +++ /dev/null @@ -1,18 +0,0 @@ -page; - } - - public function setPage(?int $page): void - { - $this->page = $page; - } - - public function getSize(): ?int - { - return $this->size; - } - - public function setSize(?int $size): void - { - $this->size = $size; - } } diff --git a/example/DTO/Request/DemoBodyRequest.php b/example/DTO/Request/DemoBodyRequest.php index 29e2029..f9f0146 100644 --- a/example/DTO/Request/DemoBodyRequest.php +++ b/example/DTO/Request/DemoBodyRequest.php @@ -4,90 +4,33 @@ namespace HyperfExample\ApiDocs\DTO\Request; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; -use Hyperf\ApiDocs\Swagger\SwaggerCommon; -use Hyperf\DTO\Annotation\ArrayType; -use Hyperf\DTO\Annotation\Dto; use Hyperf\DTO\Annotation\JSONField; use Hyperf\DTO\Annotation\Validation\Arr; -use Hyperf\DTO\Annotation\Validation\Between; -use Hyperf\DTO\Annotation\Validation\Email; -use Hyperf\DTO\Annotation\Validation\In; use Hyperf\DTO\Annotation\Validation\Integer; -use Hyperf\DTO\Annotation\Validation\Nullable; -use Hyperf\DTO\Annotation\Validation\Numeric; use Hyperf\DTO\Annotation\Validation\Required; use Hyperf\DTO\Annotation\Validation\Validation; -use Hyperf\DTO\Type\PhpType; use HyperfExample\ApiDocs\DTO\Address; -use HyperfExample\ApiDocs\Enum\StatusEnum; +use HyperfExample\ApiDocs\DTO\SystemRequest; -//#[Dto] +#[ApiModel('DemoBody请求体')] class DemoBodyRequest { + use SystemRequest; -// public const IN = ['A', 'B', 'C']; -// -// public Address $addr1; -// -// public Address $addr2; -// - #[ApiModelProperty('地址3')] + #[ApiModelProperty('收货地址')] #[Required] - public Address $addr3; - -// #[ApiModelProperty('int数组')] -// #[Required] -// #[ArrayType(SimpleType::INT)] -// public array $intArr; -// -// #[ApiModelProperty('demo名称')] -// public ?string $demoName = 'demo'; -// -// #[ApiModelProperty('枚举')] -//// #[In(DemoBodyRequest::IN)] -// #[Nullable] -// public StatusEnum $enum; -// -// #[ApiModelProperty('价格')] -// #[Required] -// public float $price; -// -// #[ApiModelProperty('电子邮件', example: '1@e.com')] -// #[Email(messages: '请输入正确的电子邮件')] -// public string $email; -// -// /** -// * @var int[] -// */ -// #[ApiModelProperty('int数据')] -// #[Validation(rule: 'array')] -// public array $intIdList; -// -// #[ApiModelProperty('addArr')] -// #[Validation(rule: 'array')] -// #[ArrayType(Address::class)] -// public array $addArr; -// -// public object $obj; -// -// #[Integer] -// #[Between(min: 2, max: 10)] -// public int $num = 6; + public Address $shippingAddress; + #[ApiModelProperty(value: '商品数量', example: 1)] #[Validation('required|numeric')] #[Integer] - #[JSONField('test_name')] - public int $test=1; + #[JSONField('item_count')] + public int $quantity = 1; -// #[Between(min: 2, max: 10)] - #[ApiModelProperty('intArr数组')] + #[ApiModelProperty('intArr数组', example: [1, 2])] #[Arr] #[Validation('integer', customKey: 'intArr.*')] - public array $intArr; - - - - private int $privateName = 0; - + public array $intArr = []; } diff --git a/example/DTO/Request/DemoDatabaseRequest.php b/example/DTO/Request/DemoDatabaseRequest.php index a9006f0..19a2d66 100644 --- a/example/DTO/Request/DemoDatabaseRequest.php +++ b/example/DTO/Request/DemoDatabaseRequest.php @@ -4,26 +4,22 @@ namespace HyperfExample\ApiDocs\DTO\Request; -use App\Model\Sale; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\DTO\Annotation\Validation\Exists; use Hyperf\DTO\Annotation\Validation\Required; use Hyperf\DTO\Annotation\Validation\Unique; +#[ApiModel('数据库验证请求')] class DemoDatabaseRequest { #[ApiModelProperty('这是一个Exists验证')] #[Required] - #[Exists(Sale::class, 'id')] + #[Exists(table: 'sale', column: 'id')] public int $id = 1; - #[ApiModelProperty('这是一个Exists验证 product')] - #[Required] - #[Exists(Sale::class)] - public float $product = 1.1; - #[ApiModelProperty('这是一个Unique验证')] #[Required] - #[Unique(Sale::class,'product','id')] + #[Unique(table: 'sale', column: 'product', ignoreIdKey: 'id')] public float $uniqueProduct = 1.3; } diff --git a/example/DTO/Request/DemoFormData.php b/example/DTO/Request/DemoFormData.php index 4f37b9c..3d6a7a0 100644 --- a/example/DTO/Request/DemoFormData.php +++ b/example/DTO/Request/DemoFormData.php @@ -4,17 +4,20 @@ namespace HyperfExample\ApiDocs\DTO\Request; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\DTO\Annotation\Validation\Between; +#[ApiModel('表单提交数据')] class DemoFormData { #[ApiModelProperty(value: '名称', required: true)] - public string $name; + public string $name = ''; - #[Between(2, 10)] - public int $num; + #[ApiModelProperty(value: '数量', example: 2)] + #[Between(min: 2, max: 10)] + public int $num = 2; #[ApiModelProperty(value: '年龄', required: true)] - public int $age; + public int $age = 0; } diff --git a/example/DTO/Request/DemoQuery.php b/example/DTO/Request/DemoQuery.php index 79bf406..e9fd55d 100644 --- a/example/DTO/Request/DemoQuery.php +++ b/example/DTO/Request/DemoQuery.php @@ -4,26 +4,25 @@ namespace HyperfExample\ApiDocs\DTO\Request; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; -use Hyperf\Contract\Arrayable; use Hyperf\DTO\Annotation\JSONField; use Hyperf\DTO\Annotation\Validation\In; use Hyperf\DTO\Annotation\Validation\Required; -use Hyperf\DTO\Type\PhpType; +use HyperfExample\ApiDocs\Enum\StatusEnum; -// #[HyperfData] -// #[Data] +#[ApiModel('查询参数')] class DemoQuery { #[ApiModelProperty('这是一个别名属性')] #[JSONField('alias_name')] #[Required] - public string $aliasName; + public string $aliasName = ''; #[ApiModelProperty('类型')] #[In(['a', 'b'])] - public string $type; - - + public string $type = ''; + #[ApiModelProperty('状态')] + public StatusEnum $status = StatusEnum::SUCCESS; } diff --git a/example/DTO/Response/ActivityResponse.php b/example/DTO/Response/ActivityResponse.php index ab2a7ab..41e90d0 100644 --- a/example/DTO/Response/ActivityResponse.php +++ b/example/DTO/Response/ActivityResponse.php @@ -4,39 +4,36 @@ namespace HyperfExample\ApiDocs\DTO\Response; -use App\Model\Activity; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\DTO\Annotation\Dto; use Hyperf\DTO\Annotation\JSONField; use Hyperf\DTO\Mapper; use HyperfExample\ApiDocs\DTO\ActivityUser; +use HyperfExample\ApiDocs\Model\Activity; #[Dto] +#[ApiModel('活动响应')] class ActivityResponse { -// public function __construct() -// { -// dump('...............ActivityResponse..................'); -// } - #[ApiModelProperty('id')] - public string $id; + public string $id = ''; #[ApiModelProperty('活动名称')] #[JSONField('activity_name')] - public string $activityName; + public string $activityName = ''; - #[ApiModelProperty('测试')] - #[JSONField('foo_bar')] - public string $fooBar; + #[ApiModelProperty('活动地点')] + #[JSONField('location_name')] + public string $location = ''; /** * @var ActivityUser[] */ - public array $activityUser; - + #[ApiModelProperty('参与用户')] + public array $activityUser = []; - public static function from(?Activity $obj): ?ActivityResponse + public static function from(?Activity $obj): ?self { return Mapper::copyProperties($obj, new self()); } diff --git a/example/DTO/Response/CityResponse.php b/example/DTO/Response/CityResponse.php index 904a607..3b72699 100644 --- a/example/DTO/Response/CityResponse.php +++ b/example/DTO/Response/CityResponse.php @@ -4,6 +4,7 @@ namespace HyperfExample\ApiDocs\DTO\Response; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\DTO\Annotation\Dto; use Hyperf\DTO\Annotation\JSONField; @@ -11,24 +12,15 @@ use Hyperf\DTO\Type\Convert; #[Dto(Convert::SNAKE)] +#[ApiModel('城市响应')] class CityResponse { #[ApiModelProperty('名称')] - public string $name; - public string $name22222; - - #[JSONField('name_arr_1')] - #[Required] - private array $nameArr = []; + public string $name = ''; public array $bodyName = []; - /** - * @return array - */ - public function getBodyName(): array - { - return $this->bodyName; - } - + #[JSONField('name_list')] + #[Required] + private array $nameArr = []; } diff --git a/example/DTO/Response/CodeResponse.php b/example/DTO/Response/CodeResponse.php index 2d5487d..625e887 100644 --- a/example/DTO/Response/CodeResponse.php +++ b/example/DTO/Response/CodeResponse.php @@ -1,23 +1,28 @@ data = $data; $this->content = $content; } - -} \ No newline at end of file +} diff --git a/example/DTO/Response/Contact.php b/example/DTO/Response/Contact.php index 945fe58..4515461 100644 --- a/example/DTO/Response/Contact.php +++ b/example/DTO/Response/Contact.php @@ -4,12 +4,15 @@ namespace HyperfExample\ApiDocs\DTO\Response; +use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; +use HyperfExample\ApiDocs\DTO\Address; +#[ApiModel('联系人信息')] class Contact { #[ApiModelProperty('名称')] - public string $name; + public string $name = ''; #[ApiModelProperty('年龄')] public ?int $age = null; @@ -17,18 +20,14 @@ class Contact #[ApiModelProperty('城市')] public ?CityResponse $city = null; - #[ApiModelProperty('城市1')] - public ?City1 $city1 = null; - /** - * 需要绝对路径. - * @var \HyperfExample\ApiDocs\DTO\Address[] + * @var Address[] */ #[ApiModelProperty('地址')] - public array $addressArr; + public array $addressArr = []; #[ApiModelProperty('数组')] - private ?array $arr; + private ?array $arr = null; public function getArr(): ?array { diff --git a/example/DTO/Response/Page.php b/example/DTO/Response/Page.php index 63969e4..fccd889 100644 --- a/example/DTO/Response/Page.php +++ b/example/DTO/Response/Page.php @@ -4,16 +4,21 @@ namespace HyperfExample\ApiDocs\DTO\Response; +use Hyperf\ApiDocs\Annotation\ApiModel; +use Hyperf\ApiDocs\Annotation\ApiModelProperty; use Hyperf\ApiDocs\Annotation\ApiVariable; +#[ApiModel('分页结果')] class Page { - public int $total; + #[ApiModelProperty('总数')] + public int $total = 0; - #[ApiVariable] #标记未可变变量 - public array $content; + #[ApiVariable] + #[ApiModelProperty('列表')] + public array $content = []; - public function __construct(array $content, int $total = 0) + public function __construct(array $content = [], int $total = 0) { $this->content = $content; $this->total = $total; diff --git a/example/DTO/Response/ReadonlyResponse.php b/example/DTO/Response/ReadonlyResponse.php new file mode 100644 index 0000000..b869daf --- /dev/null +++ b/example/DTO/Response/ReadonlyResponse.php @@ -0,0 +1,24 @@ +id = $id; + $this->createdAt = $createdAt; + } +} diff --git a/example/DTO/SystemRequest.php b/example/DTO/SystemRequest.php index 0529c99..8bf3cdd 100644 --- a/example/DTO/SystemRequest.php +++ b/example/DTO/SystemRequest.php @@ -1,5 +1,7 @@ =8.1 -//if (PHP_VERSION_ID >= 80100) { - enum StatusEnum: string - { - case SUCCESS = 'success'; - - case CLOSED = 'closed'; - } -//} else { -// class StatusEnum -// { -// -// } -//} +declare(strict_types=1); +namespace HyperfExample\ApiDocs\Enum; +enum StatusEnum: string +{ + case SUCCESS = 'success'; + case CLOSED = 'closed'; +} diff --git a/example/Model/Activity.php b/example/Model/Activity.php new file mode 100644 index 0000000..42a35f1 --- /dev/null +++ b/example/Model/Activity.php @@ -0,0 +1,19 @@ + + */ + public array $activityUser = []; +} diff --git a/example/README.md b/example/README.md new file mode 100644 index 0000000..91353c8 --- /dev/null +++ b/example/README.md @@ -0,0 +1,50 @@ +# 示例目录 + +本目录是 `tangwei/apidocs` 的注解用法活文档,不参与 Composer autoload。复制到业务项目后,将 `HyperfExample\ApiDocs` 替换为应用命名空间。 + +## 内容 + +- `Controller/`:路由、query/body/数组/表单/Header、多状态码响应、分页、具体类响应与只读响应。 +- `DTO/`:嵌套对象、数组、别名、验证、字段转换、`ApiVariable` 与 readonly 属性。 +- `Enum/`:枚举 schema。 +- `Model/`:`ActivityResponse::from()` 使用的模拟实体。 + +## 请求绑定 + +| 注解 | 用途 | +|------|------| +| `#[RequestBody]` | JSON 请求体;数组参数用 `@param DemoQuery[] $request` 声明元素类型 | +| `#[RequestQuery]` | 查询参数 DTO | +| `#[RequestHeader]` | 请求头 DTO | +| `#[RequestFormData]` | 表单 DTO,配合 `#[ApiFormData]` 补充文件字段 | + +`#[Valid]` 执行 DTO 验证。控制器方法返回具体类可获得准确的响应 schema;`object`、`array`、`mixed` 只能生成通用结构。 + +## DTO 4.0 输入规则 + +- 输入只接受 primaryKey:有 `#[JSONField]` 时使用别名,否则使用 PHP 属性名。 +- private/protected 属性需要公共 setter;readonly/static 属性不参与输入映射。 +- 不可写的响应字段标记为 `readOnly`,`$ref` 使用 `allOf` 包裹以保留该标记。 +- `#[Required]` 字段即使不可写也列为请求必填,因为验证先于映射执行。 + +## ApiVariable + +通过响应实例指定可变字段类型: + +```php +#[ApiResponse(new CodeResponse(PhpType::INT))] +public function codeInt(): CodeResponse { } +``` + +也支持 `types` 映射: + +```php +#[ApiResponse(Page::class, 207, '分页数据', types: ['content' => [Address::class]])] +``` + +## 验证与生成 + +- `#[Required]` 写入 required 列表,`#[In]` 生成 enum;其他验证规则主要用于运行时校验。 +- 数组元素验证使用 `#[Validation('integer', customKey: 'intArr.*')]`。 +- OpenAPI 文件在启动时生成,修改注解后需重启。 +- 升级 DTO 4.0 后,清理并重新生成 `runtime/container/proxy/` 中的代理。 diff --git a/publish/skills/api-docs/SKILL.md b/publish/skills/api-docs/SKILL.md index dadbfdb..66d3c31 100644 --- a/publish/skills/api-docs/SKILL.md +++ b/publish/skills/api-docs/SKILL.md @@ -236,6 +236,10 @@ class UserRequest } ``` +- DTO 4.0 输入只接受字段 primaryKey:有 `#[JSONField]` 时使用别名,否则使用 PHP 属性名;private/protected 属性需要正常业务 setter,readonly/static 属性不参与输入映射。 +- 只用于响应的私有别名字段在 schema 中标记为 `readOnly`,调用方不应将其作为请求字段提交;但带 `#[Required]` 的字段仍按请求必填输出,因为 DTO 验证先于映射执行。 +- 接口属性优先通过 DTO `classMap` 配置具体类;无法静态解析时文档使用通用 `object`,不要把接口字段描述为 `null`。 + ### DTO 验证常用注解 验证注解位于 `Hyperf\DTO\Annotation\Validation\*`,均为**属性注解、可叠加**,构造参数 `messages:` 可自定义错误消息。 diff --git a/src/Ast/ResponseVisitor.php b/src/Ast/ResponseVisitor.php index d492a55..c1f6af0 100644 --- a/src/Ast/ResponseVisitor.php +++ b/src/Ast/ResponseVisitor.php @@ -9,18 +9,20 @@ use PhpParser\BuilderFactory; use PhpParser\Node; use PhpParser\NodeVisitorAbstract; -use ReflectionClass; -use ReflectionProperty; class ResponseVisitor extends NodeVisitorAbstract { public BuilderFactory $factory; + protected string $sourceShortName; + public function __construct( protected string $generateClassName, protected array $propertyArr, + string $sourceClassName, ) { $this->factory = new BuilderFactory(); + $this->sourceShortName = (new \ReflectionClass($sourceClassName))->getShortName(); } public function leaveNode(Node $node) @@ -43,10 +45,13 @@ public function leaveNode(Node $node) $propertyTypeName = 'array'; } $node->type = new Node\Identifier($propertyTypeName); - // $node->props[0]->default = null; + // 原默认值可能与运行时替换后的类型不兼容。 + $node->props[0]->default = null; } } - if ($node instanceof Node\Stmt\Class_) { + if ($node instanceof Node\Stmt\Class_ + && $node->name?->toString() === $this->sourceShortName + ) { $node->name = new Node\Identifier($this->generateClassName); } if ($node instanceof Node\Stmt\Namespace_) { @@ -63,8 +68,8 @@ protected function buildAttributeArgs(AbstractAnnotation $annotation, array $arg protected function getNotDefaultPropertyFromAnnotation(AbstractAnnotation $annotation): array { $properties = []; - $ref = new ReflectionClass($annotation); - foreach ($ref->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { + $ref = new \ReflectionClass($annotation); + foreach ($ref->getProperties(\ReflectionProperty::IS_PUBLIC) as $property) { if ($property->hasDefaultValue() && $property->getDefaultValue() === $property->getValue($annotation)) { continue; } diff --git a/src/Swagger/GenerateParameters.php b/src/Swagger/GenerateParameters.php index 0a07cca..7d1a715 100644 --- a/src/Swagger/GenerateParameters.php +++ b/src/Swagger/GenerateParameters.php @@ -18,6 +18,7 @@ use Hyperf\DTO\Scan\MethodParametersManager; use Hyperf\DTO\Scan\Property; use Hyperf\DTO\Scan\PropertyManager; +use OpenApi\Annotations\Schema; use OpenApi\Attributes as OA; use Psr\Container\ContainerInterface; @@ -39,8 +40,7 @@ public function __construct( protected SwaggerCommon $common, protected PropertyManager $propertyManager, protected MethodParametersManager $methodParametersManager - ) { - } + ) {} public function generate(): array { @@ -77,29 +77,32 @@ public function generate(): array $requestBody = new OA\RequestBody(); $requestBody->required = true; $property = $this->methodParametersManager->getProperty($this->controller, $this->action, $paramName); - $requestBody->content = $this->getContent($property->arrClassName ?? '', property: $property); + $requestBody->content = $this->getContent('array', property: $property); $result['requestBody'] = $requestBody; } - if ($this->container->has($parameterClassName)) { + $resolvedParameterClass = $this->common->resolveDtoClass($parameterClassName) ?? $parameterClassName; + if ($this->container->has($resolvedParameterClass) + || class_exists($resolvedParameterClass) + || interface_exists($resolvedParameterClass) + ) { if ($methodParameter == null) { continue; } if ($methodParameter->isRequestBody()) { $requestBody = new OA\RequestBody(); $requestBody->required = true; - // $requestBody->description = ''; - $requestBody->content = $this->getContent($parameterClassName); + $requestBody->content = $this->getContent($resolvedParameterClass); $result['requestBody'] = $requestBody; } if ($methodParameter->isRequestQuery()) { - $parameterArr = array_merge($parameterArr, $this->getParameterArrByClass($parameterClassName, 'query')); + $parameterArr = array_merge($parameterArr, $this->getParameterArrByClass($resolvedParameterClass, 'query')); } if ($methodParameter->isRequestHeader()) { - $parameterArr = array_merge($parameterArr, $this->getParameterArrByClass($parameterClassName, 'header')); + $parameterArr = array_merge($parameterArr, $this->getParameterArrByClass($resolvedParameterClass, 'header')); } if ($methodParameter->isRequestFormData()) { - $requestFormDataclass = $parameterClassName; + $requestFormDataclass = $resolvedParameterClass; } } } @@ -135,51 +138,40 @@ public function generateFormDataSchemas($className, $apiFormDataArr): OA\Schema public function getParameterArrByClass(string $parameterClassName, string $in): array { $parameters = []; + $this->common->syncDtoMapper(); $rc = ReflectionManager::reflectClass($parameterClassName); foreach ($rc->getProperties() ?? [] as $reflectionProperty) { - $propertyManager = $this->propertyManager->getProperty($parameterClassName, $reflectionProperty->name); - $parameter = new OA\Parameter(); $fieldName = $reflectionProperty->getName(); - $schema = new OA\Schema(); - $parameter->name = $propertyManager?->alias ?? $fieldName; - $parameter->in = $in; - $schema->default = $this->common->getPropertyDefaultValue($parameterClassName, $reflectionProperty); - - $apiModelProperty = ApiAnnotation::getProperty($parameterClassName, $fieldName, ApiModelProperty::class); - $apiModelProperty = $apiModelProperty ?: new ApiModelProperty(); + if ($reflectionProperty->isStatic()) { + continue; + } + $apiModelProperty = ApiAnnotation::getProperty($parameterClassName, $fieldName, ApiModelProperty::class) ?: new ApiModelProperty(); if ($apiModelProperty->hidden) { continue; } - if (! $reflectionProperty->isPublic() - && ! $rc->hasMethod(\Hyperf\Support\setter($fieldName)) - && $propertyManager?->alias === null - ) { + $requiredAnnotation = ApiAnnotation::getProperty($parameterClassName, $fieldName, Required::class)?->toAnnotations()[0]; + $isRequired = $apiModelProperty->required || $requiredAnnotation !== null; + [, $accessor, $accessorType] = $this->common->inspectDtoProperty($rc, $fieldName); + if ($accessor === null && ! $isRequired) { continue; } - // 存在自定义简单类型 - if ($apiModelProperty->phpType) { - $phpType = $apiModelProperty->phpType; - } else { - $phpType = $this->common->getTypeName($reflectionProperty); - $enum = $propertyManager?->enum; - if ($enum) { - $phpType = $enum->backedType; - } - /** @var In $inAnnotation */ + + $propertyManager = $this->propertyManager->getProperty($parameterClassName, $fieldName); + $schema = $apiModelProperty->phpType + ? $this->swaggerComponents->createSchema(type: $apiModelProperty->phpType, namespace: $rc->getNamespaceName()) + : $this->swaggerComponents->createSchema($propertyManager, $accessorType, $rc->getNamespaceName()); + $schema->default = $this->common->getPropertyDefaultValue($parameterClassName, $reflectionProperty); + if (empty($apiModelProperty->phpType)) { $inAnnotation = ApiAnnotation::getProperty($parameterClassName, $fieldName, In::class)?->toAnnotations()[0]; - if (! empty($inAnnotation)) { + if ($inAnnotation !== null) { $schema->enum = $inAnnotation->getValue(); } - if (! empty($enum)) { - $schema->enum = $enum->valueList; - } } - $schema->type = $this->common->getSwaggerType($phpType); - - /** @var Required $requiredAnnotation */ - $requiredAnnotation = ApiAnnotation::getProperty($parameterClassName, $fieldName, Required::class)?->toAnnotations()[0]; - if ($apiModelProperty->required || $requiredAnnotation) { + $parameter = new OA\Parameter(); + $parameter->name = $propertyManager?->alias ?? $fieldName; + $parameter->in = $in; + if ($isRequired) { $parameter->required = true; } $parameter->schema = $schema; @@ -199,23 +191,9 @@ protected function getContent(string $className, string $mediaTypeStr = 'applica return $arr; } - protected function getJsonContent(string $className, ?Property $property = null): OA\JsonContent + protected function getJsonContent(string $className, ?Property $property = null): Schema { - $jsonContent = new OA\JsonContent(); - $this->swaggerComponents->generateSchemas($className); - if ($property?->phpSimpleType == 'array') { - $jsonContent->type = 'array'; - $items = new OA\Items(); - if ($property->arrClassName) { - $items->ref = $this->common->getComponentsName($property->arrClassName); - } else { - $items->type = $this->common->getSwaggerType($property->arrSimpleType); - } - $jsonContent->items = $items; - } else { - $jsonContent->ref = $this->common->getComponentsName($className); - } - return $jsonContent; + return $this->swaggerComponents->createSchema($property, $className); } /** @@ -233,7 +211,10 @@ protected function getParameterArrByBaseParam(array $baseParam): array $parameter->name = $param->name; $parameter->in = $param->getIn(); $schema->default = $param->default; - $schema->type = $this->common->getSwaggerType($param->type); + $type = $this->common->getSwaggerType($param->type); + if ($type !== null) { + $schema->type = $type; + } // 描述 $parameter->description = $param->description; if ($param->required !== null) { @@ -268,7 +249,10 @@ protected function getPropertiesByBaseParam(array $baseParam): array $property->description = $param->description; $param->required && $requiredArr[] = $fieldName; $property->default = $param->default; - $property->type = $this->common->getSwaggerType($param->type); + $type = $this->common->getSwaggerType($param->type); + if ($type !== null) { + $property->type = $type; + } $property->format = $param->format; $propertyArr[] = $property; } diff --git a/src/Swagger/GenerateProxyClass.php b/src/Swagger/GenerateProxyClass.php index 3f7f1df..ee2150f 100644 --- a/src/Swagger/GenerateProxyClass.php +++ b/src/Swagger/GenerateProxyClass.php @@ -13,8 +13,6 @@ use PhpParser\NodeTraverser; use PhpParser\ParserFactory; use PhpParser\PrettyPrinter; -use ReflectionClass; -use SplFileInfo; use function Hyperf\Support\make; @@ -132,8 +130,8 @@ protected function generateProxy(string $classname, array $propertyValues): stri } } - $ref = new ReflectionClass($classname); - $file = new SplFileInfo($ref->getFileName()); + $ref = new \ReflectionClass($classname); + $file = new \SplFileInfo($ref->getFileName()); $realPath = $file->getRealPath(); [$generateNamespaceClassName, $content] = $this->phpParser($classname, $realPath, $propertyArr); @@ -180,7 +178,7 @@ protected function phpParser(string $classname, $filePath, $propertyArr): array } $traverser = new NodeTraverser(); - $resVisitor = make(ResponseVisitor::class, [$generateClassName, $propertyArr]); + $resVisitor = make(ResponseVisitor::class, [$generateClassName, $propertyArr, $classname]); $traverser->addVisitor($resVisitor); $ast = $traverser->traverse($ast); diff --git a/src/Swagger/GenerateResponses.php b/src/Swagger/GenerateResponses.php index fddbac0..300f30f 100644 --- a/src/Swagger/GenerateResponses.php +++ b/src/Swagger/GenerateResponses.php @@ -94,57 +94,30 @@ protected function getContent(array|object|string $returnTypeClassName, array $t $returnTypeClassName = is_object($returnTypeClassName) ? $returnTypeClassName::class : $returnTypeClassName; } $returnTypeClassName == 'array' && $isArray = true; - $arr = []; - $mediaType = new OA\MediaType(); - $mediaTypeStr = 'text/plain'; - // 简单类型 - if ($this->common->isSimpleType($returnTypeClassName)) { - $schema = new OA\Schema(); - $schema->type = $this->common->getSwaggerType($returnTypeClassName); - // 数组 - if ($isArray) { - $mediaTypeStr = 'application/json'; - $schema->type = 'array'; - $items = new OA\Items(); - $swaggerType = $this->common->getSwaggerType($returnTypeClassName); - $items->type = $swaggerType == 'array' ? 'null' : $swaggerType; - $schema->items = $items; - } - $mediaType->schema = $schema; - } elseif ($this->container->has($returnTypeClassName)) { - $mediaTypeStr = 'application/json'; - $mediaType->schema = $this->getJsonContent($returnTypeClassName, $isArray); - } else { - // $schema = new OA\Schema(); - // $schema->type = 'null'; - // $mediaType->schema = $schema; - // 其他类型数据 eg:mixed - return []; + $schemaType = $returnTypeClassName; + if ($isArray && $schemaType !== 'array') { + $schemaType = ($schemaType ?? 'mixed') . '[]'; } - $arr[$mediaTypeStr] = $mediaType; - $mediaType->mediaType = $mediaTypeStr; - return $arr; - } - - /** - * 获取返回类型的JsonContent. - */ - protected function getJsonContent(string $returnTypeClassName, bool $isArray): OA\JsonContent - { - $jsonContent = new OA\JsonContent(); - $this->swaggerComponents->generateSchemas($returnTypeClassName); - + $mediaType = new OA\MediaType(); if ($isArray) { - $jsonContent->type = 'array'; - $items = new OA\Items(); - $items->ref = $this->common->getComponentsName($returnTypeClassName); - $jsonContent->items = $items; + $mediaType->mediaType = 'application/json'; + $mediaType->schema = $this->swaggerComponents->createSchema(type: $schemaType); + } elseif ($this->common->isSimpleType($returnTypeClassName)) { + $mediaType->mediaType = 'text/plain'; + $mediaType->schema = $this->swaggerComponents->createSchema(type: $returnTypeClassName); + } elseif (is_string($returnTypeClassName) && ( + $this->container->has($returnTypeClassName) + || class_exists($returnTypeClassName) + || interface_exists($returnTypeClassName) + )) { + $mediaType->mediaType = 'application/json'; + $mediaType->schema = $this->swaggerComponents->createSchema(type: $returnTypeClassName); } else { - $jsonContent->ref = $this->common->getComponentsName($returnTypeClassName); + return []; } - return $jsonContent; + return [$mediaType->mediaType => $mediaType]; } /** diff --git a/src/Swagger/SwaggerCommon.php b/src/Swagger/SwaggerCommon.php index 64c89cb..85c4e1c 100644 --- a/src/Swagger/SwaggerCommon.php +++ b/src/Swagger/SwaggerCommon.php @@ -5,10 +5,10 @@ namespace Hyperf\ApiDocs\Swagger; use Hyperf\DTO\DtoCommon; +use Hyperf\DTO\JsonMapper; +use Hyperf\DTO\Mapper; use Hyperf\DTO\Type\PhpType; use OpenApi\Generator; -use ReflectionProperty; -use Throwable; class SwaggerCommon extends DtoCommon { @@ -16,6 +16,34 @@ class SwaggerCommon extends DtoCommon protected array $simpleClassNameCache = []; + private ?JsonMapper $dtoMapper = null; + + public function setDtoMapper(JsonMapper $dtoMapper): void + { + $this->dtoMapper = $dtoMapper; + } + + public function getDtoMapper(): JsonMapper + { + return $this->dtoMapper ?? Mapper::getJsonMapper(); + } + + public function syncDtoMapper(): void + { + $this->bIgnoreVisibility = $this->getDtoMapper()->bIgnoreVisibility; + } + + public function inspectDtoProperty(\ReflectionClass $rc, string $name): array + { + $this->syncDtoMapper(); + return $this->inspectPropertyMetadata($rc, $name); + } + + public function resolveDtoClass(?string $type): ?string + { + return $this->getDtoMapper()->resolveMappedClass($type, null); + } + public function getComponentsName(string $className): string { return '#/components/schemas/' . $this->getSimpleClassName($className); @@ -53,7 +81,7 @@ public function getSimpleClassName(?string $className): string /** * 获取swagger类型. */ - public function getSwaggerType(mixed $phpType): string + public function getSwaggerType(mixed $phpType): ?string { return match ($phpType) { 'int', 'integer' => 'integer', @@ -62,7 +90,7 @@ public function getSwaggerType(mixed $phpType): string 'array' => 'array', 'object' => 'object', 'string' => 'string', - default => 'null', + default => null, }; } @@ -92,13 +120,13 @@ public function getPhpType(mixed $type): string if (is_object($type) && $type::class !== 'stdClass') { return '\\' . $type::class; } - if (is_string($type) && class_exists($type)) { + if (is_string($type) && (class_exists($type) || interface_exists($type))) { return '\\' . trim($type, '\\'); } return 'mixed'; } - public function getPropertyDefaultValue(string $className, ReflectionProperty $reflectionProperty): mixed + public function getPropertyDefaultValue(string $className, \ReflectionProperty $reflectionProperty): mixed { $default = Generator::UNDEFINED; try { @@ -106,7 +134,7 @@ public function getPropertyDefaultValue(string $className, ReflectionProperty $r if ($reflectionProperty->isInitialized($obj)) { $default = $reflectionProperty->getValue($obj); } - } catch (Throwable) { + } catch (\Throwable) { $fieldName = $reflectionProperty->getName(); $classVars = get_class_vars($className); if (isset($classVars[$fieldName])) { diff --git a/src/Swagger/SwaggerComponents.php b/src/Swagger/SwaggerComponents.php index 3960051..71e4578 100644 --- a/src/Swagger/SwaggerComponents.php +++ b/src/Swagger/SwaggerComponents.php @@ -6,19 +6,18 @@ use Hyperf\ApiDocs\Annotation\ApiModel; use Hyperf\ApiDocs\Annotation\ApiModelProperty; -use Hyperf\ApiDocs\Exception\ApiDocsException; use Hyperf\Di\Annotation\AnnotationCollector; use Hyperf\Di\ReflectionManager; use Hyperf\DTO\Annotation\Validation\In; use Hyperf\DTO\Annotation\Validation\Required; use Hyperf\DTO\ApiAnnotation; use Hyperf\DTO\Scan\Property; +use Hyperf\DTO\Scan\PropertyEnum; use Hyperf\DTO\Scan\PropertyManager; +use OpenApi\Annotations\Schema; use OpenApi\Attributes as OA; use OpenApi\Generator; -use function Hyperf\Support\setter; - class SwaggerComponents { protected array $schemas = []; @@ -27,8 +26,7 @@ public function __construct( protected SwaggerCommon $common, protected PropertyManager $propertyManager, protected ?GenerateProxyClass $generateProxyClass, - ) { - } + ) {} public function getSchemas(): array { @@ -46,114 +44,72 @@ public function getProperties(string $className): array return ['propertyArr' => [], 'requiredArr' => []]; } + $this->common->syncDtoMapper(); $rc = ReflectionManager::reflectClass($className); $propertyArr = []; $requiredArr = []; - // 循环字段 foreach ($rc->getProperties() as $reflectionProperty) { - // 属性 - $property = new OA\Property(); $fieldName = $reflectionProperty->getName(); + if ($reflectionProperty->isStatic()) { + continue; + } $propertyManager = $this->propertyManager->getProperty($className, $fieldName); if ($propertyManager === null) { - // 属性未被 DTO 扫描器登记(如代理类),按反射类型兜底 + // 属性未被 DTO 扫描器登记(如代理类),按反射类型兜底。 $propertyManager = $this->buildPropertyFromReflection($reflectionProperty); } - // 适配ApiVariable注解 $sourceClassName = $this->generateProxyClass?->getSourceClassname($className) ?? $className; $apiModelProperty = ApiAnnotation::getProperty($sourceClassName, $fieldName, ApiModelProperty::class) ?: new ApiModelProperty(); - - /** @var In $inAnnotation */ - $inAnnotation = ApiAnnotation::getProperty($sourceClassName, $fieldName, In::class)?->toAnnotations()[0]; if ($apiModelProperty->hidden) { continue; } + $requiredAnnotation = ApiAnnotation::getProperty($sourceClassName, $fieldName, Required::class)?->toAnnotations()[0]; + $isRequired = $apiModelProperty->required || $requiredAnnotation !== null; + [, $accessor] = $this->common->inspectDtoProperty($rc, $fieldName); + $isWritable = $accessor !== null; if (! $reflectionProperty->isPublic() - && ! $rc->hasMethod(setter($fieldName)) + && ! $isWritable && $propertyManager->alias === null + && ! $isRequired ) { continue; } - // 字段名称 + $property = new OA\Property(); $property->property = $propertyManager->alias ?? $fieldName; - // 描述 $apiModelProperty->value !== null && $property->description = $apiModelProperty->value; - // required - /** @var Required $requiredAnnotation */ - $requiredAnnotation = ApiAnnotation::getProperty($sourceClassName, $fieldName, Required::class)?->toAnnotations()[0]; - if ($apiModelProperty->required || $requiredAnnotation) { - $requiredArr[] = $fieldName; + if ($isRequired) { + // 验证发生在 DTO 映射前,不可写属性仍可能是请求必填字段。 + $requiredArr[] = $property->property; } $property->example = $apiModelProperty->example; $property->default = $this->common->getPropertyDefaultValue($className, $reflectionProperty); - $isSimpleType = $propertyManager->isSimpleType; - $phpSimpleType = $propertyManager->phpSimpleType; - if ($apiModelProperty->phpType) { - $isSimpleType = true; - $phpSimpleType = $apiModelProperty->phpType; - } - - // swagger 类型 - $swaggerType = $this->common->getSwaggerType($phpSimpleType); - - // 枚举:in - if (! empty($inAnnotation) && empty($apiModelProperty->phpType)) { - $property->type = $swaggerType; - $property->enum = $inAnnotation->getValue(); + $schema = $apiModelProperty->phpType + ? $this->createSchema(type: $apiModelProperty->phpType, namespace: $rc->getNamespaceName()) + : $this->createSchema($propertyManager); + $inAnnotation = ApiAnnotation::getProperty($sourceClassName, $fieldName, In::class)?->toAnnotations()[0]; + if ($inAnnotation !== null && empty($apiModelProperty->phpType)) { + $schema->enum = $inAnnotation->getValue(); } - // 简单类型 - elseif ($isSimpleType) { - // 数组 - if ($swaggerType == 'array') { - $property->type = 'array'; - $items = new OA\Items(); - $items->type = 'null'; - $property->items = $items; - } else { - // 普通简单类型 - $property->type = $swaggerType; - } - } // 枚举类型 - elseif ($propertyManager->enum) { - $property->type = $this->common->getSwaggerType($propertyManager->enum->backedType); - $property->enum = $propertyManager->enum->valueList; - } // 普通类 - else { - if ($swaggerType == 'array') { - $property->type = 'array'; - if (! empty($propertyManager->arrClassName)) { - $items = new OA\Items(); - $items->ref = $this->common->getComponentsName($propertyManager->arrClassName); - $property->items = $items; - $this->generateSchemas($propertyManager->arrClassName); - $property->default = Generator::UNDEFINED; - } elseif (! empty($propertyManager->arrSimpleType)) { - $items = new OA\Items(); - $items->type = $this->common->getSwaggerType($propertyManager->arrSimpleType); - $property->items = $items; - } elseif (! empty($propertyManager->arrInterfaceName)) { - // 接口元素没有可引用的具体 schema,降级为未约束类型。 - $items = new OA\Items(); - $items->type = 'null'; - $property->items = $items; - } - } elseif (! empty($propertyManager->className)) { - $property->ref = $this->common->getComponentsName($propertyManager->className); - $this->generateSchemas($propertyManager->className); - } elseif (! empty($propertyManager->interfaceName)) { - $property->type = 'null'; - } else { - throw ApiDocsException::typeResolutionFailed($className, $fieldName); - } + $this->copySchemaType($schema, $property); + if (! $isWritable && ! $isRequired) { + $this->markReadOnly($property); } $propertyArr[] = $property; } return ['propertyArr' => $propertyArr, 'requiredArr' => $requiredArr]; } + public function createSchema(?Property $property = null, ?string $type = null, string $namespace = ''): Schema + { + $property ??= $this->propertyManager->createPropertyFromType($type, $namespace); + $schema = new OA\Schema(); + $this->applySchemaType($schema, $property); + return $schema; + } + public function generateSchemas(string $className) { $simpleClassName = $this->common->getSimpleClassName($className); @@ -162,7 +118,7 @@ public function generateSchemas(string $className) } $schema = new OA\Schema(); $schema->schema = $simpleClassName; - // 先登记再解析属性,防止循环引用类(A ↔ B)导致无限递归 + // 先登记再解析属性,防止循环引用类(A ↔ B)导致无限递归。 $this->schemas[$simpleClassName] = $schema; $data = $this->getProperties($className); @@ -176,16 +132,121 @@ public function generateSchemas(string $className) return $this->schemas[$simpleClassName]; } + protected function applySchemaType(Schema $schema, Property $property): void + { + if ($property->enum !== null) { + $this->applyEnum($schema, $property->enum); + return; + } + if ($property->phpSimpleType === 'array') { + $this->applyArrayType($schema, $property); + return; + } + if ($property->className !== null) { + $this->applyClassType($schema, $property->className); + return; + } + if ($property->interfaceName !== null) { + $this->applyClassType($schema, $property->interfaceName); + return; + } + + $type = $this->common->getSwaggerType($property->phpSimpleType); + if ($type !== null) { + $schema->type = $type; + } + } + + protected function applyArrayType(Schema $schema, Property $property): void + { + $depth = max(1, $property->arrayDepth); + $current = $schema; + for ($level = 0; $level < $depth; ++$level) { + $current->type = 'array'; + $current->items = new OA\Items(); + $current = $current->items; + } + + if ($property->arrClassName !== null) { + $this->applyClassType($current, $property->arrClassName); + return; + } + if ($property->arrInterfaceName !== null) { + $this->applyClassType($current, $property->arrInterfaceName); + return; + } + $type = $this->common->getSwaggerType($property->arrSimpleType); + if ($type !== null) { + $current->type = $type; + if ($type === 'array') { + $current->items = new OA\Items(); + } + } + } + + protected function applyClassType(Schema $schema, string $className): void + { + $mappedClass = $this->common->resolveDtoClass($className); + if ($mappedClass === null) { + // 接口或动态 classMap 无法在启动期确定具体结构。 + $schema->type = 'object'; + return; + } + if (enum_exists($mappedClass)) { + $this->applyEnumClass($schema, $mappedClass); + return; + } + + $schema->ref = $this->common->getComponentsName($mappedClass); + $this->generateSchemas($mappedClass); + } + + protected function applyEnumClass(Schema $schema, string $enumClass): void + { + $propertyEnum = (new PropertyEnum())->get($enumClass); + if ($propertyEnum !== null) { + $this->applyEnum($schema, $propertyEnum); + return; + } + + $schema->type = 'string'; + $schema->enum = array_map(static fn ($case) => $case->name, $enumClass::cases()); + } + + protected function applyEnum(Schema $schema, PropertyEnum $propertyEnum): void + { + $schema->type = $this->common->getSwaggerType($propertyEnum->backedType); + $schema->enum = $propertyEnum->valueList; + } + + protected function copySchemaType(Schema $source, Schema $target): void + { + foreach (['type', 'ref', 'items', 'enum'] as $field) { + if ($source->{$field} !== Generator::UNDEFINED) { + $target->{$field} = $source->{$field}; + } + } + } + + protected function markReadOnly(OA\Property $property): void + { + $property->readOnly = true; + if ($property->ref === Generator::UNDEFINED) { + return; + } + + // swagger-php 序列化 $ref 时会丢弃同级字段,使用 allOf 保留 readOnly。 + $ref = new OA\Schema(); + $ref->ref = $property->ref; + $property->ref = Generator::UNDEFINED; + $property->allOf = [$ref]; + } + protected function buildPropertyFromReflection(\ReflectionProperty $reflectionProperty): Property { - $property = new Property(); - $phpType = $this->common->getTypeName($reflectionProperty); - if ($this->common->isSimpleType($phpType)) { - $property->phpSimpleType = $phpType; - } else { - $property->isSimpleType = false; - $property->className = $phpType; - } - return $property; + return $this->propertyManager->createPropertyFromType( + $this->common->getTypeName($reflectionProperty), + $reflectionProperty->getDeclaringClass()->getNamespaceName(), + ); } } diff --git a/src/Swagger/SwaggerLlms.php b/src/Swagger/SwaggerLlms.php index 855e2d0..d70706f 100644 --- a/src/Swagger/SwaggerLlms.php +++ b/src/Swagger/SwaggerLlms.php @@ -53,13 +53,17 @@ public function detail(string $operationId, string $filePath): string $openapi['components'] = $newComponents['components'] ?? []; unset($openapi['tags'], $openapi['externalDocs']); - $flags = Yaml::DUMP_OBJECT_AS_MAP ^ Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE; - $yaml = Yaml::dump($openapi, 10, 2, $flags); + $yaml = $this->dumpYaml($openapi); $content = sprintf("# %s\n\n## %s\n\n", $path['summary'] ?? $path['operationId'], $path['description'] ?? ''); $yaml = sprintf("```yaml\n%s\n```", $yaml); return $content . $yaml; } + protected function dumpYaml(array $openapi): string + { + return Yaml::dump($openapi, 10, 2, Yaml::DUMP_OBJECT_AS_MAP); + } + protected function getSchemas($data = [], array $components = []): array { $schemas = []; diff --git a/tests/GenerateParametersTest.php b/tests/GenerateParametersTest.php index f9beacd..204ed83 100644 --- a/tests/GenerateParametersTest.php +++ b/tests/GenerateParametersTest.php @@ -11,11 +11,20 @@ use Hyperf\Di\MethodDefinitionCollectorInterface; use Hyperf\Di\ReflectionType; use Hyperf\DTO\Annotation\JSONField; +use Hyperf\DTO\Annotation\Validation\Required; +use Hyperf\DTO\JsonMapper; +use Hyperf\DTO\Scan\MethodParameter; use Hyperf\DTO\Scan\MethodParametersManager; use Hyperf\DTO\Scan\PropertyEnum; use Hyperf\DTO\Scan\PropertyManager; +use HyperfTest\ApiDocs\Request\AccessorSchema; +use HyperfTest\ApiDocs\Request\AliasRequired; +use HyperfTest\ApiDocs\Request\InputAccessibility; use HyperfTest\ApiDocs\Request\PrivateAlias; +use HyperfTest\ApiDocs\Request\SchemaPayment; +use HyperfTest\ApiDocs\Request\SchemaPaymentInterface; use Mockery as m; +use OpenApi\Generator; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -60,15 +69,139 @@ public function testPathParamWithRegexConstraint(): void } /** - * DTO 4.0 不再生成别名 setter,私有 JSONField 属性仍应生成参数. + * DTO 4.0 的私有别名属性没有业务 setter 时不可写,不应生成请求参数. */ - public function testPrivateJsonFieldAliasWithoutSetter(): void + public function testPrivateJsonFieldAliasWithoutSetterIsNotParameter(): void { (new JSONField('name_arr'))->collectProperty(PrivateAlias::class, 'nameArr'); $parameters = $this->createGenerateParameters()->getParameterArrByClass(PrivateAlias::class, 'query'); + $this->assertCount(0, $parameters); + } + + public function testPublicJsonFieldAliasIsParameter(): void + { + (new JSONField('display_name'))->collectProperty(AliasRequired::class, 'displayName'); + (new Required())->collectProperty(AliasRequired::class, 'displayName'); + $parameters = $this->createGenerateParameters()->getParameterArrByClass(AliasRequired::class, 'query'); + + $this->assertCount(1, $parameters); + $this->assertSame('display_name', $parameters[0]->name); + $this->assertTrue($parameters[0]->required); + } + + public function testReadonlyAndStaticPropertiesAreNotParameters(): void + { + $parameters = $this->createGenerateParameters()->getParameterArrByClass(InputAccessibility::class, 'query'); + $this->assertCount(1, $parameters); - $this->assertSame('name_arr', $parameters[0]->name); + $this->assertSame('name', $parameters[0]->name); + } + + public function testAccessorAndComplexQuerySchemas(): void + { + (new JSONField('name_arr'))->collectProperty(AccessorSchema::class, 'nameArr'); + (new Required())->collectProperty(AccessorSchema::class, 'nameArr'); + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + $parameters = $this->createGenerateParameters(swaggerCommon: $swaggerCommon)->getParameterArrByClass(AccessorSchema::class, 'query'); + $parameters = $this->parametersByName($parameters); + + $this->assertArrayNotHasKey('status', $parameters); + $this->assertArrayNotHasKey('internal', $parameters); + $this->assertArrayHasKey('id', $parameters); + $this->assertTrue($parameters['name_arr']->required); + $this->assertSame('#/components/schemas/Address', $parameters['tag']->schema->ref); + $this->assertSame('#/components/schemas/SchemaPayment', $parameters['payment']->schema->ref); + $this->assertSame(Generator::UNDEFINED, $parameters['ids']->schema->items->type); + $this->assertSame(Generator::UNDEFINED, $parameters['payload']->schema->type); + } + + public function testIgnoreVisibilityAllowsPrivateParameters(): void + { + $mapper = new JsonMapper(); + $mapper->bIgnoreVisibility = true; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + + $parameters = $this->createGenerateParameters(swaggerCommon: $swaggerCommon) + ->getParameterArrByClass(AccessorSchema::class, 'query'); + $parameters = $this->parametersByName($parameters); + + $this->assertArrayHasKey('status', $parameters); + $this->assertArrayHasKey('internal', $parameters); + } + + public function testInterfaceMethodParameterUsesClassMapForRequestBody(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + $methodParameter = (new MethodParameter())->setIsRequestBody(true); + $manager = m::mock(MethodParametersManager::class); + $manager->shouldReceive('getMethodParameter')->with('DemoController', 'list', 'payment')->andReturn($methodParameter); + + $result = $this->createGenerateParameters('/', [ + $this->reflectionType(SchemaPaymentInterface::class, 'payment'), + ], $swaggerCommon, $manager)->generate(); + + $this->assertSame('#/components/schemas/SchemaPayment', $result['requestBody']->content[0]->schema->ref); + } + + public function testInterfaceMethodParameterUsesClassMapForQuery(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + $methodParameter = (new MethodParameter())->setIsRequestQuery(true); + $manager = m::mock(MethodParametersManager::class); + $manager->shouldReceive('getMethodParameter')->with('DemoController', 'list', 'payment')->andReturn($methodParameter); + + $result = $this->createGenerateParameters('/', [ + $this->reflectionType(SchemaPaymentInterface::class, 'payment'), + ], $swaggerCommon, $manager)->generate(); + + $this->assertCount(1, $result['parameter']); + $this->assertSame('provider', $result['parameter'][0]->name); + } + + public function testRequestBodyArrayHasItemsWithoutNullComponent(): void + { + $generateParameters = $this->createGenerateParameters(); + $method = new \ReflectionMethod($generateParameters, 'getJsonContent'); + $method->setAccessible(true); + + $schema = $method->invoke($generateParameters, 'array'); + $property = new \ReflectionProperty($generateParameters, 'swaggerComponents'); + $property->setAccessible(true); + $components = $property->getValue($generateParameters); + + $this->assertSame('array', $schema->type); + $this->assertSame(Generator::UNDEFINED, $schema->items->type); + $this->assertArrayNotHasKey('Null', $components->getSchemas()); + } + + public function testRequestBodyInterfaceMatrixUsesClassMapAndArrayDepth(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + $generateParameters = $this->createGenerateParameters(swaggerCommon: $swaggerCommon); + $property = (new PropertyManager($swaggerCommon, new PropertyEnum())) + ->createPropertyFromType(SchemaPaymentInterface::class . '[][]', ''); + $method = new \ReflectionMethod($generateParameters, 'getJsonContent'); + $method->setAccessible(true); + + $schema = $method->invoke($generateParameters, 'array', $property); + + $this->assertSame('array', $schema->type); + $this->assertSame('array', $schema->items->type); + $this->assertSame('#/components/schemas/SchemaPayment', $schema->items->items->ref); } private function reflectionType(string $type, string $name, bool $allowsNull = false, bool $defaultValueAvailable = false): ReflectionType @@ -81,10 +214,11 @@ private function reflectionType(string $type, string $name, bool $allowsNull = f ]); } - private function createGenerateParameters(string $route = '/', array $definitions = []): GenerateParameters + private function createGenerateParameters(string $route = '/', array $definitions = [], ?SwaggerCommon $swaggerCommon = null, ?MethodParametersManager $methodParametersManager = null): GenerateParameters { - $swaggerCommon = new SwaggerCommon(); + $swaggerCommon ??= new SwaggerCommon(); $container = m::mock(ContainerInterface::class); + $container->shouldReceive('has')->andReturn(false); $methodDefinitionCollector = m::mock(MethodDefinitionCollectorInterface::class); $methodDefinitionCollector->shouldReceive('getParameters')->andReturn($definitions); @@ -99,10 +233,19 @@ private function createGenerateParameters(string $route = '/', array $definition new SwaggerComponents($swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), null), $swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), - m::mock(MethodParametersManager::class), + $methodParametersManager ?? m::mock(MethodParametersManager::class), ); } + private function parametersByName(array $parameters): array + { + $result = []; + foreach ($parameters as $parameter) { + $result[$parameter->name] = $parameter; + } + return $result; + } + private function generate(string $route, array $definitions): array { return $this->createGenerateParameters($route, $definitions)->generate(); diff --git a/tests/GenerateProxyClassTest.php b/tests/GenerateProxyClassTest.php index e7a109a..9b978d7 100644 --- a/tests/GenerateProxyClassTest.php +++ b/tests/GenerateProxyClassTest.php @@ -12,8 +12,11 @@ use Hyperf\ApiDocs\Swagger\SwaggerConfig; use Hyperf\Di\Annotation\AnnotationCollector; use Hyperf\DTO\DtoConfig; +use Hyperf\DTO\Type\PhpType; use HyperfTest\ApiDocs\Request\Address; use HyperfTest\ApiDocs\Request\Page; +use HyperfTest\ApiDocs\Request\ProxyNullableDefaults; +use HyperfTest\ApiDocs\Request\ProxyWithHelper; use HyperfTest\ApiDocs\Request\User; use Mockery as m; use PHPUnit\Framework\TestCase; @@ -33,7 +36,7 @@ protected function setUp(): void protected function tearDown(): void { m::close(); - AnnotationCollector::clear(Page::class); + AnnotationCollector::clear(); } /** @@ -86,6 +89,38 @@ public function testApiResponseTypesKeyMustBeString(): void new ApiResponse(Page::class, 200, 'ok', [123 => Address::class]); } + public function testGenerateProxyKeepsHelperClassName(): void + { + (new ApiVariable())->collectProperty(ProxyWithHelper::class, 'content'); + $proxy = $this->makeGenerateProxyClass(); + $proxyClass = $proxy->generateByTypes(ProxyWithHelper::class, ['content' => [Address::class]]); + $filename = sys_get_temp_dir() . '/api_docs_proxy_test/' . str_replace('\\', '_', $proxyClass) . '.dto.proxy.php'; + + $this->assertFileExists($filename); + $content = file_get_contents($filename); + $this->assertSame(1, substr_count($content, 'class ProxyWithHelperArrayAddress')); + $this->assertSame(1, substr_count($content, 'class ProxyHelper')); + } + + public function testGeneratedProxyRemovesIncompatibleDefaults(): void + { + (new ApiVariable())->collectProperty(ProxyNullableDefaults::class, 'data'); + (new ApiVariable())->collectProperty(ProxyNullableDefaults::class, 'content'); + $proxy = $this->makeGenerateProxyClass(); + $proxyClass = $proxy->generateByTypes(ProxyNullableDefaults::class, [ + 'data' => PhpType::INT, + 'content' => null, + ]); + $filename = sys_get_temp_dir() . '/api_docs_proxy_test/' . str_replace('\\', '_', $proxyClass) . '.dto.proxy.php'; + + $content = file_get_contents($filename); + $this->assertStringContainsString('public int $data;', $content); + $this->assertStringNotContainsString('public int $data = null', $content); + + require $filename; + $this->assertTrue(class_exists($proxyClass, false)); + } + private function makeGenerateProxyClass(): GenerateProxyClass { $swaggerConfig = m::mock(SwaggerConfig::class); diff --git a/tests/GenerateResponsesTest.php b/tests/GenerateResponsesTest.php index 79ab5ed..0353af4 100644 --- a/tests/GenerateResponsesTest.php +++ b/tests/GenerateResponsesTest.php @@ -12,12 +12,16 @@ use Hyperf\ApiDocs\Swagger\SwaggerConfig; use Hyperf\Di\MethodDefinitionCollector; use Hyperf\Di\MethodDefinitionCollectorInterface; +use Hyperf\DTO\JsonMapper; use Hyperf\DTO\Scan\PropertyEnum; use Hyperf\DTO\Scan\PropertyManager; use HyperfTest\ApiDocs\Request\Address; use HyperfTest\ApiDocs\Request\DemoBodyRequest; use HyperfTest\ApiDocs\Request\Page; +use HyperfTest\ApiDocs\Request\SchemaPayment; +use HyperfTest\ApiDocs\Request\SchemaPaymentInterface; use Mockery as m; +use OpenApi\Generator; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -111,13 +115,72 @@ public function testApiResponseWithTypes(): void $this->assertSame('#/components/schemas/Address', $resp206->content['application/json']->schema->ref); } - private function makeGenerateResponses(SwaggerConfig $swaggerConfig, array $apiResponseArr, ?GenerateProxyClass $proxy = null, array $containerHasClasses = []): GenerateResponses + public function testMixedResponseHasUnconstrainedSchema(): void + { + $swaggerConfig = m::mock(SwaggerConfig::class); + $swaggerConfig->shouldReceive('getGlobalReturnResponsesClass')->andReturn(''); + $generateResponses = $this->makeGenerateResponses($swaggerConfig, []); + + $content = $this->invokeGetContent($generateResponses, 'mixed'); + + $this->assertSame(Generator::UNDEFINED, $content['text/plain']->schema->type); + } + + public function testInterfaceResponseUsesClassMap(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerCommon = new SwaggerCommon(); + $swaggerCommon->setDtoMapper($mapper); + $swaggerConfig = m::mock(SwaggerConfig::class); + $swaggerConfig->shouldReceive('getGlobalReturnResponsesClass')->andReturn(''); + $generateResponses = $this->makeGenerateResponses($swaggerConfig, [], swaggerCommon: $swaggerCommon); + + $content = $this->invokeGetContent($generateResponses, SchemaPaymentInterface::class); + + $this->assertSame('#/components/schemas/SchemaPayment', $content['application/json']->schema->ref); + } + + public function testUnresolvedInterfaceResponseHasObjectContent(): void + { + $swaggerConfig = m::mock(SwaggerConfig::class); + $swaggerConfig->shouldReceive('getGlobalReturnResponsesClass')->andReturn(''); + $generateResponses = $this->makeGenerateResponses($swaggerConfig, []); + + $content = $this->invokeGetContent($generateResponses, SchemaPaymentInterface::class); + + $this->assertSame('object', $content['application/json']->schema->type); + } + + public function testNestedArrayResponseItemsHaveUnconstrainedType(): void + { + $swaggerConfig = m::mock(SwaggerConfig::class); + $swaggerConfig->shouldReceive('getGlobalReturnResponsesClass')->andReturn(''); + $generateResponses = $this->makeGenerateResponses($swaggerConfig, []); + $method = new \ReflectionMethod($generateResponses, 'getContent'); + $method->setAccessible(true); + + $content = $method->invoke($generateResponses, 'array'); + $schema = $content['application/json']->schema; + + $this->assertSame('array', $schema->type); + $this->assertSame(Generator::UNDEFINED, $schema->items->type); + } + + private function invokeGetContent(GenerateResponses $generateResponses, string $type): array + { + $method = new \ReflectionMethod($generateResponses, 'getContent'); + $method->setAccessible(true); + return $method->invoke($generateResponses, $type); + } + + private function makeGenerateResponses(SwaggerConfig $swaggerConfig, array $apiResponseArr, ?GenerateProxyClass $proxy = null, array $containerHasClasses = [], ?SwaggerCommon $swaggerCommon = null): GenerateResponses { $container = m::mock(ContainerInterface::class); $container->shouldReceive('has')->andReturnUsing(fn ($class) => in_array($class, $containerHasClasses, true)); $container->shouldReceive('get')->with(MethodDefinitionCollectorInterface::class)->andReturn(new MethodDefinitionCollector()); - $swaggerCommon = new SwaggerCommon(); + $swaggerCommon ??= new SwaggerCommon(); return new GenerateResponses( DemoBodyRequest::class, 'getBo', diff --git a/tests/Request/AbstractPayment.php b/tests/Request/AbstractPayment.php new file mode 100644 index 0000000..6810abb --- /dev/null +++ b/tests/Request/AbstractPayment.php @@ -0,0 +1,10 @@ +id = $id; + } + + public function setTag(Address $tag): void + { + $this->tag = $tag; + } + + private function setStatus(string $status): void + { + $this->status = $status; + } +} diff --git a/tests/Request/AliasRequired.php b/tests/Request/AliasRequired.php new file mode 100644 index 0000000..8d34fe4 --- /dev/null +++ b/tests/Request/AliasRequired.php @@ -0,0 +1,15 @@ +id = '1'; + } +} diff --git a/tests/Request/InterfaceSchema.php b/tests/Request/InterfaceSchema.php new file mode 100644 index 0000000..1a676e2 --- /dev/null +++ b/tests/Request/InterfaceSchema.php @@ -0,0 +1,21 @@ +data = $data; + $this->content = $content; + } +} diff --git a/tests/Request/ProxyWithHelper.php b/tests/Request/ProxyWithHelper.php new file mode 100644 index 0000000..f3f4e42 --- /dev/null +++ b/tests/Request/ProxyWithHelper.php @@ -0,0 +1,15 @@ +assertEquals('array', $swaggerCommon->getSwaggerType('array')); $this->assertEquals('object', $swaggerCommon->getSwaggerType('object')); $this->assertEquals('string', $swaggerCommon->getSwaggerType('string')); - $this->assertEquals('null', $swaggerCommon->getSwaggerType('unknown')); + $this->assertNull($swaggerCommon->getSwaggerType('unknown')); + $this->assertNull($swaggerCommon->getSwaggerType('mixed')); + } + + public function testGetPhpTypeSupportsInterfaces(): void + { + $swaggerCommon = new SwaggerCommon(); + + $this->assertSame('\\' . SchemaPaymentInterface::class, $swaggerCommon->getPhpType(SchemaPaymentInterface::class)); } public function testGetSimpleType2SwaggerType(): void @@ -144,7 +152,7 @@ public function testSimpleClassNameClear(): void $swaggerCommon->getSimpleClassName('Test\Class\Name'); $swaggerCommon->simpleClassNameClear(); - $reflection = new ReflectionClass($swaggerCommon); + $reflection = new \ReflectionClass($swaggerCommon); $property = $reflection->getProperty('classNameCache'); $property->setAccessible(true); $this->assertEmpty($property->getValue($swaggerCommon)); diff --git a/tests/SwaggerLlmsTest.php b/tests/SwaggerLlmsTest.php new file mode 100644 index 0000000..02897ad --- /dev/null +++ b/tests/SwaggerLlmsTest.php @@ -0,0 +1,26 @@ +setAccessible(true); + + $yaml = $method->invoke(new SwaggerLlms(), ['schema' => ['items' => []]]); + + $this->assertMatchesRegularExpression('/items:\s*\{\s*\}/', $yaml); + $this->assertStringNotContainsString('items: []', $yaml); + } +} diff --git a/tests/SwaggerSchemasTest.php b/tests/SwaggerSchemasTest.php index d72c2ce..79eef0a 100644 --- a/tests/SwaggerSchemasTest.php +++ b/tests/SwaggerSchemasTest.php @@ -10,15 +10,33 @@ use Hyperf\Di\MethodDefinitionCollector; use Hyperf\Di\MethodDefinitionCollectorInterface; use Hyperf\DTO\Annotation\JSONField; +use Hyperf\DTO\Annotation\Validation\Required; +use Hyperf\DTO\Exception\DtoException; +use Hyperf\DTO\JsonMapper; use Hyperf\DTO\Scan\PropertyEnum; use Hyperf\DTO\Scan\PropertyManager; +use HyperfTest\ApiDocs\Request\AbstractPayment; +use HyperfTest\ApiDocs\Request\AbstractSchema; +use HyperfTest\ApiDocs\Request\AccessorSchema; use HyperfTest\ApiDocs\Request\Address; +use HyperfTest\ApiDocs\Request\AliasRequired; +use HyperfTest\ApiDocs\Request\CardPayment; use HyperfTest\ApiDocs\Request\DemoBodyRequest; +use HyperfTest\ApiDocs\Request\EnumSchema; +use HyperfTest\ApiDocs\Request\InputAccessibility; use HyperfTest\ApiDocs\Request\InterfaceSchema; +use HyperfTest\ApiDocs\Request\OtherSchemaPayment; use HyperfTest\ApiDocs\Request\PrivateAlias; +use HyperfTest\ApiDocs\Request\PrivateRefAlias; +use HyperfTest\ApiDocs\Request\SchemaPayment; +use HyperfTest\ApiDocs\Request\SchemaPaymentInterface; +use HyperfTest\ApiDocs\Request\StatusEnum; +use HyperfTest\ApiDocs\Request\StatusInterface; use HyperfTest\ApiDocs\Request\TreeNode; use HyperfTest\ApiDocs\Request\User; use Mockery as m; +use OpenApi\Annotations\Schema; +use OpenApi\Generator; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; @@ -45,7 +63,7 @@ public function testSchemas(): void $schemas = $swaggerComponents->generateSchemas($classname); $properties = $schemas->properties; - //dump($properties);die(); + // dump($properties);die(); $this->assertEquals('int', $properties[0]->property); $this->assertEquals('integer', $properties[0]->type); @@ -95,9 +113,9 @@ public function testSchemas(): void } /** - * DTO 4.0 不再生成别名 setter,私有 JSONField 属性仍应生成 schema 字段. + * 私有别名属性仍可用于响应,但 DTO 4.0 请求输入为只读. */ - public function testPrivateJsonFieldAliasWithoutSetter(): void + public function testPrivateJsonFieldAliasWithoutSetterIsReadOnly(): void { (new JSONField('name_arr'))->collectProperty(PrivateAlias::class, 'nameArr'); $swaggerCommon = new SwaggerCommon(); @@ -107,22 +125,172 @@ public function testPrivateJsonFieldAliasWithoutSetter(): void $this->assertCount(1, $schema->properties); $this->assertSame('name_arr', $schema->properties[0]->property); + $this->assertTrue($schema->properties[0]->readOnly); } - public function testInterfacePropertiesUseNullSchemaType(): void + public function testInterfacePropertiesUseObjectSchemaType(): void { $swaggerCommon = new SwaggerCommon(); $swaggerComponents = new SwaggerComponents($swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), null); $schema = $swaggerComponents->generateSchemas(InterfaceSchema::class); - $properties = []; - foreach ($schema->properties as $property) { - $properties[$property->property] = $property; - } + $properties = $this->propertiesByName($schema); - $this->assertSame('null', $properties['payment']->type); + $this->assertSame('object', $properties['payment']->type); $this->assertSame('array', $properties['payments']->type); - $this->assertSame('null', $properties['payments']->items->type); + $this->assertSame('object', $properties['payments']->items->type); + $this->assertSame(Generator::UNDEFINED, $properties['untyped']->items->type); + $this->assertSame('array', $properties['paymentMatrix']->items->type); + $this->assertSame('object', $properties['paymentMatrix']->items->items->type); + $this->assertSame('array', $properties['intMatrix']->items->type); + $this->assertSame('integer', $properties['intMatrix']->items->items->type); + } + + public function testInterfacePropertiesUseStaticClassMapSchema(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $swaggerComponents = $this->createComponents($mapper); + + $schema = $swaggerComponents->generateSchemas(InterfaceSchema::class); + $properties = $this->propertiesByName($schema); + + $this->assertSame('#/components/schemas/SchemaPayment', $properties['payment']->ref); + $this->assertSame('#/components/schemas/SchemaPayment', $properties['payments']->items->ref); + $this->assertSame('#/components/schemas/SchemaPayment', $properties['paymentMatrix']->items->items->ref); + $this->assertArrayHasKey('SchemaPayment', $swaggerComponents->getSchemas()); + } + + public function testRequiredUsesJsonFieldAlias(): void + { + (new JSONField('display_name'))->collectProperty(AliasRequired::class, 'displayName'); + (new Required())->collectProperty(AliasRequired::class, 'displayName'); + $swaggerCommon = new SwaggerCommon(); + $swaggerComponents = new SwaggerComponents($swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), null); + + $schema = $swaggerComponents->generateSchemas(AliasRequired::class); + + $this->assertSame(['display_name'], $schema->required); + $this->assertSame('display_name', $schema->properties[0]->property); + } + + public function testReadonlyPropertyIsReadOnlyAndStaticPropertyIsSkipped(): void + { + $swaggerCommon = new SwaggerCommon(); + $swaggerComponents = new SwaggerComponents($swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), null); + + $schema = $swaggerComponents->generateSchemas(InputAccessibility::class); + $properties = $this->propertiesByName($schema); + + $this->assertArrayNotHasKey('static', $properties); + $this->assertTrue($properties['id']->readOnly); + $this->assertSame(Generator::UNDEFINED, $properties['name']->readOnly); + } + + public function testReadOnlyReferenceSurvivesJsonSerialization(): void + { + (new JSONField('the_address'))->collectProperty(PrivateRefAlias::class, 'address'); + $swaggerComponents = $this->createComponents(); + + $schema = $swaggerComponents->generateSchemas(PrivateRefAlias::class); + $data = json_decode(json_encode($schema), true, 512, JSON_THROW_ON_ERROR); + $property = $data['properties']['the_address']; + + $this->assertTrue($property['readOnly']); + $this->assertSame('#/components/schemas/Address', $property['allOf'][0]['$ref']); + $this->assertArrayNotHasKey('$ref', $property); + } + + public function testAccessorVisibilityRequiredAndComplexParameterTypes(): void + { + $this->collectAccessorAnnotations(); + $swaggerComponents = $this->createComponents(); + + $schema = $swaggerComponents->generateSchemas(AccessorSchema::class); + $properties = $this->propertiesByName($schema); + + $this->assertArrayNotHasKey('status', $properties); + $this->assertArrayNotHasKey('internal', $properties); + $this->assertSame(Generator::UNDEFINED, $properties['id']->readOnly); + $this->assertSame(Generator::UNDEFINED, $properties['name_arr']->readOnly); + $this->assertContains('name_arr', $schema->required); + $this->assertSame('#/components/schemas/Address', $properties['tag']->ref); + $this->assertSame('object', $properties['payment']->type); + $this->assertSame(Generator::UNDEFINED, $properties['ids']->items->type); + $this->assertSame(Generator::UNDEFINED, $properties['payload']->type); + } + + public function testIgnoreVisibilityUsesDtoAccessorRules(): void + { + $this->collectAccessorAnnotations(); + $mapper = new JsonMapper(); + $mapper->bIgnoreVisibility = true; + $swaggerComponents = $this->createComponents($mapper); + + $properties = $this->propertiesByName($swaggerComponents->generateSchemas(AccessorSchema::class)); + + $this->assertArrayHasKey('status', $properties); + $this->assertArrayHasKey('internal', $properties); + $this->assertSame(Generator::UNDEFINED, $properties['status']->readOnly); + $this->assertSame(Generator::UNDEFINED, $properties['internal']->readOnly); + } + + public function testAbstractClassUsesClassMapSchema(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[AbstractPayment::class] = CardPayment::class; + $swaggerComponents = $this->createComponents($mapper); + + $properties = $this->propertiesByName($swaggerComponents->generateSchemas(AbstractSchema::class)); + + $this->assertSame('#/components/schemas/CardPayment', $properties['payment']->ref); + $this->assertArrayHasKey('CardPayment', $swaggerComponents->getSchemas()); + } + + public function testClassMapEnumTargetUsesScalarEnumSchema(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[StatusInterface::class] = StatusEnum::class; + $swaggerComponents = $this->createComponents($mapper); + + $properties = $this->propertiesByName($swaggerComponents->generateSchemas(EnumSchema::class)); + + $this->assertSame('string', $properties['status']->type); + $this->assertSame(['active', 'disabled'], $properties['status']->enum); + $this->assertArrayNotHasKey('StatusEnum', $swaggerComponents->getSchemas()); + } + + public function testClassMapLeadingSlashKeyTakesPriority(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = SchemaPayment::class; + $mapper->classMap['\\' . SchemaPaymentInterface::class] = OtherSchemaPayment::class; + $swaggerComponents = $this->createComponents($mapper); + + $schema = $swaggerComponents->createSchema(type: SchemaPaymentInterface::class); + + $this->assertSame('#/components/schemas/OtherSchemaPayment', $schema->ref); + } + + public function testCallableClassMapUsesDtoResolver(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = static fn ($type, $value) => SchemaPayment::class; + $swaggerComponents = $this->createComponents($mapper); + + $schema = $swaggerComponents->createSchema(type: SchemaPaymentInterface::class); + + $this->assertSame('#/components/schemas/SchemaPayment', $schema->ref); + } + + public function testInvalidClassMapTargetThrows(): void + { + $mapper = new JsonMapper(); + $mapper->classMap[SchemaPaymentInterface::class] = 'Missing\PaymentClass'; + $swaggerComponents = $this->createComponents($mapper); + + $this->expectException(DtoException::class); + $swaggerComponents->createSchema(type: SchemaPaymentInterface::class); } public function testGetPropertiesWithEmptyClassName(): void @@ -211,4 +379,28 @@ public function testCircularReferenceSchemas(): void $swaggerCommon->simpleClassNameClear(); } + + private function createComponents(?JsonMapper $mapper = null): SwaggerComponents + { + $swaggerCommon = new SwaggerCommon(); + if ($mapper !== null) { + $swaggerCommon->setDtoMapper($mapper); + } + return new SwaggerComponents($swaggerCommon, new PropertyManager($swaggerCommon, new PropertyEnum()), null); + } + + private function collectAccessorAnnotations(): void + { + (new JSONField('name_arr'))->collectProperty(AccessorSchema::class, 'nameArr'); + (new Required())->collectProperty(AccessorSchema::class, 'nameArr'); + } + + private function propertiesByName(Schema $schema): array + { + $properties = []; + foreach ($schema->properties as $property) { + $properties[$property->property] = $property; + } + return $properties; + } }