Debian Codegraph @

vendor/zircote/swagger-php/src/Annotations/AbstractAnnotation.php

raw
1 <?php declare(strict_types=1);
2
3 /**
4 * @license Apache 2.0
5 */
6
7 namespace OpenApi\Annotations;
8
9 use OpenApi\Analysis;
10 use OpenApi\Annotations as OA;
11 use OpenApi\Context;
12 use OpenApi\Generator;
13 use OpenApi\OpenApiException;
14 use Symfony\Component\Yaml\Yaml;
15
16 /**
17 * The openapi annotation base class.
18 */
19 abstract class AbstractAnnotation implements \JsonSerializable
20 {
21 /**
22 * While the OpenAPI Specification tries to accommodate most use cases, additional data can be added to extend the specification at certain points.
23 * For further details see https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#specificationExtensions
24 * The keys inside the array will be prefixed with <code>x-</code>.
25 *
26 * @var array<string,mixed>
27 */
28 public $x = Generator::UNDEFINED;
29
30 /**
31 * Arbitrary attachables for this annotation.
32 * These will be ignored but can be used for custom processing.
33 *
34 * @var array
35 */
36 public $attachables = Generator::UNDEFINED;
37
38 public Context $_context;
39
40 /**
41 * Annotations that couldn't be merged by mapping or postprocessing.
42 *
43 * @var array
44 */
45 public $_unmerged = [];
46
47 /**
48 * The properties which are required by [the spec](https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md).
49 *
50 * @var list<string>
51 */
52 public static $_required = [];
53
54 /**
55 * Specify the type of the property.
56 *
57 * Examples:
58 * 'name' => 'string' // a string
59 * 'required' => 'boolean', // true or false
60 * 'tags' => '[string]', // string array
61 * 'in' => ["query", "header", "path", "formData", "body"] // must be one on these
62 * 'oneOf' => [Schema::class] // array of schema objects.
63 *
64 * @var array<string,string|array<string>>
65 */
66 public static $_types = [];
67
68 /**
69 * Declarative mapping of Annotation types to properties.
70 *
71 * Examples:
72 * Info::class => 'info', // Set @OA\Info annotation as the info property.
73 * Parameter::class => ['parameters'], // Append @OA\Parameter annotations the parameters list.
74 * PathItem::class => ['paths', 'path'], // Add @OA\PathItem annotation to the `paths` map and use `path` as key.
75 *
76 * @var array<class-string<AbstractAnnotation>,string|array<string>>
77 */
78 public static $_nested = [];
79
80 /**
81 * Reverse mapping of $_nested with the allowed parent annotations.
82 *
83 * @var array<class-string<AbstractAnnotation>>
84 */
85 public static $_parents = [];
86
87 /**
88 * Properties that are blacklisted from the JSON output.
89 *
90 * @var array<string>
91 */
92 public static $_blacklist = ['_context', '_unmerged', '_analysis', 'attachables'];
93
94 public function __construct(array $properties)
95 {
96 if (isset($properties['_context'])) {
97 $this->_context = $properties['_context'];
98 unset($properties['_context']);
99 } elseif (Generator::$context) {
100 $this->_context = Generator::$context;
101 } else {
102 $this->_context = new Context(['generated' => true]);
103 }
104
105 if ($this->_context->is('annotations') === false) {
106 $this->_context->annotations = [];
107 }
108
109 $this->_context->annotations[] = $this;
110 $nestedContext = new Context(['nested' => $this], $this->_context);
111 foreach ($properties as $property => $value) {
112 if (property_exists($this, $property)) {
113 $this->{$property} = $value;
114 if (is_array($value)) {
115 foreach ($value as $key => $annotation) {
116 if ($annotation instanceof AbstractAnnotation) {
117 $this->{$property}[$key] = $this->nested($annotation, $nestedContext);
118 }
119 }
120 }
121 } elseif ($property !== 'value') {
122 $this->{$property} = $value;
123 } elseif (is_array($value)) {
124 $annotations = [];
125 foreach ($value as $annotation) {
126 if ($annotation instanceof AbstractAnnotation) {
127 $annotations[] = $annotation;
128 } else {
129 $this->_context->logger->warning('Unexpected field in ' . $this->identity() . ' in ' . $this->_context);
130 }
131 }
132 $this->merge($annotations);
133 } elseif (is_object($value)) {
134 $this->merge([$value]);
135 } else {
136 if (!Generator::isDefault($value)) {
137 $this->_context->logger->warning('Unexpected parameter "' . $property . '" in ' . $this->identity());
138 }
139 }
140 }
141 }
142
143 /**
144 * Merge given annotations to their mapped properties configured in static::$_nested.
145 *
146 * Annotations that couldn't be merged are added to the _unmerged array.
147 *
148 * @param list<AbstractAnnotation> $annotations
149 * @param bool $ignore Ignore unmerged annotations
150 *
151 * @return list<AbstractAnnotation> The unmerged annotations
152 */
153 public function merge(array $annotations, bool $ignore = false): array
154 {
155 $unmerged = [];
156 $nestedContext = new Context(['nested' => $this], $this->_context);
157
158 foreach ($annotations as $annotation) {
159 $mapped = false;
160 if ($details = $this->matchNested($annotation)) {
161 $property = $details->value;
162 if (is_array($property)) {
163 $property = $property[0];
164 if (Generator::isDefault($this->{$property})) {
165 $this->{$property} = [];
166 }
167 $this->{$property}[] = $this->nested($annotation, $nestedContext);
168 $mapped = true;
169 } elseif (Generator::isDefault($this->{$property})) {
170 // ignore duplicate nested if only one expected
171 $this->{$property} = $this->nested($annotation, $nestedContext);
172 $mapped = true;
173 }
174 }
175 if (!$mapped) {
176 $unmerged[] = $annotation;
177 }
178 }
179 if (!$ignore) {
180 foreach ($unmerged as $annotation) {
181 $this->_unmerged[] = $this->nested($annotation, $nestedContext);
182 }
183 }
184
185 return $unmerged;
186 }
187
188 /**
189 * Merge the properties from the given object into this annotation.
190 * Prevents overwriting properties that are already configured.
191 *
192 * @param object $object
193 */
194 public function mergeProperties($object): void
195 {
196 $currentValues = get_object_vars($this);
197 foreach ($object as $property => $value) {
198 if ($property === '_context') {
199 continue;
200 }
201 if (Generator::isDefault($currentValues[$property])) {
202 // Overwrite default values
203 $this->{$property} = $value;
204 continue;
205 }
206 if ($property === '_unmerged') {
207 $this->_unmerged = array_merge($this->_unmerged, $value);
208 continue;
209 }
210 if ($currentValues[$property] !== $value) {
211 // New value is not the same?
212 if (Generator::isDefault($value)) {
213 continue;
214 }
215 $identity = method_exists($object, 'identity') ? $object->identity() : $object::class;
216 $context1 = $this->_context;
217 $context2 = property_exists($object, '_context') ? $object->_context : 'unknown';
218 if ($this->{$property} instanceof AbstractAnnotation) {
219 $context1 = $this->{$property}->_context;
220 }
221 $this->_context->logger->error('Multiple definitions for ' . $identity . '->' . $property . "\n Using: " . $context1 . "\n Skipping: " . $context2);
222 }
223 }
224 }
225
226 /**
227 * Generate the documentation in YAML format.
228 *
229 * @param int-mask-of<Yaml::PARSE_*>|null $flags A bit field of PARSE_* constants to customize the YAML parser behavior
230 */
231 public function toYaml(?int $flags = null): string
232 {
233 if ($flags === null) {
234 $flags = Yaml::DUMP_OBJECT_AS_MAP ^ Yaml::DUMP_EMPTY_ARRAY_AS_SEQUENCE;
235 }
236
237 return Yaml::dump(json_decode($this->toJson(JSON_INVALID_UTF8_IGNORE)), 10, 2, $flags);
238 }
239
240 /**
241 * Generate the documentation in JSON format.
242 */
243 public function toJson(?int $flags = null): string
244 {
245 if ($flags === null) {
246 $flags = JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_IGNORE;
247 }
248
249 return json_encode($this, $flags);
250 }
251
252 public function __debugInfo()
253 {
254 $properties = [];
255 foreach (get_object_vars($this) as $property => $value) {
256 if (!Generator::isDefault($value)) {
257 $properties[$property] = $value;
258 }
259 }
260
261 return $properties;
262 }
263
264 public function jsonSerialize(): \stdClass
265 {
266 $data = new \stdClass();
267
268 // Strip undefined values.
269 foreach (get_object_vars($this) as $property => $value) {
270 if (!Generator::isDefault($value)) {
271 $data->{$property} = $value;
272 }
273 }
274
275 // Strip properties that are for internal (swagger-php) use.
276 foreach (static::$_blacklist as $property) {
277 unset($data->{$property});
278 }
279
280 // Correct empty array to empty objects.
281 foreach (static::$_types as $property => $type) {
282 if ($type === 'object' && is_array($data->{$property}) && $data->{$property} === []) {
283 $data->{$property} = new \stdClass();
284 }
285 }
286
287 // Inject vendor properties.
288 unset($data->x);
289 if (is_array($this->x)) {
290 foreach ($this->x as $property => $value) {
291 $prefixed = 'x-' . $property;
292 $data->{$prefixed} = $value;
293 }
294 }
295
296 // Map nested keys
297 foreach (static::$_nested as $nested) {
298 if (is_string($nested) || count($nested) === 1) {
299 continue;
300 }
301 $property = $nested[0];
302 if (Generator::isDefault($this->{$property})) {
303 continue;
304 }
305 $keyField = $nested[1];
306 $object = new \stdClass();
307 foreach ($this->{$property} as $key => $item) {
308 if (is_numeric($key) === false && is_array($item)) {
309 $object->{$key} = $item;
310 } else {
311 $key = $item->{$keyField} ?? Generator::UNDEFINED;
312 if (!Generator::isDefault($key) && empty($object->{$key})) {
313 $object->{$key} = $item instanceof \JsonSerializable ? $item->jsonSerialize() : $item;
314 unset($object->{$key}->{$keyField});
315 }
316 }
317 }
318 $data->{$property} = $object;
319 }
320
321 // $ref
322 if (isset($data->ref)) {
323 // Only specific https://github.com/OAI/OpenAPI-Specification/blob/3.1.0/versions/3.1.0.md#reference-object
324 $ref = ['$ref' => $data->ref];
325 if (!$this->_context->isVersion('3.0.x')) {
326 foreach (['summary', 'description'] as $prop) {
327 if (property_exists($data, $prop)) {
328 $ref[$prop] = $data->{$prop};
329 }
330 }
331 }
332 if (property_exists($this, 'nullable') && $this->nullable === true) {
333 $ref = ['oneOf' => [$ref]];
334 if (!$this->_context->isVersion('3.0.x')) {
335 $ref['oneOf'][] = ['type' => 'null'];
336 } else {
337 $ref['nullable'] = $data->nullable;
338 }
339 unset($data->ref, $data->nullable);
340
341 // preserve other properties
342 foreach (get_object_vars($data) as $property => $value) {
343 $ref[$property] = $value;
344 }
345 }
346 $data = (object) $ref;
347 }
348
349 if ($this->_context->isVersion('3.0.x')) {
350 if (isset($data->exclusiveMinimum) && is_numeric($data->exclusiveMinimum)) {
351 $data->minimum = $data->exclusiveMinimum;
352 $data->exclusiveMinimum = true;
353 }
354
355 if (isset($data->exclusiveMaximum) && is_numeric($data->exclusiveMaximum)) {
356 $data->maximum = $data->exclusiveMaximum;
357 $data->exclusiveMaximum = true;
358 }
359
360 if (isset($data->type) && is_array($data->type)) {
361 if (in_array('null', $data->type)) {
362 $data->nullable = true;
363 $data->type = array_filter($data->type, static fn ($v): bool => $v !== 'null');
364 if (1 === count($data->type)) {
365 $data->type = array_pop($data->type);
366 }
367 }
368 }
369 if (isset($data->type) && is_array($data->type)) {
370 if (1 === count($data->type)) {
371 $data->type = array_pop($data->type);
372 } else {
373 unset($data->type);
374 }
375 }
376
377 unset($data->unevaluatedProperties);
378 }
379
380 if (!$this->_context->isVersion('3.0.x')) {
381 if (isset($data->nullable)) {
382 if (true === $data->nullable) {
383 if (isset($data->oneOf)) {
384 $data->oneOf[] = ['type' => 'null'];
385 } elseif (isset($data->anyOf)) {
386 $data->anyOf[] = ['type' => 'null'];
387 } elseif (isset($data->allOf)) {
388 $data->allOf[] = ['type' => 'null'];
389 } elseif (isset($data->type)) {
390 $data->type = (array) $data->type;
391 $data->type[] = 'null';
392 }
393 }
394 unset($data->nullable);
395 }
396
397 if (isset($data->minimum) && isset($data->exclusiveMinimum)) {
398 if (true === $data->exclusiveMinimum) {
399 $data->exclusiveMinimum = $data->minimum;
400 unset($data->minimum);
401 } elseif (false === $data->exclusiveMinimum) {
402 unset($data->exclusiveMinimum);
403 }
404 }
405
406 if (isset($data->maximum) && isset($data->exclusiveMaximum)) {
407 if (true === $data->exclusiveMaximum) {
408 $data->exclusiveMaximum = $data->maximum;
409 unset($data->maximum);
410 } elseif (false === $data->exclusiveMaximum) {
411 unset($data->exclusiveMaximum);
412 }
413 }
414 }
415
416 return $data;
417 }
418
419 /**
420 * Validate a given value against a `_$type` definition.
421 */
422 private function validateValueType(string $type, mixed $value): bool
423 {
424 if (str_starts_with($type, '[') && str_ends_with($type, ']')) {
425 // $value must be an array
426 if (!$this->validateValueType('array', $value)) {
427 return false;
428 }
429
430 $itemType = substr($type, 1, -1);
431 foreach ($value as $item) {
432 if (!$this->validateValueType($itemType, $item)) {
433 return false;
434 }
435 }
436
437 return true;
438 }
439
440 if (is_subclass_of($type, AbstractAnnotation::class)) {
441 $type = 'object';
442 }
443
444 $isValidType = fn (string $type, mixed $value): bool => match ($type) {
445 'string' => is_string($value),
446 'boolean' => is_bool($value),
447 'integer' => is_int($value),
448 'number' => is_numeric($value),
449 'object' => is_object($value),
450 'array' => is_array($value) && array_is_list($value),
451 'scheme' => in_array($value, ['http', 'https', 'ws', 'wss'], strict: true),
452 default => throw new OpenApiException('Invalid type "' . $type . '"'),
453 };
454
455 foreach (explode('|', $type) as $tt) {
456 if ($isValidType(trim($tt), $value)) {
457 return true;
458 }
459 }
460
461 return false;
462 }
463
464 public function validate(?Analysis $analysis = null, string $version = OpenApi::DEFAULT_VERSION, ?object $context = null): bool
465 {
466 $isValid = true;
467
468 // validate unmerged
469 foreach ($this->_unmerged as $annotation) {
470 if (!is_object($annotation)) {
471 $this->_context->logger->warning('Unexpected type: "' . gettype($annotation) . '" in ' . $this->identity() . '->_unmerged, expecting a Annotation object');
472 break;
473 }
474
475 if ($details = $this->matchNested($annotation)) {
476 $property = $details->value;
477 if (is_array($property)) {
478 $this->_context->logger->warning('Only one ' . $annotation->identity([]) . ' allowed for ' . $this->identity() . ' multiple found, skipped: ' . $annotation->_context);
479 } else {
480 $this->_context->logger->warning('Only one ' . $annotation->identity([]) . ' allowed for ' . $this->identity() . " multiple found in:\n Using: " . $this->{$property}->_context . "\n Skipped: " . $annotation->_context);
481 }
482 } elseif ($annotation instanceof AbstractAnnotation) {
483 $message = 'Unexpected ' . $annotation->identity();
484 if ($annotation::$_parents) {
485 $message .= ', expected to be inside ' . implode(', ', AbstractAnnotation::shorten($annotation::$_parents));
486 }
487 $this->_context->logger->warning($message . ' in ' . $annotation->_context);
488 }
489
490 $isValid = false;
491 }
492
493 // validate conflicting keys
494 foreach ($this::$_nested as $annotationClass => $nested) {
495 if (is_string($nested) || count($nested) === 1) {
496 continue;
497 }
498 $property = $nested[0];
499 if (Generator::isDefault($this->{$property})) {
500 continue;
501 }
502 $keys = [];
503 $keyField = $nested[1];
504 /** @var AbstractAnnotation $item */
505 foreach ($this->{$property} as $key => $item) {
506 if (is_array($item) && !is_numeric($key)) {
507 $this->_context->logger->warning($this->identity() . '->' . $property . ' is an object literal, use nested ' . AbstractAnnotation::shorten($annotationClass) . '() annotation(s) in ' . $this->_context);
508 $keys[$key] = $item;
509 } elseif (Generator::isDefault($item->{$keyField} ?? Generator::UNDEFINED)) {
510 $this->_context->logger->error($item->identity() . ' is missing key-field: "' . $keyField . '" in ' . $item->_context);
511 } elseif (isset($keys[$item->{$keyField}])) {
512 $this->_context->logger->error('Multiple ' . $item->identity([]) . ' with the same ' . $keyField . '="' . $item->{$keyField} . "\":\n " . $item->_context . "\n " . $keys[$item->{$keyField}]->_context);
513 } else {
514 $keys[$item->{$keyField}] = $item;
515 }
516 }
517 }
518
519 // validate refs
520 if ($analysis?->openapi && property_exists($this, 'ref') && !Generator::isDefault($this->ref) && is_string($this->ref)) {
521 if (str_starts_with($this->ref, '#/')) {
522 try {
523 $analysis->openapi->ref($this->ref);
524 } catch (\Exception $e) {
525 $this->_context->logger->warning($e->getMessage() . ' for ' . $this->identity() . ' in ' . $this->_context, ['exception' => $e]);
526 $isValid = false;
527 }
528 }
529 }
530
531 // validate required properties
532 if (!property_exists($this, 'ref') || Generator::isDefault($this->ref) || !is_string($this->ref)) {
533 foreach ($this::$_required as $property) {
534 if (Generator::isDefault($this->{$property})) {
535 $message = 'Missing required field "' . $property . '" for ' . $this->identity() . ' in ' . $this->_context;
536 foreach ($this::$_nested as $class => $nested) {
537 $nestedProperty = is_array($nested) ? $nested[0] : $nested;
538 if ($property === $nestedProperty) {
539 if ($this instanceof OpenApi) {
540 $message = 'Required ' . AbstractAnnotation::shorten($class) . '() not found';
541 } elseif (is_array($nested)) {
542 $message = $this->identity() . ' requires at least one ' . AbstractAnnotation::shorten($class) . '() in ' . $this->_context;
543 } else {
544 $message = $this->identity() . ' requires a ' . AbstractAnnotation::shorten($class) . '() in ' . $this->_context;
545 }
546 break;
547 }
548 }
549 $this->_context->logger->warning($message);
550 }
551 }
552 }
553
554 // validate types
555 foreach ($this::$_types as $property => $type) {
556 $value = $this->{$property};
557 if (Generator::isDefault($value) || $value === null) {
558 continue;
559 }
560 if (is_string($type)) {
561 if (!$this->validateValueType($type, $value)) {
562 $this->_context->logger->warning($this->identity() . '->' . $property . ' is a "' . gettype($value) . '", expecting a "' . $type . '" in ' . $this->_context);
563 $isValid = false;
564 }
565 } elseif (is_array($type)) { // enum?
566 if (!in_array($value, $type)) {
567 $this->_context->logger->warning($this->identity() . '->' . $property . ' "' . $value . '" is invalid, expecting "' . implode('", "', $type) . '" in ' . $this->_context);
568 }
569 } else {
570 throw new OpenApiException('Invalid ' . static::class . '::$_types[' . $property . ']');
571 }
572 }
573
574 // validate example/examples
575 if (property_exists($this, 'example') && property_exists($this, 'examples')) {
576 if (!Generator::isDefault($this->example) && !Generator::isDefault($this->examples)) {
577 $this->_context->logger->warning($this->identity() . ': "example" and "examples" are mutually exclusive');
578
579 $isValid = false;
580 }
581 }
582
583 return $isValid;
584 }
585
586 /**
587 * Return a simple string representation of the annotation.
588 *
589 * @param array|null $properties the properties to include in the string representation
590 * @example "@OA\Response(response=200)"
591 */
592 public function identity(?array $properties = null): string
593 {
594 $class = static::class;
595
596 if (null === $properties) {
597 $properties = [];
598 /** @var class-string<AbstractAnnotation> $parent */
599 foreach (static::$_parents as $parent) {
600 foreach ($parent::$_nested as $annotationClass => $entry) {
601 if ($annotationClass === $class && is_array($entry) && !Generator::isDefault($this->{$entry[1]})) {
602 $properties[] = $entry[1];
603 break 2;
604 }
605 }
606 }
607 }
608
609 $details = [];
610 foreach ($properties as $property) {
611 $value = $this->{$property};
612 if ($value !== null && !Generator::isDefault($value)) {
613 $details[] = $property . '=' . (is_string($value) ? '"' . $value . '"' : $value);
614 }
615 }
616
617 return static::shorten(static::class) . '(' . implode(',', $details) . ')';
618 }
619
620 /**
621 * Check if <code>$other</code> can be nested, and if so, return details about where/how.
622 *
623 * @param AbstractAnnotation $other the other annotation
624 *
625 * @return null|object key/value object or <code>null</code>
626 */
627 public function matchNested($other)
628 {
629 if ($other instanceof AbstractAnnotation && array_key_exists($root = $other->getRoot(), static::$_nested)) {
630 return (object) ['key' => $root, 'value' => static::$_nested[$root]];
631 }
632
633 return null;
634 }
635
636 /**
637 * Get the root annotation.
638 *
639 * This is used for resolving type equality and nesting rules to allow those rules to also work for custom,
640 * derived annotation classes.
641 *
642 * @return class-string the root annotation class in the <code>OpenApi\\Annotations</code> namespace
643 */
644 public function getRoot(): string
645 {
646 $class = static::class;
647
648 do {
649 if (str_starts_with($class, 'OpenApi\\Annotations\\')) {
650 break;
651 }
652 } while ($class = get_parent_class($class));
653
654 return $class;
655 }
656
657 /**
658 * Match the annotation root.
659 *
660 * @param class-string $thisClass the root class to match
661 */
662 public function isRoot(string $thisClass): bool
663 {
664 return static::class === $thisClass || $this->getRoot() === $thisClass;
665 }
666
667 /**
668 * Wrap the context with a reference to the annotation it is nested in.
669 */
670 protected function nested(AbstractAnnotation $annotation, Context $nestedContext): self
671 {
672 if (property_exists($annotation, '_context') && $annotation->_context === $this->_context) {
673 $annotation->_context = $nestedContext;
674 }
675
676 return $annotation;
677 }
678
679 protected function combine(...$args): array
680 {
681 $combined = [];
682 foreach ($args as $arg) {
683 if (is_array($arg)) {
684 $combined = array_merge($combined, $arg);
685 } else {
686 $combined[] = $arg;
687 }
688 }
689
690 return array_filter($combined, static fn ($value): bool => !Generator::isDefault($value) && $value !== null);
691 }
692
693 /**
694 * Shorten class name(s).
695 *
696 * @param array|object|string $classes Class(es) to shorten
697 *
698 * @return string|list<string> One or more shortened class names
699 */
700 protected static function shorten($classes)
701 {
702 $short = [];
703 foreach ((array) $classes as $class) {
704 $short[] = '@' . str_replace([
705 'OpenApi\\Annotations\\',
706 'OpenApi\\Attributes\\',
707 ], 'OA\\', (string) $class);
708 }
709
710 return is_array($classes) ? $short : array_pop($short);
711 }
712 }