Debian Codegraph @

vendor/zircote/swagger-php/src/Annotations/OpenApi.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\Generator;
11 use OpenApi\OpenApiException;
12
13 /**
14 * This is the root document object for the API specification.
15 *
16 * @see [OpenApi Object](https://spec.openapis.org/oas/v3.1.1.html#openapi-object)
17 *
18 * @Annotation
19 */
20 class OpenApi extends AbstractAnnotation
21 {
22 public const VERSION_3_0_0 = '3.0.0';
23
24 public const VERSION_3_1_0 = '3.1.0';
25
26 public const VERSION_3_2_0 = '3.2.0';
27
28 public const DEFAULT_VERSION = self::VERSION_3_0_0;
29
30 public const SUPPORTED_VERSIONS = [
31 self::VERSION_3_0_0, '3.0.1', '3.0.2', '3.0.3', '3.0.4',
32 self::VERSION_3_1_0, '3.1.1', '3.1.2',
33 self::VERSION_3_2_0,
34 ];
35
36 /**
37 * The semantic version number of the OpenAPI Specification version that the OpenAPI document uses.
38 *
39 * The openapi field should be used by tooling specifications and clients to interpret the OpenAPI document.
40 *
41 * A version specified via <code>Generator::setVersion()</code> will overwrite this value.
42 *
43 * NOTE: This is not related to the API info::version string.
44 *
45 * @var string
46 */
47 public $openapi = self::DEFAULT_VERSION;
48
49 /**
50 * Provides metadata about the API. The metadata may be used by tooling as required.
51 *
52 * @var Info
53 */
54 public $info = Generator::UNDEFINED;
55
56 /**
57 * An array of <code>@Server</code> objects, which provide connectivity information to a target server.
58 *
59 * If not provided, or is an empty array, the default value would be a Server Object with an url value of <code>/</code>.
60 *
61 * @var list<Server>
62 */
63 public $servers = Generator::UNDEFINED;
64
65 /**
66 * The available paths and operations for the API.
67 *
68 * @var array<PathItem>
69 */
70 public $paths = Generator::UNDEFINED;
71
72 /**
73 * An element to hold various components for the specification.
74 *
75 * @var Components
76 */
77 public $components = Generator::UNDEFINED;
78
79 /**
80 * A declaration of which security mechanisms can be used across the API.
81 *
82 * The list of values includes alternative security requirement objects that can be used.
83 * Only one of the security requirement objects need to be satisfied to authorize a request.
84 * Individual operations can override this definition.
85 * To make security optional, an empty security requirement (<code>{}</code>) can be included in the array.
86 *
87 * @var array
88 */
89 public $security = Generator::UNDEFINED;
90
91 /**
92 * A list of tags used by the specification with additional metadata.
93 *
94 * The order of the tags can be used to reflect on their order by the parsing tools.
95 * Not all tags that are used by the Operation Object must be declared.
96 * The tags that are not declared may be organized randomly or based on the tools' logic.
97 * Each tag name in the list must be unique.
98 *
99 * @var list<Tag>
100 */
101 public $tags = Generator::UNDEFINED;
102
103 /**
104 * Additional external documentation.
105 *
106 * @var ExternalDocumentation
107 */
108 public $externalDocs = Generator::UNDEFINED;
109
110 /**
111 * The available webhooks for the API.
112 *
113 * @since OpenAPI 3.1.0
114 * @var list<Webhook>
115 */
116 public $webhooks = Generator::UNDEFINED;
117
118 /**
119 * @var Analysis
120 */
121 public $_analysis = Generator::UNDEFINED;
122
123 /**
124 * @inheritdoc
125 */
126 public static $_required = ['openapi', 'info'];
127
128 /**
129 * @inheritdoc
130 */
131 public static $_nested = [
132 Info::class => 'info',
133 Server::class => ['servers'],
134 PathItem::class => ['paths', 'path'],
135 Components::class => 'components',
136 Tag::class => ['tags'],
137 ExternalDocumentation::class => 'externalDocs',
138 Webhook::class => ['webhooks', 'webhook'],
139 Attachable::class => ['attachables'],
140 ];
141
142 /**
143 * @inheritdoc
144 */
145 public static $_types = [];
146
147 public function __construct(array $properties)
148 {
149 parent::__construct($properties);
150
151 if ($this->_context->root()->version) {
152 // override via `Generator::setVersion()`
153 $this->openapi = $this->_context->root()->version;
154 } else {
155 $this->_context->root()->version = $this->openapi;
156 }
157 }
158
159 #[\Override]
160 public function validate(?Analysis $analysis = null, string $version = OpenApi::DEFAULT_VERSION, ?object $context = null): bool
161 {
162 $isValid = parent::validate($analysis, $version, $context);
163
164 if (!in_array($this->openapi, OpenApi::SUPPORTED_VERSIONS)) {
165 $this->_context->logger->warning('Unsupported OpenAPI version "' . $this->openapi . '". Allowed versions are: ' . implode(', ', OpenApi::SUPPORTED_VERSIONS));
166 $isValid = false;
167 }
168
169 /* paths is optional in 3.1.x */
170 if (OpenApi::versionMatch($version, '3.0.x') && Generator::isDefault($this->paths)) {
171 $this->_context->logger->warning('Required @OA\PathItem() not found');
172 $isValid = false;
173 }
174
175 if (OpenApi::versionMatch($version, '3.1.x')
176 && Generator::isDefault($this->paths)
177 && Generator::isDefault($this->webhooks)
178 && Generator::isDefault($this->components)
179 ) {
180 $this->_context->logger->warning('At least one of @OA\PathItem(), @OA\Components() or @OA\Webhook() required');
181 $isValid = false;
182 }
183
184 return $isValid;
185 }
186
187 /**
188 * Compare OpenApi version numbers.
189 *
190 * Allows patch version placeholder `x`; e.g. `3.1.x`.
191 */
192 public static function versionMatch(string $version1, string $version2): bool
193 {
194 $expand = static function (string $v): array {
195 if (!str_ends_with($v, '.x')) {
196 return [$v];
197 }
198 $minor = str_replace('.x', '', $v);
199
200 return array_filter(self::SUPPORTED_VERSIONS, static fn (string $sv): bool => str_starts_with($sv, $minor));
201 };
202 $versions1 = $expand($version1);
203 $versions2 = $expand($version2);
204
205 return array_intersect($versions1, $versions2) !== [];
206 }
207
208 /**
209 * Save the OpenAPI documentation to a file.
210 */
211 public function saveAs(string $filename, string $format = 'auto'): void
212 {
213 if ($format === 'auto') {
214 $format = strtolower(substr($filename, -5)) === '.json' ? 'json' : 'yaml';
215 }
216
217 $content = strtolower($format) === 'json' ? $this->toJson() : $this->toYaml();
218
219 if (file_put_contents($filename, $content) === false) {
220 throw new OpenApiException('Failed to saveAs("' . $filename . '", "' . $format . '")');
221 }
222 }
223
224 /**
225 * Look up an annotation with a $ref url.
226 *
227 * @param string $ref The $ref value; example: "#/components/schemas/Product"
228 */
229 public function ref(string $ref)
230 {
231 if (!str_starts_with($ref, '#/')) {
232 throw new OpenApiException('Unsupported $ref "' . $ref . '", it should start with "#/"');
233 }
234
235 return self::resolveRef($ref, '#/', $this, []);
236 }
237
238 /**
239 * Recursive helper for ref().
240 *
241 * @param array|AbstractAnnotation $container
242 * @param array<class-string<AbstractAnnotation>,string|array<string>> $mapping
243 */
244 private static function resolveRef(string $ref, string $resolved, $container, array $mapping)
245 {
246 if ($ref === $resolved) {
247 return $container;
248 }
249 $path = substr($ref, strlen($resolved));
250 $slash = strpos($path, '/');
251
252 $subpath = $slash === false ? $path : substr($path, 0, $slash);
253 $property = Components::refDecode($subpath);
254 $unresolved = $slash === false ? $resolved . $subpath : $resolved . $subpath . '/';
255
256 if (is_object($container)) {
257 // support use x-* in ref
258 $xKey = str_starts_with($property, 'x-') ? substr($property, 2) : null;
259 if ($xKey) {
260 if (!is_array($container->x) || !array_key_exists($xKey, $container->x)) {
261 $xKey = null;
262 }
263 }
264 if (property_exists($container, $property) === false && !$xKey) {
265 throw new OpenApiException('$ref "' . $ref . '" not found');
266 }
267
268 $nextContainer = $xKey ? $container->x[$xKey] : $container->{$property};
269
270 if ($slash === false) {
271 return $nextContainer;
272 }
273 $mapping = [];
274 foreach ($container::$_nested as $nestedClass => $nested) {
275 if (is_string($nested) === false && count($nested) === 2 && $nested[0] === $property) {
276 $mapping[$nestedClass] = $nested[1];
277 }
278 }
279
280 return self::resolveRef($ref, $unresolved, $nextContainer, $mapping);
281 } elseif (is_array($container)) {
282 if (array_key_exists($property, $container)) {
283 return self::resolveRef($ref, $unresolved, $container[$property], []);
284 }
285 foreach ($mapping as $nestedClass => $keyField) {
286 foreach ($container as $key => $item) {
287 if (is_numeric($key) && is_object($item) && $item instanceof $nestedClass && (string) $item->{$keyField} === $property) {
288 return self::resolveRef($ref, $unresolved, $item, []);
289 }
290 }
291 }
292 }
293
294 throw new OpenApiException('$ref "' . $unresolved . '" not found');
295 }
296
297 public function jsonSerialize(): \stdClass
298 {
299 $data = parent::jsonSerialize();
300
301 if ($this->_context->isVersion('3.0.x')) {
302 unset($data->webhooks);
303 }
304
305 return $data;
306 }
307 }