From e3e7f2cdd9cc8887e72c5c68a5fcf081138ed439 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E9=93=AD=E6=98=95?= <715557344@qq.com> Date: Tue, 12 Dec 2023 17:40:33 +0800 Subject: [PATCH] Support to read custom attribute for validation when using swagger. (#6379) --- src/Annotation/Property.php | 3 +- src/Annotation/QueryParameter.php | 1 + src/Request/AttributeCollector.php | 59 ++++++++++++++++++++++++++++++ src/Request/SwaggerRequest.php | 16 ++++++++ 4 files changed, 78 insertions(+), 1 deletion(-) create mode 100644 src/Request/AttributeCollector.php diff --git a/src/Annotation/Property.php b/src/Annotation/Property.php index 2465d5d..446c8b7 100644 --- a/src/Annotation/Property.php +++ b/src/Annotation/Property.php @@ -62,7 +62,8 @@ public function __construct( AdditionalProperties|bool|null $additionalProperties = null, ?array $x = null, ?array $attachables = null, - public mixed $rules = null + public mixed $rules = null, + public mixed $attribute = null ) { parent::__construct( $property, diff --git a/src/Annotation/QueryParameter.php b/src/Annotation/QueryParameter.php index 7e83ab9..92cc582 100644 --- a/src/Annotation/QueryParameter.php +++ b/src/Annotation/QueryParameter.php @@ -45,6 +45,7 @@ public function __construct( ?array $x = null, ?array $attachables = null, public mixed $rules = null, + public mixed $attribute = null, ) { parent::__construct( $parameter, diff --git a/src/Request/AttributeCollector.php b/src/Request/AttributeCollector.php new file mode 100644 index 0000000..480c0e3 --- /dev/null +++ b/src/Request/AttributeCollector.php @@ -0,0 +1,59 @@ +attribute) { + $attributes[$parameter->name] = $parameter->attribute; + } + } + + /** @var RequestBody $body */ + $body = Util::findAnnotations($methodAnnotations, RequestBody::class)[0] ?? null; + if ($body) { + if ($body->_content instanceof JsonContent) { + if (is_array($body->_content->properties)) { + foreach ($body->_content->properties as $property) { + if ($property instanceof Property) { + if ($property->attribute) { + $attributes[$property->property] = $property->attribute; + } + } + } + } + } + } + + return static::$attributes[$class][$method] = $attributes; + } +} diff --git a/src/Request/SwaggerRequest.php b/src/Request/SwaggerRequest.php index 9e05901..705df74 100644 --- a/src/Request/SwaggerRequest.php +++ b/src/Request/SwaggerRequest.php @@ -44,4 +44,20 @@ public function rules(): array return RuleCollector::get($callback[0], $callback[1]); } + + public function attributes(): array + { + /** @var Dispatched $dispatched */ + $dispatched = RequestContext::getOrNull()?->getAttribute(Dispatched::class); + if (! $dispatched) { + throw new RuntimeException('The request is invalid.'); + } + + $callback = $dispatched->handler?->callback; + if (! $callback || ! is_array($callback)) { + throw new RuntimeException('The SwaggerRequest is only used by swagger annotations.'); + } + + return AttributeCollector::get($callback[0], $callback[1]); + } }