|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | +/** |
| 5 | + * This file is part of MineAdmin. |
| 6 | + * |
| 7 | + * @link https://www.mineadmin.com |
| 8 | + * @document https://doc.mineadmin.com |
| 9 | + |
| 10 | + * @license https://github.com/mineadmin/MineAdmin/blob/master/LICENSE |
| 11 | + */ |
| 12 | + |
| 13 | +namespace Mine\Swagger\Attributes; |
| 14 | + |
| 15 | +use Hyperf\Swagger\Annotation\JsonContent; |
| 16 | +use Hyperf\Swagger\Annotation\Property; |
| 17 | +use Hyperf\Swagger\Annotation\Response as Base; |
| 18 | +use OpenApi\Generator; |
| 19 | + |
| 20 | +#[\Attribute(\Attribute::IS_REPEATABLE | \Attribute::TARGET_METHOD)] |
| 21 | +class ResultResponse extends Base |
| 22 | +{ |
| 23 | + public function __construct( |
| 24 | + object|string $instance, |
| 25 | + ?string $title = null, |
| 26 | + ?array $examples = null, |
| 27 | + ?string $description = null, |
| 28 | + mixed $example = Generator::UNDEFINED, |
| 29 | + ?array $headers = null, |
| 30 | + ?int $response = 200, |
| 31 | + ) { |
| 32 | + parent::__construct( |
| 33 | + response: $response, |
| 34 | + description: $description, |
| 35 | + headers: $headers, |
| 36 | + content: $this->generatorResponse($instance, $title, $example, $examples), |
| 37 | + ); |
| 38 | + } |
| 39 | + |
| 40 | + protected function parserInstance(object|string $instance): array |
| 41 | + { |
| 42 | + $result = []; |
| 43 | + $reflectionClass = new \ReflectionClass($instance); |
| 44 | + foreach ($reflectionClass->getProperties() as $property) { |
| 45 | + $result[] = $this->parserProperty($property, \is_string($instance) ? $instance : $instance->{$property->getName()}); |
| 46 | + } |
| 47 | + return $result; |
| 48 | + } |
| 49 | + |
| 50 | + protected function parserProperty(\ReflectionProperty $reflectionProperty, mixed $value): Property |
| 51 | + { |
| 52 | + $property = new Property(); |
| 53 | + $property->property = $reflectionProperty->getName(); |
| 54 | + /** @phpstan-ignore-next-line */ |
| 55 | + $typeName = $reflectionProperty->getType()?->getName(); |
| 56 | + if ($property->ref === Generator::UNDEFINED && class_exists($typeName)) { |
| 57 | + $property->ref = $typeName; |
| 58 | + } |
| 59 | + if ($property->ref === Generator::UNDEFINED && \is_object($value)) { |
| 60 | + $property->ref = $value::class; |
| 61 | + } |
| 62 | + if ($property->ref === Generator::UNDEFINED && \is_string($value) && class_exists($value)) { |
| 63 | + $property->ref = $value; |
| 64 | + } |
| 65 | + return $property; |
| 66 | + } |
| 67 | + |
| 68 | + private function generatorResponse(object|string $instance, ?string $title, mixed $example, ?array $examples = []): JsonContent |
| 69 | + { |
| 70 | + $properties = $this->parserInstance($instance); |
| 71 | + return new JsonContent(examples: $examples, title: $title, properties: $properties, example: $example); |
| 72 | + } |
| 73 | +} |
0 commit comments