1 | <?php |
||
2 | |||
3 | /* |
||
4 | * This file is part of the API Platform project. |
||
5 | * |
||
6 | * (c) Kévin Dunglas <[email protected]> |
||
7 | * |
||
8 | * For the full copyright and license information, please view the LICENSE |
||
9 | * file that was distributed with this source code. |
||
10 | */ |
||
11 | |||
12 | declare(strict_types=1); |
||
13 | |||
14 | namespace ApiPlatform\Core\Swagger\Serializer; |
||
15 | |||
16 | use ApiPlatform\Core\Api\FilterCollection; |
||
17 | use ApiPlatform\Core\Api\FilterLocatorTrait; |
||
18 | use ApiPlatform\Core\Api\FormatsProviderInterface; |
||
19 | use ApiPlatform\Core\Api\OperationAwareFormatsProviderInterface; |
||
20 | use ApiPlatform\Core\Api\OperationMethodResolverInterface; |
||
21 | use ApiPlatform\Core\Api\OperationType; |
||
22 | use ApiPlatform\Core\Api\ResourceClassResolverInterface; |
||
23 | use ApiPlatform\Core\Api\UrlGeneratorInterface; |
||
24 | use ApiPlatform\Core\Documentation\Documentation; |
||
25 | use ApiPlatform\Core\Exception\ResourceClassNotFoundException; |
||
26 | use ApiPlatform\Core\JsonSchema\Schema; |
||
27 | use ApiPlatform\Core\JsonSchema\SchemaFactory; |
||
28 | use ApiPlatform\Core\JsonSchema\SchemaFactoryInterface; |
||
29 | use ApiPlatform\Core\JsonSchema\TypeFactory; |
||
30 | use ApiPlatform\Core\JsonSchema\TypeFactoryInterface; |
||
31 | use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface; |
||
32 | use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface; |
||
33 | use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface; |
||
34 | use ApiPlatform\Core\Metadata\Resource\ResourceMetadata; |
||
35 | use ApiPlatform\Core\Operation\Factory\SubresourceOperationFactoryInterface; |
||
36 | use ApiPlatform\Core\PathResolver\OperationPathResolverInterface; |
||
37 | use Psr\Container\ContainerInterface; |
||
38 | use Symfony\Component\PropertyInfo\Type; |
||
39 | use Symfony\Component\Serializer\NameConverter\NameConverterInterface; |
||
40 | use Symfony\Component\Serializer\Normalizer\CacheableSupportsMethodInterface; |
||
41 | use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
||
42 | |||
43 | /** |
||
44 | * Generates an OpenAPI specification (formerly known as Swagger). OpenAPI v2 and v3 are supported. |
||
45 | * |
||
46 | * @author Amrouche Hamza <[email protected]> |
||
47 | * @author Teoh Han Hui <[email protected]> |
||
48 | * @author Kévin Dunglas <[email protected]> |
||
49 | * @author Anthony GRASSIOT <[email protected]> |
||
50 | */ |
||
51 | final class DocumentationNormalizer implements NormalizerInterface, CacheableSupportsMethodInterface |
||
52 | { |
||
53 | use FilterLocatorTrait; |
||
54 | |||
55 | public const FORMAT = 'json'; |
||
56 | public const BASE_URL = 'base_url'; |
||
57 | public const SPEC_VERSION = 'spec_version'; |
||
58 | public const OPENAPI_VERSION = '3.0.2'; |
||
59 | public const SWAGGER_DEFINITION_NAME = 'swagger_definition_name'; |
||
60 | public const SWAGGER_VERSION = '2.0'; |
||
61 | |||
62 | /** |
||
63 | * @deprecated |
||
64 | */ |
||
65 | public const ATTRIBUTE_NAME = 'swagger_context'; |
||
66 | |||
67 | private $resourceMetadataFactory; |
||
68 | private $propertyNameCollectionFactory; |
||
69 | private $propertyMetadataFactory; |
||
70 | private $operationMethodResolver; |
||
71 | private $operationPathResolver; |
||
72 | private $oauthEnabled; |
||
73 | private $oauthType; |
||
74 | private $oauthFlow; |
||
75 | private $oauthTokenUrl; |
||
76 | private $oauthAuthorizationUrl; |
||
77 | private $oauthScopes; |
||
78 | private $apiKeys; |
||
79 | private $subresourceOperationFactory; |
||
80 | private $paginationEnabled; |
||
81 | private $paginationPageParameterName; |
||
82 | private $clientItemsPerPage; |
||
83 | private $itemsPerPageParameterName; |
||
84 | private $paginationClientEnabled; |
||
85 | private $paginationClientEnabledParameterName; |
||
86 | private $formats; |
||
87 | private $formatsProvider; |
||
88 | /** |
||
89 | * @var SchemaFactoryInterface |
||
90 | */ |
||
91 | private $jsonSchemaFactory; |
||
92 | /** |
||
93 | * @var TypeFactoryInterface |
||
94 | */ |
||
95 | private $jsonSchemaTypeFactory; |
||
96 | private $defaultContext = [ |
||
97 | self::BASE_URL => '/', |
||
98 | ApiGatewayNormalizer::API_GATEWAY => false, |
||
99 | ]; |
||
100 | |||
101 | /** |
||
102 | * @param SchemaFactoryInterface|ResourceClassResolverInterface|null $jsonSchemaFactory |
||
103 | * @param ContainerInterface|FilterCollection|null $filterLocator |
||
104 | * @param array|OperationAwareFormatsProviderInterface $formats |
||
105 | * @param mixed|null $jsonSchemaTypeFactory |
||
106 | * @param int[] $swaggerVersions |
||
107 | */ |
||
108 | public function __construct(ResourceMetadataFactoryInterface $resourceMetadataFactory, PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, $jsonSchemaFactory = null, $jsonSchemaTypeFactory = null, OperationPathResolverInterface $operationPathResolver, UrlGeneratorInterface $urlGenerator = null, $filterLocator = null, NameConverterInterface $nameConverter = null, bool $oauthEnabled = false, string $oauthType = '', string $oauthFlow = '', string $oauthTokenUrl = '', string $oauthAuthorizationUrl = '', array $oauthScopes = [], array $apiKeys = [], SubresourceOperationFactoryInterface $subresourceOperationFactory = null, bool $paginationEnabled = true, string $paginationPageParameterName = 'page', bool $clientItemsPerPage = false, string $itemsPerPageParameterName = 'itemsPerPage', $formats = [], bool $paginationClientEnabled = false, string $paginationClientEnabledParameterName = 'pagination', array $defaultContext = [], array $swaggerVersions = [2, 3]) |
||
109 | { |
||
110 | if ($jsonSchemaTypeFactory instanceof OperationMethodResolverInterface) { |
||
111 | @trigger_error(sprintf('Passing an instance of %s to %s() is deprecated since version 2.5 and will be removed in 3.0.', OperationMethodResolverInterface::class, __METHOD__), E_USER_DEPRECATED); |
||
112 | |||
113 | $this->operationMethodResolver = $jsonSchemaTypeFactory; |
||
114 | $this->jsonSchemaTypeFactory = new TypeFactory(); |
||
115 | } else { |
||
116 | $this->jsonSchemaTypeFactory = $jsonSchemaTypeFactory ?? new TypeFactory(); |
||
117 | } |
||
118 | |||
119 | if ($jsonSchemaFactory instanceof ResourceClassResolverInterface) { |
||
120 | @trigger_error(sprintf('Passing an instance of %s to %s() is deprecated since version 2.5 and will be removed in 3.0.', ResourceClassResolverInterface::class, __METHOD__), E_USER_DEPRECATED); |
||
121 | } |
||
122 | |||
123 | if (null === $jsonSchemaFactory || $jsonSchemaFactory instanceof ResourceClassResolverInterface) { |
||
124 | $jsonSchemaFactory = new SchemaFactory($this->jsonSchemaTypeFactory, $resourceMetadataFactory, $propertyNameCollectionFactory, $propertyMetadataFactory, $nameConverter); |
||
125 | $this->jsonSchemaTypeFactory->setSchemaFactory($jsonSchemaFactory); |
||
126 | } |
||
127 | $this->jsonSchemaFactory = $jsonSchemaFactory; |
||
128 | |||
129 | if ($nameConverter) { |
||
130 | @trigger_error(sprintf('Passing an instance of %s to %s() is deprecated since version 2.5 and will be removed in 3.0.', NameConverterInterface::class, __METHOD__), E_USER_DEPRECATED); |
||
131 | } |
||
132 | |||
133 | if ($urlGenerator) { |
||
134 | @trigger_error(sprintf('Passing an instance of %s to %s() is deprecated since version 2.1 and will be removed in 3.0.', UrlGeneratorInterface::class, __METHOD__), E_USER_DEPRECATED); |
||
135 | } |
||
136 | |||
137 | if ($formats instanceof FormatsProviderInterface) { |
||
138 | @trigger_error(sprintf('Passing an instance of %s to %s() is deprecated since version 2.5 and will be removed in 3.0, pass an array instead.', FormatsProviderInterface::class, __METHOD__), E_USER_DEPRECATED); |
||
139 | |||
140 | $this->formatsProvider = $formats; |
||
141 | } else { |
||
142 | $this->formats = $formats; |
||
143 | } |
||
144 | |||
145 | $this->setFilterLocator($filterLocator, true); |
||
146 | |||
147 | $this->resourceMetadataFactory = $resourceMetadataFactory; |
||
148 | $this->propertyNameCollectionFactory = $propertyNameCollectionFactory; |
||
149 | $this->propertyMetadataFactory = $propertyMetadataFactory; |
||
150 | $this->operationPathResolver = $operationPathResolver; |
||
151 | $this->oauthEnabled = $oauthEnabled; |
||
152 | $this->oauthType = $oauthType; |
||
153 | $this->oauthFlow = $oauthFlow; |
||
154 | $this->oauthTokenUrl = $oauthTokenUrl; |
||
155 | $this->oauthAuthorizationUrl = $oauthAuthorizationUrl; |
||
156 | $this->oauthScopes = $oauthScopes; |
||
157 | $this->subresourceOperationFactory = $subresourceOperationFactory; |
||
158 | $this->paginationEnabled = $paginationEnabled; |
||
159 | $this->paginationPageParameterName = $paginationPageParameterName; |
||
160 | $this->apiKeys = $apiKeys; |
||
161 | $this->clientItemsPerPage = $clientItemsPerPage; |
||
162 | $this->itemsPerPageParameterName = $itemsPerPageParameterName; |
||
163 | $this->paginationClientEnabled = $paginationClientEnabled; |
||
164 | $this->paginationClientEnabledParameterName = $paginationClientEnabledParameterName; |
||
165 | |||
166 | $this->defaultContext[self::SPEC_VERSION] = $swaggerVersions[0] ?? 2; |
||
167 | |||
168 | $this->defaultContext = array_merge($this->defaultContext, $defaultContext); |
||
169 | } |
||
170 | |||
171 | /** |
||
172 | * {@inheritdoc} |
||
173 | */ |
||
174 | public function normalize($object, $format = null, array $context = []) |
||
175 | { |
||
176 | $v3 = 3 === ($context['spec_version'] ?? $this->defaultContext['spec_version']) && !($context['api_gateway'] ?? $this->defaultContext['api_gateway']); |
||
177 | |||
178 | $definitions = new \ArrayObject(); |
||
179 | $paths = new \ArrayObject(); |
||
180 | $links = new \ArrayObject(); |
||
181 | |||
182 | foreach ($object->getResourceNameCollection() as $resourceClass) { |
||
183 | $resourceMetadata = $this->resourceMetadataFactory->create($resourceClass); |
||
184 | $resourceShortName = $resourceMetadata->getShortName(); |
||
185 | |||
186 | // Items needs to be parsed first to be able to reference the lines from the collection operation |
||
187 | $this->addPaths($v3, $paths, $definitions, $resourceClass, $resourceShortName, $resourceMetadata, OperationType::ITEM, $links); |
||
188 | $this->addPaths($v3, $paths, $definitions, $resourceClass, $resourceShortName, $resourceMetadata, OperationType::COLLECTION, $links); |
||
189 | |||
190 | if (null === $this->subresourceOperationFactory) { |
||
191 | continue; |
||
192 | } |
||
193 | |||
194 | foreach ($this->subresourceOperationFactory->create($resourceClass) as $operationId => $subresourceOperation) { |
||
195 | $paths[$this->getPath($subresourceOperation['shortNames'][0], $subresourceOperation['route_name'], $subresourceOperation, OperationType::SUBRESOURCE)] = $this->addSubresourceOperation($v3, $subresourceOperation, $definitions, $operationId, $resourceMetadata); |
||
196 | } |
||
197 | } |
||
198 | |||
199 | $definitions->ksort(); |
||
200 | $paths->ksort(); |
||
201 | |||
202 | return $this->computeDoc($v3, $object, $definitions, $paths, $context); |
||
203 | } |
||
204 | |||
205 | /** |
||
206 | * Updates the list of entries in the paths collection. |
||
207 | */ |
||
208 | private function addPaths(bool $v3, \ArrayObject $paths, \ArrayObject $definitions, string $resourceClass, string $resourceShortName, ResourceMetadata $resourceMetadata, string $operationType, \ArrayObject $links) |
||
209 | { |
||
210 | if (null === $operations = OperationType::COLLECTION === $operationType ? $resourceMetadata->getCollectionOperations() : $resourceMetadata->getItemOperations()) { |
||
211 | return; |
||
212 | } |
||
213 | |||
214 | foreach ($operations as $operationName => $operation) { |
||
215 | $path = $this->getPath($resourceShortName, $operationName, $operation, $operationType); |
||
216 | if ($this->operationMethodResolver) { |
||
217 | $method = OperationType::ITEM === $operationType ? $this->operationMethodResolver->getItemOperationMethod($resourceClass, $operationName) : $this->operationMethodResolver->getCollectionOperationMethod($resourceClass, $operationName); |
||
218 | } else { |
||
219 | $method = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'method', 'GET'); |
||
220 | } |
||
221 | |||
222 | $paths[$path][strtolower($method)] = $this->getPathOperation($v3, $operationName, $operation, $method, $operationType, $resourceClass, $resourceMetadata, $definitions, $links); |
||
223 | } |
||
224 | } |
||
225 | |||
226 | /** |
||
227 | * Gets the path for an operation. |
||
228 | * |
||
229 | * If the path ends with the optional _format parameter, it is removed |
||
230 | * as optional path parameters are not yet supported. |
||
231 | * |
||
232 | * @see https://github.com/OAI/OpenAPI-Specification/issues/93 |
||
233 | */ |
||
234 | private function getPath(string $resourceShortName, string $operationName, array $operation, string $operationType): string |
||
235 | { |
||
236 | $path = $this->operationPathResolver->resolveOperationPath($resourceShortName, $operation, $operationType, $operationName); |
||
237 | if ('.{_format}' === substr($path, -10)) { |
||
238 | $path = substr($path, 0, -10); |
||
239 | } |
||
240 | |||
241 | return $path; |
||
242 | } |
||
243 | |||
244 | /** |
||
245 | * Gets a path Operation Object. |
||
246 | * |
||
247 | * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#operation-object |
||
248 | */ |
||
249 | private function getPathOperation(bool $v3, string $operationName, array $operation, string $method, string $operationType, string $resourceClass, ResourceMetadata $resourceMetadata, \ArrayObject $definitions, \ArrayObject $links): \ArrayObject |
||
250 | { |
||
251 | $pathOperation = new \ArrayObject($operation[$v3 ? 'openapi_context' : 'swagger_context'] ?? []); |
||
252 | $resourceShortName = $resourceMetadata->getShortName(); |
||
253 | $pathOperation['tags'] ?? $pathOperation['tags'] = [$resourceShortName]; |
||
254 | $pathOperation['operationId'] ?? $pathOperation['operationId'] = lcfirst($operationName).ucfirst($resourceShortName).ucfirst($operationType); |
||
255 | if ($v3 && 'GET' === $method && OperationType::ITEM === $operationType && $link = $this->getLinkObject($resourceClass, $pathOperation['operationId'], $this->getPath($resourceShortName, $operationName, $operation, $operationType))) { |
||
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
256 | $links[$pathOperation['operationId']] = $link; |
||
257 | } |
||
258 | if ($resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'deprecation_reason', null, true)) { |
||
259 | $pathOperation['deprecated'] = true; |
||
260 | } |
||
261 | |||
262 | if (null === $this->formatsProvider) { |
||
263 | $requestFormats = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'input_formats', [], true); |
||
264 | $responseFormats = $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'output_formats', [], true); |
||
265 | } else { |
||
266 | $requestFormats = $responseFormats = $this->formatsProvider->getFormatsFromOperation($resourceClass, $operationName, $operationType); |
||
267 | } |
||
268 | |||
269 | $requestMimeTypes = $this->flattenMimeTypes($requestFormats); |
||
270 | $responseMimeTypes = $this->flattenMimeTypes($responseFormats); |
||
271 | switch ($method) { |
||
272 | case 'GET': |
||
273 | return $this->updateGetOperation($v3, $pathOperation, $responseMimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions); |
||
274 | case 'POST': |
||
275 | return $this->updatePostOperation($v3, $pathOperation, $requestMimeTypes, $responseMimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions, $links); |
||
276 | case 'PATCH': |
||
277 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Updates the %s resource.', $resourceShortName); |
||
278 | // no break |
||
279 | case 'PUT': |
||
280 | return $this->updatePutOperation($v3, $pathOperation, $requestMimeTypes, $responseMimeTypes, $operationType, $resourceMetadata, $resourceClass, $resourceShortName, $operationName, $definitions); |
||
281 | case 'DELETE': |
||
282 | return $this->updateDeleteOperation($v3, $pathOperation, $resourceShortName, $operationType, $operationName, $resourceMetadata); |
||
283 | } |
||
284 | |||
285 | return $pathOperation; |
||
286 | } |
||
287 | |||
288 | /** |
||
289 | * @return array the update message as first value, and if the schema is defined as second |
||
290 | */ |
||
291 | private function addSchemas(bool $v3, array $message, \ArrayObject $definitions, string $resourceClass, string $operationType, string $operationName, array $mimeTypes, bool $output = true, bool $forceCollection = false) |
||
292 | { |
||
293 | if (!$v3) { |
||
294 | $jsonSchema = $this->getJsonSchema($v3, $definitions, $resourceClass, $output, $operationType, $operationName, 'json', null, $forceCollection); |
||
295 | if (!$jsonSchema->isDefined()) { |
||
296 | return [$message, false]; |
||
297 | } |
||
298 | |||
299 | $message['schema'] = $jsonSchema->getArrayCopy(false); |
||
300 | |||
301 | return [$message, true]; |
||
302 | } |
||
303 | |||
304 | foreach ($mimeTypes as $mimeType => $format) { |
||
305 | $jsonSchema = $this->getJsonSchema($v3, $definitions, $resourceClass, $output, $operationType, $operationName, $format, null, $forceCollection); |
||
306 | if (!$jsonSchema->isDefined()) { |
||
307 | return [$message, false]; |
||
308 | } |
||
309 | |||
310 | $message['content'][$mimeType] = ['schema' => $jsonSchema->getArrayCopy(false)]; |
||
311 | } |
||
312 | |||
313 | return [$message, true]; |
||
314 | } |
||
315 | |||
316 | private function updateGetOperation(bool $v3, \ArrayObject $pathOperation, array $mimeTypes, string $operationType, ResourceMetadata $resourceMetadata, string $resourceClass, string $resourceShortName, string $operationName, \ArrayObject $definitions): \ArrayObject |
||
317 | { |
||
318 | $successStatus = (string) $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'status', '200'); |
||
319 | |||
320 | if (!$v3) { |
||
321 | $pathOperation['produces'] ?? $pathOperation['produces'] = array_keys($mimeTypes); |
||
322 | } |
||
323 | |||
324 | if (OperationType::COLLECTION === $operationType) { |
||
325 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Retrieves the collection of %s resources.', $resourceShortName); |
||
326 | |||
327 | $successResponse = ['description' => sprintf('%s collection response', $resourceShortName)]; |
||
328 | [$successResponse] = $this->addSchemas($v3, $successResponse, $definitions, $resourceClass, $operationType, $operationName, $mimeTypes); |
||
329 | |||
330 | $pathOperation['responses'] ?? $pathOperation['responses'] = [$successStatus => $successResponse]; |
||
331 | $pathOperation['parameters'] ?? $pathOperation['parameters'] = $this->getFiltersParameters($v3, $resourceClass, $operationName, $resourceMetadata); |
||
332 | |||
333 | $this->addPaginationParameters($v3, $resourceMetadata, $operationName, $pathOperation); |
||
334 | |||
335 | return $pathOperation; |
||
336 | } |
||
337 | |||
338 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Retrieves a %s resource.', $resourceShortName); |
||
339 | |||
340 | $pathOperation = $this->addItemOperationParameters($v3, $pathOperation); |
||
341 | |||
342 | $successResponse = ['description' => sprintf('%s resource response', $resourceShortName)]; |
||
343 | [$successResponse] = $this->addSchemas($v3, $successResponse, $definitions, $resourceClass, $operationType, $operationName, $mimeTypes); |
||
344 | |||
345 | $pathOperation['responses'] ?? $pathOperation['responses'] = [ |
||
346 | $successStatus => $successResponse, |
||
347 | '404' => ['description' => 'Resource not found'], |
||
348 | ]; |
||
349 | |||
350 | return $pathOperation; |
||
351 | } |
||
352 | |||
353 | private function addPaginationParameters(bool $v3, ResourceMetadata $resourceMetadata, string $operationName, \ArrayObject $pathOperation) |
||
354 | { |
||
355 | if ($this->paginationEnabled && $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_enabled', true, true)) { |
||
356 | $paginationParameter = [ |
||
357 | 'name' => $this->paginationPageParameterName, |
||
358 | 'in' => 'query', |
||
359 | 'required' => false, |
||
360 | 'description' => 'The collection page number', |
||
361 | ]; |
||
362 | $v3 ? $paginationParameter['schema'] = [ |
||
363 | 'type' => 'integer', |
||
364 | 'default' => 1, |
||
365 | ] : $paginationParameter['type'] = 'integer'; |
||
366 | $pathOperation['parameters'][] = $paginationParameter; |
||
367 | |||
368 | if ($resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_items_per_page', $this->clientItemsPerPage, true)) { |
||
369 | $itemPerPageParameter = [ |
||
370 | 'name' => $this->itemsPerPageParameterName, |
||
371 | 'in' => 'query', |
||
372 | 'required' => false, |
||
373 | 'description' => 'The number of items per page', |
||
374 | ]; |
||
375 | if ($v3) { |
||
376 | $itemPerPageParameter['schema'] = [ |
||
377 | 'type' => 'integer', |
||
378 | 'default' => $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_items_per_page', 30, true), |
||
379 | 'minimum' => 0, |
||
380 | ]; |
||
381 | |||
382 | if ($maximumItemPerPage = $resourceMetadata->getCollectionOperationAttribute($operationName, 'maximum_items_per_page', false, true)) { |
||
383 | $itemPerPageParameter['schema']['maximum'] = $maximumItemPerPage; |
||
384 | } |
||
385 | } else { |
||
386 | $itemPerPageParameter['type'] = 'integer'; |
||
387 | } |
||
388 | |||
389 | $pathOperation['parameters'][] = $itemPerPageParameter; |
||
390 | } |
||
391 | } |
||
392 | |||
393 | if ($this->paginationEnabled && $resourceMetadata->getCollectionOperationAttribute($operationName, 'pagination_client_enabled', $this->paginationClientEnabled, true)) { |
||
394 | $paginationEnabledParameter = [ |
||
395 | 'name' => $this->paginationClientEnabledParameterName, |
||
396 | 'in' => 'query', |
||
397 | 'required' => false, |
||
398 | 'description' => 'Enable or disable pagination', |
||
399 | ]; |
||
400 | $v3 ? $paginationEnabledParameter['schema'] = ['type' => 'boolean'] : $paginationEnabledParameter['type'] = 'boolean'; |
||
401 | $pathOperation['parameters'][] = $paginationEnabledParameter; |
||
402 | } |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * @throws ResourceClassNotFoundException |
||
407 | */ |
||
408 | private function addSubresourceOperation(bool $v3, array $subresourceOperation, \ArrayObject $definitions, string $operationId, ResourceMetadata $resourceMetadata): \ArrayObject |
||
409 | { |
||
410 | $operationName = 'get'; // TODO: we might want to extract that at some point to also support other subresource operations |
||
411 | $collection = $subresourceOperation['collection'] ?? false; |
||
412 | |||
413 | $subResourceMetadata = $this->resourceMetadataFactory->create($subresourceOperation['resource_class']); |
||
414 | |||
415 | $pathOperation = new \ArrayObject([]); |
||
416 | $pathOperation['tags'] = $subresourceOperation['shortNames']; |
||
417 | $pathOperation['operationId'] = $operationId; |
||
418 | $pathOperation['summary'] = sprintf('Retrieves %s%s resource%s.', $subresourceOperation['collection'] ? 'the collection of ' : 'a ', $subresourceOperation['shortNames'][0], $subresourceOperation['collection'] ? 's' : ''); |
||
419 | |||
420 | if (null === $this->formatsProvider) { |
||
421 | // TODO: Subresource operation metadata aren't available by default, for now we have to fallback on default formats. |
||
422 | // TODO: A better approach would be to always populate the subresource operation array. |
||
423 | $responseFormats = $this |
||
424 | ->resourceMetadataFactory |
||
425 | ->create($subresourceOperation['resource_class']) |
||
426 | ->getTypedOperationAttribute(OperationType::SUBRESOURCE, $operationName, 'output_formats', $this->formats, true); |
||
427 | } else { |
||
428 | $responseFormats = $this->formatsProvider->getFormatsFromOperation($subresourceOperation['resource_class'], $operationName, OperationType::SUBRESOURCE); |
||
429 | } |
||
430 | |||
431 | $mimeTypes = $this->flattenMimeTypes($responseFormats); |
||
432 | |||
433 | if (!$v3) { |
||
434 | $pathOperation['produces'] = array_keys($mimeTypes); |
||
435 | } |
||
436 | |||
437 | $successResponse = [ |
||
438 | 'description' => sprintf('%s %s response', $subresourceOperation['shortNames'][0], $collection ? 'collection' : 'resource'), |
||
439 | ]; |
||
440 | [$successResponse] = $this->addSchemas($v3, $successResponse, $definitions, $subresourceOperation['resource_class'], OperationType::SUBRESOURCE, $operationName, $mimeTypes, true, $collection); |
||
441 | |||
442 | $pathOperation['responses'] = ['200' => $successResponse, '404' => ['description' => 'Resource not found']]; |
||
443 | |||
444 | // Avoid duplicates parameters when there is a filter on a subresource identifier |
||
445 | $parametersMemory = []; |
||
446 | $pathOperation['parameters'] = []; |
||
447 | foreach ($subresourceOperation['identifiers'] as list($identifier, , $hasIdentifier)) { |
||
448 | if (true === $hasIdentifier) { |
||
449 | $parameter = ['name' => $identifier, 'in' => 'path', 'required' => true]; |
||
450 | $v3 ? $parameter['schema'] = ['type' => 'string'] : $parameter['type'] = 'string'; |
||
451 | $pathOperation['parameters'][] = $parameter; |
||
452 | $parametersMemory[] = $identifier; |
||
453 | } |
||
454 | } |
||
455 | if ($parameters = $this->getFiltersParameters($v3, $subresourceOperation['resource_class'], $operationName, $subResourceMetadata)) { |
||
456 | foreach ($parameters as $parameter) { |
||
457 | if (!\in_array($parameter['name'], $parametersMemory, true)) { |
||
458 | $pathOperation['parameters'][] = $parameter; |
||
459 | } |
||
460 | } |
||
461 | } |
||
462 | |||
463 | if ($subresourceOperation['collection']) { |
||
464 | $this->addPaginationParameters($v3, $resourceMetadata, $operationName, $pathOperation); |
||
465 | } |
||
466 | |||
467 | return new \ArrayObject(['get' => $pathOperation]); |
||
468 | } |
||
469 | |||
470 | private function updatePostOperation(bool $v3, \ArrayObject $pathOperation, array $requestMimeTypes, array $responseMimeTypes, string $operationType, ResourceMetadata $resourceMetadata, string $resourceClass, string $resourceShortName, string $operationName, \ArrayObject $definitions, \ArrayObject $links): \ArrayObject |
||
471 | { |
||
472 | if (!$v3) { |
||
473 | $pathOperation['consumes'] ?? $pathOperation['consumes'] = array_keys($requestMimeTypes); |
||
474 | $pathOperation['produces'] ?? $pathOperation['produces'] = array_keys($responseMimeTypes); |
||
475 | } |
||
476 | |||
477 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Creates a %s resource.', $resourceShortName); |
||
478 | |||
479 | if (OperationType::ITEM === $operationType) { |
||
480 | $pathOperation = $this->addItemOperationParameters($v3, $pathOperation); |
||
481 | } |
||
482 | |||
483 | $successResponse = ['description' => sprintf('%s resource created', $resourceShortName)]; |
||
484 | [$successResponse, $defined] = $this->addSchemas($v3, $successResponse, $definitions, $resourceClass, $operationType, $operationName, $responseMimeTypes); |
||
485 | |||
486 | if ($defined && $v3 && ($links[$key = 'get'.ucfirst($resourceShortName).ucfirst(OperationType::ITEM)] ?? null)) { |
||
487 | $successResponse['links'] = [ucfirst($key) => $links[$key]]; |
||
488 | } |
||
489 | |||
490 | $pathOperation['responses'] ?? $pathOperation['responses'] = [ |
||
491 | (string) $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'status', '201') => $successResponse, |
||
492 | '400' => ['description' => 'Invalid input'], |
||
493 | '404' => ['description' => 'Resource not found'], |
||
494 | ]; |
||
495 | |||
496 | return $this->addRequestBody($v3, $pathOperation, $definitions, $resourceClass, $resourceShortName, $operationType, $operationName, $requestMimeTypes); |
||
497 | } |
||
498 | |||
499 | private function updatePutOperation(bool $v3, \ArrayObject $pathOperation, array $requestMimeTypes, array $responseMimeTypes, string $operationType, ResourceMetadata $resourceMetadata, string $resourceClass, string $resourceShortName, string $operationName, \ArrayObject $definitions): \ArrayObject |
||
500 | { |
||
501 | if (!$v3) { |
||
502 | $pathOperation['consumes'] ?? $pathOperation['consumes'] = array_keys($requestMimeTypes); |
||
503 | $pathOperation['produces'] ?? $pathOperation['produces'] = array_keys($responseMimeTypes); |
||
504 | } |
||
505 | |||
506 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Replaces the %s resource.', $resourceShortName); |
||
507 | |||
508 | $pathOperation = $this->addItemOperationParameters($v3, $pathOperation); |
||
509 | |||
510 | $successResponse = ['description' => sprintf('%s resource updated', $resourceShortName)]; |
||
511 | [$successResponse] = $this->addSchemas($v3, $successResponse, $definitions, $resourceClass, $operationType, $operationName, $responseMimeTypes); |
||
512 | |||
513 | $pathOperation['responses'] ?? $pathOperation['responses'] = [ |
||
514 | (string) $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'status', '200') => $successResponse, |
||
515 | '400' => ['description' => 'Invalid input'], |
||
516 | '404' => ['description' => 'Resource not found'], |
||
517 | ]; |
||
518 | |||
519 | return $this->addRequestBody($v3, $pathOperation, $definitions, $resourceClass, $resourceShortName, $operationType, $operationName, $requestMimeTypes, true); |
||
520 | } |
||
521 | |||
522 | private function addRequestBody(bool $v3, \ArrayObject $pathOperation, \ArrayObject $definitions, string $resourceClass, string $resourceShortName, string $operationType, string $operationName, array $requestMimeTypes, bool $put = false) |
||
523 | { |
||
524 | if (isset($pathOperation['requestBody'])) { |
||
525 | return $pathOperation; |
||
526 | } |
||
527 | |||
528 | [$message, $defined] = $this->addSchemas($v3, [], $definitions, $resourceClass, $operationType, $operationName, $requestMimeTypes, false); |
||
529 | if (!$defined) { |
||
530 | return $pathOperation; |
||
531 | } |
||
532 | |||
533 | $description = sprintf('The %s %s resource', $put ? 'updated' : 'new', $resourceShortName); |
||
534 | if ($v3) { |
||
535 | $pathOperation['requestBody'] = $message + ['description' => $description]; |
||
536 | |||
537 | return $pathOperation; |
||
538 | } |
||
539 | |||
540 | $pathOperation['parameters'][] = [ |
||
541 | 'name' => lcfirst($resourceShortName), |
||
542 | 'in' => 'body', |
||
543 | 'description' => $description, |
||
544 | ] + $message; |
||
545 | |||
546 | return $pathOperation; |
||
547 | } |
||
548 | |||
549 | private function updateDeleteOperation(bool $v3, \ArrayObject $pathOperation, string $resourceShortName, string $operationType, string $operationName, ResourceMetadata $resourceMetadata): \ArrayObject |
||
550 | { |
||
551 | $pathOperation['summary'] ?? $pathOperation['summary'] = sprintf('Removes the %s resource.', $resourceShortName); |
||
552 | $pathOperation['responses'] ?? $pathOperation['responses'] = [ |
||
553 | (string) $resourceMetadata->getTypedOperationAttribute($operationType, $operationName, 'status', '204') => ['description' => sprintf('%s resource deleted', $resourceShortName)], |
||
554 | '404' => ['description' => 'Resource not found'], |
||
555 | ]; |
||
556 | |||
557 | return $this->addItemOperationParameters($v3, $pathOperation); |
||
558 | } |
||
559 | |||
560 | private function addItemOperationParameters(bool $v3, \ArrayObject $pathOperation): \ArrayObject |
||
561 | { |
||
562 | $parameter = [ |
||
563 | 'name' => 'id', |
||
564 | 'in' => 'path', |
||
565 | 'required' => true, |
||
566 | ]; |
||
567 | $v3 ? $parameter['schema'] = ['type' => 'string'] : $parameter['type'] = 'string'; |
||
568 | $pathOperation['parameters'] ?? $pathOperation['parameters'] = [$parameter]; |
||
569 | |||
570 | return $pathOperation; |
||
571 | } |
||
572 | |||
573 | private function getJsonSchema(bool $v3, \ArrayObject $definitions, string $resourceClass, bool $output, ?string $operationType, ?string $operationName, string $format = 'json', ?array $serializerContext = null, bool $forceCollection = false): Schema |
||
574 | { |
||
575 | $schema = new Schema($v3 ? Schema::VERSION_OPENAPI : Schema::VERSION_SWAGGER); |
||
576 | $schema->setDefinitions($definitions); |
||
577 | |||
578 | $this->jsonSchemaFactory->buildSchema($resourceClass, $format, $output, $operationType, $operationName, $schema, $serializerContext, $forceCollection); |
||
579 | |||
580 | return $schema; |
||
581 | } |
||
582 | |||
583 | private function computeDoc(bool $v3, Documentation $documentation, \ArrayObject $definitions, \ArrayObject $paths, array $context): array |
||
584 | { |
||
585 | $baseUrl = $context[self::BASE_URL] ?? $this->defaultContext[self::BASE_URL]; |
||
586 | |||
587 | if ($v3) { |
||
588 | $docs = ['openapi' => self::OPENAPI_VERSION]; |
||
589 | if ('/' !== $baseUrl && '' !== $baseUrl) { |
||
590 | $docs['servers'] = [['url' => $baseUrl]]; |
||
591 | } |
||
592 | } else { |
||
593 | $docs = [ |
||
594 | 'swagger' => self::SWAGGER_VERSION, |
||
595 | 'basePath' => $baseUrl, |
||
596 | ]; |
||
597 | } |
||
598 | |||
599 | $docs += [ |
||
600 | 'info' => [ |
||
601 | 'title' => $documentation->getTitle(), |
||
602 | 'version' => $documentation->getVersion(), |
||
603 | ], |
||
604 | 'paths' => $paths, |
||
605 | ]; |
||
606 | |||
607 | if ('' !== $description = $documentation->getDescription()) { |
||
608 | $docs['info']['description'] = $description; |
||
609 | } |
||
610 | |||
611 | $securityDefinitions = []; |
||
612 | $security = []; |
||
613 | |||
614 | if ($this->oauthEnabled) { |
||
615 | $securityDefinitions['oauth'] = [ |
||
616 | 'type' => $this->oauthType, |
||
617 | 'description' => 'OAuth client_credentials Grant', |
||
618 | 'flow' => $this->oauthFlow, |
||
619 | 'tokenUrl' => $this->oauthTokenUrl, |
||
620 | 'authorizationUrl' => $this->oauthAuthorizationUrl, |
||
621 | 'scopes' => $this->oauthScopes, |
||
622 | ]; |
||
623 | |||
624 | $security[] = ['oauth' => []]; |
||
625 | } |
||
626 | |||
627 | foreach ($this->apiKeys as $key => $apiKey) { |
||
628 | $name = $apiKey['name']; |
||
629 | $type = $apiKey['type']; |
||
630 | |||
631 | $securityDefinitions[$key] = [ |
||
632 | 'type' => 'apiKey', |
||
633 | 'in' => $type, |
||
634 | 'description' => sprintf('Value for the %s %s', $name, 'query' === $type ? sprintf('%s parameter', $type) : $type), |
||
635 | 'name' => $name, |
||
636 | ]; |
||
637 | |||
638 | $security[] = [$key => []]; |
||
639 | } |
||
640 | |||
641 | if ($v3) { |
||
642 | if ($securityDefinitions && $security) { |
||
643 | $docs['security'] = $security; |
||
644 | } |
||
645 | } elseif ($securityDefinitions && $security) { |
||
646 | $docs['securityDefinitions'] = $securityDefinitions; |
||
647 | $docs['security'] = $security; |
||
648 | } |
||
649 | |||
650 | if ($v3) { |
||
651 | if (\count($definitions) + \count($securityDefinitions)) { |
||
652 | $docs['components'] = []; |
||
653 | if (\count($definitions)) { |
||
654 | $docs['components']['schemas'] = $definitions; |
||
655 | } |
||
656 | if (\count($securityDefinitions)) { |
||
657 | $docs['components']['securitySchemes'] = $securityDefinitions; |
||
658 | } |
||
659 | } |
||
660 | } elseif (\count($definitions) > 0) { |
||
661 | $docs['definitions'] = $definitions; |
||
662 | } |
||
663 | |||
664 | return $docs; |
||
665 | } |
||
666 | |||
667 | /** |
||
668 | * Gets parameters corresponding to enabled filters. |
||
669 | */ |
||
670 | private function getFiltersParameters(bool $v3, string $resourceClass, string $operationName, ResourceMetadata $resourceMetadata): array |
||
671 | { |
||
672 | if (null === $this->filterLocator) { |
||
673 | return []; |
||
674 | } |
||
675 | |||
676 | $parameters = []; |
||
677 | $resourceFilters = $resourceMetadata->getCollectionOperationAttribute($operationName, 'filters', [], true); |
||
678 | foreach ($resourceFilters as $filterId) { |
||
679 | if (!$filter = $this->getFilter($filterId)) { |
||
680 | continue; |
||
681 | } |
||
682 | |||
683 | foreach ($filter->getDescription($resourceClass) as $name => $data) { |
||
684 | $parameter = [ |
||
685 | 'name' => $name, |
||
686 | 'in' => 'query', |
||
687 | 'required' => $data['required'], |
||
688 | ]; |
||
689 | |||
690 | $type = \in_array($data['type'], Type::$builtinTypes, true) ? $this->jsonSchemaTypeFactory->getType(new Type($data['type'], false, null, $data['is_collection'] ?? false)) : ['type' => 'string']; |
||
691 | $v3 ? $parameter['schema'] = $type : $parameter += $type; |
||
692 | |||
693 | if ($v3 && isset($data['schema'])) { |
||
694 | $parameter['schema'] = $data['schema']; |
||
695 | } |
||
696 | |||
697 | if ('array' === ($type['type'] ?? '')) { |
||
698 | $deepObject = \in_array($data['type'], [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_OBJECT], true); |
||
699 | |||
700 | if ($v3) { |
||
701 | $parameter['style'] = $deepObject ? 'deepObject' : 'form'; |
||
702 | $parameter['explode'] = true; |
||
703 | } else { |
||
704 | $parameter['collectionFormat'] = $deepObject ? 'csv' : 'multi'; |
||
705 | } |
||
706 | } |
||
707 | |||
708 | $key = $v3 ? 'openapi' : 'swagger'; |
||
709 | if (isset($data[$key])) { |
||
710 | $parameter = $data[$key] + $parameter; |
||
711 | } |
||
712 | |||
713 | $parameters[] = $parameter; |
||
714 | } |
||
715 | } |
||
716 | |||
717 | return $parameters; |
||
718 | } |
||
719 | |||
720 | /** |
||
721 | * {@inheritdoc} |
||
722 | */ |
||
723 | public function supportsNormalization($data, $format = null): bool |
||
724 | { |
||
725 | return self::FORMAT === $format && $data instanceof Documentation; |
||
726 | } |
||
727 | |||
728 | /** |
||
729 | * {@inheritdoc} |
||
730 | */ |
||
731 | public function hasCacheableSupportsMethod(): bool |
||
732 | { |
||
733 | return true; |
||
734 | } |
||
735 | |||
736 | private function flattenMimeTypes(array $responseFormats): array |
||
737 | { |
||
738 | $responseMimeTypes = []; |
||
739 | foreach ($responseFormats as $responseFormat => $mimeTypes) { |
||
740 | foreach ($mimeTypes as $mimeType) { |
||
741 | $responseMimeTypes[$mimeType] = $responseFormat; |
||
742 | } |
||
743 | } |
||
744 | |||
745 | return $responseMimeTypes; |
||
746 | } |
||
747 | |||
748 | /** |
||
749 | * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#linkObject. |
||
750 | */ |
||
751 | private function getLinkObject(string $resourceClass, string $operationId, string $path): array |
||
752 | { |
||
753 | $linkObject = $identifiers = []; |
||
754 | foreach ($this->propertyNameCollectionFactory->create($resourceClass) as $propertyName) { |
||
755 | $propertyMetadata = $this->propertyMetadataFactory->create($resourceClass, $propertyName); |
||
756 | if (!$propertyMetadata->isIdentifier()) { |
||
0 ignored issues
–
show
The expression
$propertyMetadata->isIdentifier() of type boolean|null is loosely compared to false ; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.
If an expression can have both $a = canBeFalseAndNull();
// Instead of
if ( ! $a) { }
// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
|
|||
757 | continue; |
||
758 | } |
||
759 | |||
760 | $linkObject['parameters'][$propertyName] = sprintf('$response.body#/%s', $propertyName); |
||
761 | $identifiers[] = $propertyName; |
||
762 | } |
||
763 | |||
764 | if (!$linkObject) { |
||
765 | return []; |
||
766 | } |
||
767 | $linkObject['operationId'] = $operationId; |
||
768 | $linkObject['description'] = 1 === \count($identifiers) ? sprintf('The `%1$s` value returned in the response can be used as the `%1$s` parameter in `GET %2$s`.', $identifiers[0], $path) : sprintf('The values returned in the response can be used in `GET %s`.', $path); |
||
769 | |||
770 | return $linkObject; |
||
771 | } |
||
772 | } |
||
773 |