• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15255731762

26 May 2025 01:55PM UTC coverage: 0.0% (-26.5%) from 26.526%
15255731762

Pull #7176

github

web-flow
Merge 66f6cf4d2 into 79edced67
Pull Request #7176: Merge 4.1

0 of 387 new or added lines in 28 files covered. (0.0%)

11394 existing lines in 372 files now uncovered.

0 of 51334 relevant lines covered (0.0%)

0.0 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/OpenApi/Factory/OpenApiFactory.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
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\OpenApi\Factory;
15

16
use ApiPlatform\JsonSchema\Schema;
17
use ApiPlatform\JsonSchema\SchemaFactoryInterface;
18
use ApiPlatform\Metadata\ApiResource;
19
use ApiPlatform\Metadata\CollectionOperationInterface;
20
use ApiPlatform\Metadata\Error;
21
use ApiPlatform\Metadata\ErrorResource;
22
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
23
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
24
use ApiPlatform\Metadata\Exception\ResourceClassNotFoundException;
25
use ApiPlatform\Metadata\Exception\RuntimeException;
26
use ApiPlatform\Metadata\HeaderParameterInterface;
27
use ApiPlatform\Metadata\HttpOperation;
28
use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
29
use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
30
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
31
use ApiPlatform\Metadata\Resource\Factory\ResourceNameCollectionFactoryInterface;
32
use ApiPlatform\Metadata\Resource\ResourceMetadataCollection;
33
use ApiPlatform\OpenApi\Attributes\Webhook;
34
use ApiPlatform\OpenApi\Model\Components;
35
use ApiPlatform\OpenApi\Model\Contact;
36
use ApiPlatform\OpenApi\Model\Info;
37
use ApiPlatform\OpenApi\Model\License;
38
use ApiPlatform\OpenApi\Model\Link;
39
use ApiPlatform\OpenApi\Model\MediaType;
40
use ApiPlatform\OpenApi\Model\OAuthFlow;
41
use ApiPlatform\OpenApi\Model\OAuthFlows;
42
use ApiPlatform\OpenApi\Model\Operation;
43
use ApiPlatform\OpenApi\Model\Parameter;
44
use ApiPlatform\OpenApi\Model\PathItem;
45
use ApiPlatform\OpenApi\Model\Paths;
46
use ApiPlatform\OpenApi\Model\RequestBody;
47
use ApiPlatform\OpenApi\Model\Response;
48
use ApiPlatform\OpenApi\Model\SecurityScheme;
49
use ApiPlatform\OpenApi\Model\Server;
50
use ApiPlatform\OpenApi\Model\Tag;
51
use ApiPlatform\OpenApi\OpenApi;
52
use ApiPlatform\OpenApi\Options;
53
use ApiPlatform\OpenApi\Serializer\NormalizeOperationNameTrait;
54
use ApiPlatform\State\ApiResource\Error as ApiResourceError;
55
use ApiPlatform\State\Pagination\PaginationOptions;
56
use ApiPlatform\State\Util\StateOptionsTrait;
57
use ApiPlatform\Validator\Exception\ValidationException;
58
use Psr\Container\ContainerInterface;
59
use Symfony\Component\PropertyInfo\PropertyInfoExtractor;
60
use Symfony\Component\PropertyInfo\Type as LegacyType;
61
use Symfony\Component\Routing\RouteCollection;
62
use Symfony\Component\Routing\RouterInterface;
63
use Symfony\Component\TypeInfo\Type;
64
use Symfony\Component\TypeInfo\TypeIdentifier;
65

66
/**
67
 * Generates an Open API v3 specification.
68
 */
69
final class OpenApiFactory implements OpenApiFactoryInterface
70
{
71
    use NormalizeOperationNameTrait;
72
    use StateOptionsTrait;
73
    use TypeFactoryTrait;
74

75
    public const BASE_URL = 'base_url';
76
    public const API_PLATFORM_TAG = 'x-apiplatform-tag';
77
    public const OVERRIDE_OPENAPI_RESPONSES = 'open_api_override_responses';
78
    private readonly Options $openApiOptions;
79
    private readonly PaginationOptions $paginationOptions;
80
    private ?RouteCollection $routeCollection = null;
81
    private ?ContainerInterface $filterLocator = null;
82
    /**
83
     * @var array<string|class-string, ErrorResource>
84
     */
85
    private array $localErrorResourceCache = [];
86

87
    /**
88
     * @param array<string, string[]> $formats
89
     */
90
    public function __construct(
91
        private readonly ResourceNameCollectionFactoryInterface $resourceNameCollectionFactory,
92
        private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory,
93
        private readonly PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory,
94
        private readonly PropertyMetadataFactoryInterface $propertyMetadataFactory,
95
        private readonly SchemaFactoryInterface $jsonSchemaFactory,
96
        ?ContainerInterface $filterLocator = null,
97
        private readonly array $formats = [],
98
        ?Options $openApiOptions = null,
99
        ?PaginationOptions $paginationOptions = null,
100
        private readonly ?RouterInterface $router = null,
101
        private readonly array $errorFormats = [],
102
    ) {
UNCOV
103
        $this->filterLocator = $filterLocator;
×
UNCOV
104
        $this->openApiOptions = $openApiOptions ?: new Options('API Platform');
×
UNCOV
105
        $this->paginationOptions = $paginationOptions ?: new PaginationOptions();
×
106
    }
107

108
    /**
109
     * {@inheritdoc}
110
     *
111
     * You can filter openapi operations with the `x-apiplatform-tag` on an OpenApi Operation using the `filter_tags`.
112
     *
113
     * @param array{base_url?: string, filter_tags?: string[]}&array<string, mixed> $context
114
     */
115
    public function __invoke(array $context = []): OpenApi
116
    {
UNCOV
117
        $baseUrl = $context[self::BASE_URL] ?? '/';
×
UNCOV
118
        $contact = null === $this->openApiOptions->getContactUrl() || null === $this->openApiOptions->getContactEmail() ? null : new Contact($this->openApiOptions->getContactName(), $this->openApiOptions->getContactUrl(), $this->openApiOptions->getContactEmail());
×
UNCOV
119
        $license = null === $this->openApiOptions->getLicenseName() ? null : new License($this->openApiOptions->getLicenseName(), $this->openApiOptions->getLicenseUrl(), $this->openApiOptions->getLicenseIdentifier());
×
UNCOV
120
        $info = new Info($this->openApiOptions->getTitle(), $this->openApiOptions->getVersion(), trim($this->openApiOptions->getDescription()), $this->openApiOptions->getTermsOfService(), $contact, $license);
×
UNCOV
121
        $servers = '/' === $baseUrl || '' === $baseUrl ? [new Server('/')] : [new Server($baseUrl)];
×
UNCOV
122
        $paths = new Paths();
×
UNCOV
123
        $schemas = new \ArrayObject();
×
UNCOV
124
        $webhooks = new \ArrayObject();
×
UNCOV
125
        $tags = [];
×
126

UNCOV
127
        foreach ($this->resourceNameCollectionFactory->create() as $resourceClass) {
×
UNCOV
128
            $resourceMetadataCollection = $this->resourceMetadataFactory->create($resourceClass);
×
UNCOV
129
            foreach ($resourceMetadataCollection as $resourceMetadata) {
×
UNCOV
130
                $this->collectPaths($resourceMetadata, $resourceMetadataCollection, $paths, $schemas, $webhooks, $tags, $context);
×
131
            }
132
        }
133

UNCOV
134
        $securitySchemes = $this->getSecuritySchemes();
×
UNCOV
135
        $securityRequirements = [];
×
136

UNCOV
137
        foreach (array_keys($securitySchemes) as $key) {
×
UNCOV
138
            $securityRequirements[] = [$key => []];
×
139
        }
140

UNCOV
141
        $globalTags = $this->openApiOptions->getTags() ?: array_values($tags) ?: [];
×
142

UNCOV
143
        return new OpenApi(
×
UNCOV
144
            $info,
×
UNCOV
145
            $servers,
×
UNCOV
146
            $paths,
×
UNCOV
147
            new Components(
×
UNCOV
148
                $schemas,
×
UNCOV
149
                new \ArrayObject(),
×
UNCOV
150
                new \ArrayObject(),
×
UNCOV
151
                new \ArrayObject(),
×
UNCOV
152
                new \ArrayObject(),
×
UNCOV
153
                new \ArrayObject(),
×
UNCOV
154
                new \ArrayObject($securitySchemes)
×
UNCOV
155
            ),
×
UNCOV
156
            $securityRequirements,
×
UNCOV
157
            $globalTags,
×
UNCOV
158
            null,
×
UNCOV
159
            null,
×
UNCOV
160
            $webhooks
×
UNCOV
161
        );
×
162
    }
163

164
    private function collectPaths(ApiResource $resource, ResourceMetadataCollection $resourceMetadataCollection, Paths $paths, \ArrayObject $schemas, \ArrayObject $webhooks, array &$tags, array $context = []): void
165
    {
UNCOV
166
        if (0 === $resource->getOperations()->count()) {
×
167
            return;
×
168
        }
169

UNCOV
170
        $defaultError = $this->getErrorResource($this->openApiOptions->getErrorResourceClass() ?? ApiResourceError::class);
×
UNCOV
171
        $defaultValidationError = $this->getErrorResource($this->openApiOptions->getValidationErrorResourceClass() ?? ValidationException::class, 422, 'Unprocessable entity');
×
172

173
        // This filters on our extension x-apiplatform-tag as the openapi operation tag is used for ordering operations
UNCOV
174
        $filteredTags = $context['filter_tags'] ?? [];
×
UNCOV
175
        if (!\is_array($filteredTags)) {
×
UNCOV
176
            $filteredTags = [$filteredTags];
×
177
        }
178

UNCOV
179
        foreach ($resource->getOperations() as $operationName => $operation) {
×
UNCOV
180
            $resourceShortName = $operation->getShortName() ?? $operation;
×
181
            // No path to return
UNCOV
182
            if (null === $operation->getUriTemplate() && null === $operation->getRouteName()) {
×
183
                continue;
×
184
            }
185

UNCOV
186
            $openapiAttribute = $operation->getOpenapi();
×
187

188
            // Operation ignored from OpenApi
UNCOV
189
            if ($operation instanceof HttpOperation && false === $openapiAttribute) {
×
UNCOV
190
                continue;
×
191
            }
192

193
            // See https://github.com/api-platform/core/issues/6993 we would like to allow only `false` but as we typed `bool` we have this check
UNCOV
194
            $operationTag = !\is_object($openapiAttribute) ? [] : ($openapiAttribute->getExtensionProperties()[self::API_PLATFORM_TAG] ?? []);
×
UNCOV
195
            if (!\is_array($operationTag)) {
×
UNCOV
196
                $operationTag = [$operationTag];
×
197
            }
198

UNCOV
199
            if ($filteredTags && $filteredTags !== array_intersect($filteredTags, $operationTag)) {
×
UNCOV
200
                continue;
×
201
            }
202

UNCOV
203
            $resourceClass = $operation->getClass() ?? $resource->getClass();
×
UNCOV
204
            $routeName = $operation->getRouteName() ?? $operation->getName();
×
205

UNCOV
206
            if (!$this->routeCollection && $this->router) {
×
UNCOV
207
                $this->routeCollection = $this->router->getRouteCollection();
×
208
            }
209

UNCOV
210
            if ($this->routeCollection && $routeName && $route = $this->routeCollection->get($routeName)) {
×
UNCOV
211
                $path = $route->getPath();
×
212
            } else {
213
                $path = rtrim($operation->getRoutePrefix() ?? '', '/').'/'.ltrim($operation->getUriTemplate() ?? '', '/');
×
214
            }
215

UNCOV
216
            $path = $this->getPath($path);
×
UNCOV
217
            $method = $operation->getMethod() ?? 'GET';
×
218

UNCOV
219
            if (!\in_array($method, PathItem::$methods, true)) {
×
220
                continue;
×
221
            }
222

UNCOV
223
            $pathItem = null;
×
224

UNCOV
225
            if ($openapiAttribute instanceof Webhook) {
×
226
                $pathItem = $openapiAttribute->getPathItem() ?: new PathItem();
×
227
                $openapiOperation = $pathItem->{'get'.ucfirst(strtolower($method))}() ?: new Operation();
×
UNCOV
228
            } elseif (!\is_object($openapiAttribute)) {
×
UNCOV
229
                $openapiOperation = new Operation();
×
230
            } else {
UNCOV
231
                $openapiOperation = $openapiAttribute;
×
232
            }
233

234
            // Complete with defaults
UNCOV
235
            $openapiOperation = new Operation(
×
UNCOV
236
                operationId: null !== $openapiOperation->getOperationId() ? $openapiOperation->getOperationId() : $this->normalizeOperationName($operationName),
×
UNCOV
237
                tags: null !== $openapiOperation->getTags() ? $openapiOperation->getTags() : [$operation->getShortName() ?: $resourceShortName],
×
UNCOV
238
                responses: null !== $openapiOperation->getResponses() ? $openapiOperation->getResponses() : [],
×
UNCOV
239
                summary: null !== $openapiOperation->getSummary() ? $openapiOperation->getSummary() : $this->getPathDescription($resourceShortName, $method, $operation instanceof CollectionOperationInterface),
×
UNCOV
240
                description: null !== $openapiOperation->getDescription() ? $openapiOperation->getDescription() : $this->getPathDescription($resourceShortName, $method, $operation instanceof CollectionOperationInterface),
×
UNCOV
241
                externalDocs: $openapiOperation->getExternalDocs(),
×
UNCOV
242
                parameters: null !== $openapiOperation->getParameters() ? $openapiOperation->getParameters() : [],
×
UNCOV
243
                requestBody: $openapiOperation->getRequestBody(),
×
UNCOV
244
                callbacks: $openapiOperation->getCallbacks(),
×
UNCOV
245
                deprecated: null !== $openapiOperation->getDeprecated() ? $openapiOperation->getDeprecated() : ($operation->getDeprecationReason() ? true : null),
×
UNCOV
246
                security: null !== $openapiOperation->getSecurity() ? $openapiOperation->getSecurity() : null,
×
UNCOV
247
                servers: null !== $openapiOperation->getServers() ? $openapiOperation->getServers() : null,
×
UNCOV
248
                extensionProperties: $openapiOperation->getExtensionProperties(),
×
UNCOV
249
            );
×
250

UNCOV
251
            foreach ($openapiOperation->getTags() as $v) {
×
UNCOV
252
                $tags[$v] = new Tag(name: $v, description: $resource->getDescription() ?? "Resource '$v' operations.");
×
253
            }
254

UNCOV
255
            [$requestMimeTypes, $responseMimeTypes] = $this->getMimeTypes($operation);
×
256

UNCOV
257
            if ($path) {
×
UNCOV
258
                $pathItem = $paths->getPath($path) ?: new PathItem();
×
259
            } elseif (!$pathItem) {
×
260
                $pathItem = new PathItem();
×
261
            }
262

UNCOV
263
            $forceSchemaCollection = $operation instanceof CollectionOperationInterface && 'GET' === $method;
×
UNCOV
264
            $schema = new Schema('openapi');
×
UNCOV
265
            $schema->setDefinitions($schemas);
×
266

UNCOV
267
            $operationOutputSchemas = [];
×
268

UNCOV
269
            foreach ($responseMimeTypes as $operationFormat) {
×
UNCOV
270
                $operationOutputSchema = null;
×
271
                // Having JSONSchema for non-json schema makes no sense
UNCOV
272
                if (str_starts_with($operationFormat, 'json')) {
×
UNCOV
273
                    $operationOutputSchema = $this->jsonSchemaFactory->buildSchema($resourceClass, $operationFormat, Schema::TYPE_OUTPUT, $operation, $schema, null, $forceSchemaCollection);
×
UNCOV
274
                    $this->appendSchemaDefinitions($schemas, $operationOutputSchema->getDefinitions());
×
275
                }
276

UNCOV
277
                $operationOutputSchemas[$operationFormat] = $operationOutputSchema;
×
278
            }
279

280
            // Set up parameters
UNCOV
281
            $openapiParameters = $openapiOperation->getParameters();
×
UNCOV
282
            foreach ($operation->getUriVariables() ?? [] as $parameterName => $uriVariable) {
×
UNCOV
283
                if ($uriVariable->getExpandedValue() ?? false) {
×
UNCOV
284
                    continue;
×
285
                }
286

UNCOV
287
                $parameter = new Parameter(
×
UNCOV
288
                    $parameterName,
×
UNCOV
289
                    'path',
×
UNCOV
290
                    $uriVariable->getDescription() ?? "$resourceShortName identifier",
×
UNCOV
291
                    $uriVariable->getRequired() ?? true,
×
UNCOV
292
                    false,
×
UNCOV
293
                    null,
×
UNCOV
294
                    $uriVariable->getSchema() ?? ['type' => 'string'],
×
UNCOV
295
                );
×
296

UNCOV
297
                if ($linkParameter = $uriVariable->getOpenApi()) {
×
298
                    $parameter = $this->mergeParameter($parameter, $linkParameter);
×
299
                }
300

UNCOV
301
                if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $parameter)) {
×
302
                    $openapiParameters[$i] = $this->mergeParameter($parameter, $operationParameter);
×
303
                    continue;
×
304
                }
305

UNCOV
306
                $openapiParameters[] = $parameter;
×
307
            }
308

UNCOV
309
            $openapiOperation = $openapiOperation->withParameters($openapiParameters);
×
310

UNCOV
311
            if ($operation instanceof CollectionOperationInterface && 'POST' !== $method) {
×
UNCOV
312
                foreach (array_merge($this->getPaginationParameters($operation), $this->getFiltersParameters($operation)) as $parameter) {
×
UNCOV
313
                    if ($operationParameter = $this->hasParameter($openapiOperation, $parameter)) {
×
314
                        continue;
×
315
                    }
316

UNCOV
317
                    $openapiOperation = $openapiOperation->withParameter($parameter);
×
318
                }
319
            }
320

UNCOV
321
            $entityClass = $this->getStateOptionsClass($operation, $operation->getClass());
×
UNCOV
322
            $openapiParameters = $openapiOperation->getParameters();
×
UNCOV
323
            foreach ($operation->getParameters() ?? [] as $key => $p) {
×
UNCOV
324
                if (false === $p->getOpenApi()) {
×
UNCOV
325
                    continue;
×
326
                }
327

UNCOV
328
                if (($f = $p->getFilter()) && \is_string($f) && $this->filterLocator && $this->filterLocator->has($f)) {
×
UNCOV
329
                    $filter = $this->filterLocator->get($f);
×
330

UNCOV
331
                    if ($d = $filter->getDescription($entityClass)) {
×
UNCOV
332
                        foreach ($d as $name => $description) {
×
UNCOV
333
                            if ($prop = $p->getProperty()) {
×
334
                                $name = str_replace($prop, $key, $name);
×
335
                            }
336

UNCOV
337
                            $openapiParameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $f);
×
338
                        }
339

UNCOV
340
                        continue;
×
341
                    }
342
                }
343

UNCOV
344
                $in = $p instanceof HeaderParameterInterface ? 'header' : 'query';
×
UNCOV
345
                $defaultParameter = new Parameter(
×
UNCOV
346
                    $key,
×
UNCOV
347
                    $in,
×
UNCOV
348
                    $p->getDescription() ?? "$resourceShortName $key",
×
UNCOV
349
                    $p->getRequired() ?? false,
×
UNCOV
350
                    false,
×
UNCOV
351
                    null,
×
UNCOV
352
                    $p->getSchema() ?? ['type' => 'string'],
×
UNCOV
353
                );
×
354

UNCOV
355
                $linkParameter = $p->getOpenApi();
×
UNCOV
356
                if (null === $linkParameter) {
×
UNCOV
357
                    if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $defaultParameter)) {
×
358
                        $openapiParameters[$i] = $this->mergeParameter($defaultParameter, $operationParameter);
×
359
                    } else {
UNCOV
360
                        $openapiParameters[] = $defaultParameter;
×
361
                    }
362

UNCOV
363
                    continue;
×
364
                }
365

UNCOV
366
                if (\is_array($linkParameter)) {
×
367
                    foreach ($linkParameter as $lp) {
×
368
                        $parameter = $this->mergeParameter($defaultParameter, $lp);
×
369
                        if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $parameter)) {
×
370
                            $openapiParameters[$i] = $this->mergeParameter($parameter, $operationParameter);
×
371
                            continue;
×
372
                        }
373

374
                        $openapiParameters[] = $parameter;
×
375
                    }
376
                    continue;
×
377
                }
378

UNCOV
379
                $parameter = $this->mergeParameter($defaultParameter, $linkParameter);
×
UNCOV
380
                if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $parameter)) {
×
381
                    $openapiParameters[$i] = $this->mergeParameter($parameter, $operationParameter);
×
382
                    continue;
×
383
                }
UNCOV
384
                $openapiParameters[] = $parameter;
×
385
            }
386

UNCOV
387
            $openapiOperation = $openapiOperation->withParameters($openapiParameters);
×
UNCOV
388
            $existingResponses = $openapiOperation->getResponses() ?: [];
×
UNCOV
389
            $overrideResponses = $operation->getExtraProperties()[self::OVERRIDE_OPENAPI_RESPONSES] ?? $this->openApiOptions->getOverrideResponses();
×
UNCOV
390
            $errors = null;
×
UNCOV
391
            if ($operation instanceof HttpOperation && null !== ($errors = $operation->getErrors())) {
×
392
                /** @var array<class-string|string, Error> */
393
                $errorOperations = [];
×
394
                foreach ($errors as $error) {
×
395
                    $errorOperations[$error] = $this->getErrorResource($error);
×
396
                }
397

398
                $openapiOperation = $this->addOperationErrors($openapiOperation, $errorOperations, $resourceMetadataCollection, $schema, $schemas, $operation);
×
399
            }
400

UNCOV
401
            if ($overrideResponses || !$existingResponses) {
×
402
                // Create responses
403
                switch ($method) {
UNCOV
404
                    case 'GET':
×
UNCOV
405
                        $successStatus = (string) $operation->getStatus() ?: 200;
×
UNCOV
406
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s %s', $resourceShortName, $operation instanceof CollectionOperationInterface ? 'collection' : 'resource'), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas);
×
UNCOV
407
                        break;
×
UNCOV
408
                    case 'POST':
×
UNCOV
409
                        $successStatus = (string) $operation->getStatus() ?: 201;
×
UNCOV
410
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource created', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
×
411

UNCOV
412
                        if (null === $errors) {
×
UNCOV
413
                            $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
414
                                $defaultError->withStatus(400)->withDescription('Invalid input'),
×
UNCOV
415
                                $defaultValidationError,
×
UNCOV
416
                            ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
417
                        }
UNCOV
418
                        break;
×
UNCOV
419
                    case 'PATCH':
×
UNCOV
420
                    case 'PUT':
×
UNCOV
421
                        $successStatus = (string) $operation->getStatus() ?: 200;
×
UNCOV
422
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource updated', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
×
423

UNCOV
424
                        if (null === $errors) {
×
UNCOV
425
                            $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
426
                                $defaultError->withStatus(400)->withDescription('Invalid input'),
×
UNCOV
427
                                $defaultValidationError,
×
UNCOV
428
                            ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
429
                        }
UNCOV
430
                        break;
×
UNCOV
431
                    case 'DELETE':
×
UNCOV
432
                        $successStatus = (string) $operation->getStatus() ?: 204;
×
UNCOV
433
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource deleted', $resourceShortName), $openapiOperation);
×
UNCOV
434
                        break;
×
435
                }
436
            }
437

UNCOV
438
            if ($overrideResponses && !isset($existingResponses[403]) && $operation->getSecurity()) {
×
439
                $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
440
                    $defaultError->withStatus(403)->withDescription('Forbidden'),
×
441
                ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
442
            }
443

UNCOV
444
            if ($overrideResponses && !$operation instanceof CollectionOperationInterface && 'POST' !== $operation->getMethod() && !isset($existingResponses[404]) && null === $errors) {
×
UNCOV
445
                $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
446
                    $defaultError->withStatus(404)->withDescription('Not found'),
×
UNCOV
447
                ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
448
            }
449

UNCOV
450
            if (!$openapiOperation->getResponses()) {
×
451
                $openapiOperation = $openapiOperation->withResponse('default', new Response('Unexpected error'));
×
452
            }
453

454
            if (
UNCOV
455
                \in_array($method, ['PATCH', 'PUT', 'POST'], true)
×
UNCOV
456
                && !(false === ($input = $operation->getInput()) || (\is_array($input) && null === $input['class']))
×
457
            ) {
UNCOV
458
                $content = $openapiOperation->getRequestBody()?->getContent();
×
UNCOV
459
                if (null === $content) {
×
UNCOV
460
                    $operationInputSchemas = [];
×
UNCOV
461
                    foreach ($requestMimeTypes as $operationFormat) {
×
UNCOV
462
                        $operationInputSchema = null;
×
UNCOV
463
                        if (str_starts_with($operationFormat, 'json')) {
×
UNCOV
464
                            $operationInputSchema = $this->jsonSchemaFactory->buildSchema($resourceClass, $operationFormat, Schema::TYPE_INPUT, $operation, $schema, null, $forceSchemaCollection);
×
UNCOV
465
                            $this->appendSchemaDefinitions($schemas, $operationInputSchema->getDefinitions());
×
466
                        }
467

UNCOV
468
                        $operationInputSchemas[$operationFormat] = $operationInputSchema;
×
469
                    }
UNCOV
470
                    $content = $this->buildContent($requestMimeTypes, $operationInputSchemas);
×
471
                }
472

UNCOV
473
                $openapiOperation = $openapiOperation->withRequestBody(new RequestBody(
×
UNCOV
474
                    description: $openapiOperation->getRequestBody()?->getDescription() ?? \sprintf('The %s %s resource', 'POST' === $method ? 'new' : 'updated', $resourceShortName),
×
UNCOV
475
                    content: $content,
×
UNCOV
476
                    required: $openapiOperation->getRequestBody()?->getRequired() ?? true,
×
UNCOV
477
                ));
×
478
            }
479

UNCOV
480
            if ($openapiAttribute instanceof Webhook) {
×
481
                $webhooks[$openapiAttribute->getName()] = $pathItem->{'with'.ucfirst($method)}($openapiOperation);
×
482
                continue;
×
483
            }
484

485
            // We merge content types for errors, maybe that this logic could be applied to every resources at some point
UNCOV
486
            if ($operation instanceof Error && ($existingPathItem = $paths->getPath($path)) && ($existingOperation = $existingPathItem->getGet()) && ($currentResponse = $openapiOperation->getResponses()[200] ?? null)) {
×
487
                $errorResponse = $existingOperation->getResponses()[200];
×
488
                $currentResponseContent = $currentResponse->getContent();
×
489

490
                foreach ($errorResponse->getContent() as $mime => $content) {
×
491
                    $currentResponseContent[$mime] = $content;
×
492
                }
493

494
                $openapiOperation = $existingOperation->withResponse(200, $currentResponse->withContent($currentResponseContent));
×
495
            }
496

UNCOV
497
            $paths->addPath($path, $pathItem->{'with'.ucfirst($method)}($openapiOperation));
×
498
        }
499
    }
500

501
    private function buildOpenApiResponse(array $existingResponses, int|string $status, string $description, ?Operation $openapiOperation = null, ?HttpOperation $operation = null, ?array $responseMimeTypes = null, ?array $operationOutputSchemas = null, ?ResourceMetadataCollection $resourceMetadataCollection = null): Operation
502
    {
UNCOV
503
        if (isset($existingResponses[$status])) {
×
504
            return $openapiOperation;
×
505
        }
UNCOV
506
        $responseLinks = $responseContent = null;
×
UNCOV
507
        if ($responseMimeTypes && $operationOutputSchemas) {
×
UNCOV
508
            $responseContent = $this->buildContent($responseMimeTypes, $operationOutputSchemas);
×
509
        }
UNCOV
510
        if ($resourceMetadataCollection && $operation) {
×
UNCOV
511
            $responseLinks = $this->getLinks($resourceMetadataCollection, $operation);
×
512
        }
513

UNCOV
514
        return $openapiOperation->withResponse($status, new Response($description, $responseContent, null, $responseLinks));
×
515
    }
516

517
    /**
518
     * @param array<string, string> $responseMimeTypes
519
     * @param array<string, Schema> $operationSchemas
520
     *
521
     * @return \ArrayObject<MediaType>
522
     */
523
    private function buildContent(array $responseMimeTypes, array $operationSchemas): \ArrayObject
524
    {
525
        /** @var \ArrayObject<MediaType> $content */
UNCOV
526
        $content = new \ArrayObject();
×
527

UNCOV
528
        foreach ($responseMimeTypes as $mimeType => $format) {
×
UNCOV
529
            $content[$mimeType] = isset($operationSchemas[$format]) ? new MediaType(schema: new \ArrayObject($operationSchemas[$format]->getArrayCopy(false))) : new \ArrayObject();
×
530
        }
531

UNCOV
532
        return $content;
×
533
    }
534

535
    /**
536
     * @return array[array<string, string>, array<string, string>]
537
     */
538
    private function getMimeTypes(HttpOperation $operation): array
539
    {
UNCOV
540
        $requestFormats = $operation->getInputFormats() ?: [];
×
UNCOV
541
        $responseFormats = $operation->getOutputFormats() ?: [];
×
542

UNCOV
543
        $requestMimeTypes = $this->flattenMimeTypes($requestFormats);
×
UNCOV
544
        $responseMimeTypes = $this->flattenMimeTypes($responseFormats);
×
545

UNCOV
546
        return [$requestMimeTypes, $responseMimeTypes];
×
547
    }
548

549
    /**
550
     * @param array<string, string[]> $responseFormats
551
     *
552
     * @return array<string, string>
553
     */
554
    private function flattenMimeTypes(array $responseFormats): array
555
    {
UNCOV
556
        $responseMimeTypes = [];
×
UNCOV
557
        foreach ($responseFormats as $responseFormat => $mimeTypes) {
×
UNCOV
558
            foreach ($mimeTypes as $mimeType) {
×
UNCOV
559
                $responseMimeTypes[$mimeType] = $responseFormat;
×
560
            }
561
        }
562

UNCOV
563
        return $responseMimeTypes;
×
564
    }
565

566
    /**
567
     * Gets the path for an operation.
568
     *
569
     * If the path ends with the optional _format parameter, it is removed
570
     * as optional path parameters are not yet supported.
571
     *
572
     * @see https://github.com/OAI/OpenAPI-Specification/issues/93
573
     */
574
    private function getPath(string $path): string
575
    {
576
        // Handle either API Platform's URI Template (rfc6570) or Symfony's route
UNCOV
577
        if (str_ends_with($path, '{._format}') || str_ends_with($path, '.{_format}')) {
×
UNCOV
578
            $path = substr($path, 0, -10);
×
579
        }
580

UNCOV
581
        return str_starts_with($path, '/') ? $path : '/'.$path;
×
582
    }
583

584
    private function getPathDescription(string $resourceShortName, string $method, bool $isCollection): string
585
    {
586
        switch ($method) {
UNCOV
587
            case 'GET':
×
UNCOV
588
                $pathSummary = $isCollection ? 'Retrieves the collection of %s resources.' : 'Retrieves a %s resource.';
×
UNCOV
589
                break;
×
UNCOV
590
            case 'POST':
×
UNCOV
591
                $pathSummary = 'Creates a %s resource.';
×
UNCOV
592
                break;
×
UNCOV
593
            case 'PATCH':
×
UNCOV
594
                $pathSummary = 'Updates the %s resource.';
×
UNCOV
595
                break;
×
UNCOV
596
            case 'PUT':
×
UNCOV
597
                $pathSummary = 'Replaces the %s resource.';
×
UNCOV
598
                break;
×
UNCOV
599
            case 'DELETE':
×
UNCOV
600
                $pathSummary = 'Removes the %s resource.';
×
UNCOV
601
                break;
×
602
            default:
603
                return $resourceShortName;
×
604
        }
605

UNCOV
606
        return \sprintf($pathSummary, $resourceShortName);
×
607
    }
608

609
    /**
610
     * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#linkObject.
611
     *
612
     * @return \ArrayObject<Link>
613
     */
614
    private function getLinks(ResourceMetadataCollection $resourceMetadataCollection, HttpOperation $currentOperation): \ArrayObject
615
    {
616
        /** @var \ArrayObject<Link> $links */
UNCOV
617
        $links = new \ArrayObject();
×
618

619
        // Only compute get links for now
UNCOV
620
        foreach ($resourceMetadataCollection as $resource) {
×
UNCOV
621
            foreach ($resource->getOperations() as $operationName => $operation) {
×
UNCOV
622
                $parameters = [];
×
UNCOV
623
                $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
×
624
                if (
UNCOV
625
                    $operationName === $operation->getName()
×
UNCOV
626
                    || isset($links[$operationName])
×
UNCOV
627
                    || $operation instanceof CollectionOperationInterface
×
UNCOV
628
                    || 'GET' !== $method
×
629
                ) {
UNCOV
630
                    continue;
×
631
                }
632

633
                // Operation ignored from OpenApi
634
                if ($operation instanceof HttpOperation && (false === $operation->getOpenapi() || $operation->getOpenapi() instanceof Webhook)) {
×
635
                    continue;
×
636
                }
637

638
                $operationUriVariables = $operation->getUriVariables();
×
639
                foreach ($currentOperation->getUriVariables() ?? [] as $parameterName => $uriVariableDefinition) {
×
640
                    if (!isset($operationUriVariables[$parameterName])) {
×
641
                        continue;
×
642
                    }
643

644
                    if ($operationUriVariables[$parameterName]->getIdentifiers() === $uriVariableDefinition->getIdentifiers() && $operationUriVariables[$parameterName]->getFromClass() === $uriVariableDefinition->getFromClass()) {
×
645
                        $parameters[$parameterName] = '$request.path.'.($uriVariableDefinition->getIdentifiers()[0] ?? 'id');
×
646
                    }
647
                }
648

649
                foreach ($operationUriVariables ?? [] as $parameterName => $uriVariableDefinition) {
×
650
                    if (isset($parameters[$parameterName])) {
×
651
                        continue;
×
652
                    }
653

654
                    if ($uriVariableDefinition->getFromClass() === $currentOperation->getClass()) {
×
655
                        $parameters[$parameterName] = '$response.body#/'.($uriVariableDefinition->getIdentifiers()[0] ?? 'id');
×
656
                    }
657
                }
658

659
                $links[$operationName] = new Link(
×
660
                    $operationName,
×
661
                    new \ArrayObject($parameters),
×
662
                    null,
×
663
                    $operation->getDescription() ?? ''
×
664
                );
×
665
            }
666
        }
667

UNCOV
668
        return $links;
×
669
    }
670

671
    /**
672
     * Gets parameters corresponding to enabled filters.
673
     */
674
    private function getFiltersParameters(CollectionOperationInterface|HttpOperation $operation): array
675
    {
UNCOV
676
        $parameters = [];
×
UNCOV
677
        $resourceFilters = $operation->getFilters();
×
UNCOV
678
        $entityClass = $this->getStateOptionsClass($operation, $operation->getClass());
×
679

UNCOV
680
        foreach ($resourceFilters ?? [] as $filterId) {
×
UNCOV
681
            if (!$this->filterLocator->has($filterId)) {
×
682
                continue;
×
683
            }
684

UNCOV
685
            $filter = $this->filterLocator->get($filterId);
×
UNCOV
686
            foreach ($filter->getDescription($entityClass) as $name => $description) {
×
UNCOV
687
                $parameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $filterId);
×
688
            }
689
        }
690

UNCOV
691
        return $parameters;
×
692
    }
693

694
    /**
695
     * @param array<string, mixed> $description
696
     */
697
    private function getFilterParameter(string $name, array $description, string $shortName, string $filter): Parameter
698
    {
UNCOV
699
        if (isset($description['swagger'])) {
×
700
            trigger_deprecation('api-platform/core', '4.0', \sprintf('Using the "swagger" field of the %s::getDescription() (%s) is deprecated.', $filter, $shortName));
×
701
        }
702

UNCOV
703
        if (!isset($description['openapi']) || $description['openapi'] instanceof Parameter) {
×
UNCOV
704
            $schema = $description['schema'] ?? [];
×
705

UNCOV
706
            if (method_exists(PropertyInfoExtractor::class, 'getType')) {
×
UNCOV
707
                if (isset($description['type']) && \in_array($description['type'], TypeIdentifier::values(), true) && !isset($schema['type'])) {
×
UNCOV
708
                    $type = Type::builtin($description['type']);
×
UNCOV
709
                    if ($description['is_collection'] ?? false) {
×
UNCOV
710
                        $type = Type::array($type, Type::int());
×
711
                    }
712

UNCOV
713
                    $schema += $this->getType($type);
×
714
                }
715
            // TODO: remove in 5.x
716
            } else {
717
                if (isset($description['type']) && \in_array($description['type'], LegacyType::$builtinTypes, true) && !isset($schema['type'])) {
×
718
                    $schema += $this->getType(new LegacyType($description['type'], false, null, $description['is_collection'] ?? false));
×
719
                }
720
            }
721

UNCOV
722
            if (!isset($schema['type'])) {
×
UNCOV
723
                $schema['type'] = 'string';
×
724
            }
725

UNCOV
726
            $arrayValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::ARRAY->value : LegacyType::BUILTIN_TYPE_ARRAY;
×
UNCOV
727
            $objectValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::OBJECT->value : LegacyType::BUILTIN_TYPE_OBJECT;
×
728

UNCOV
729
            $style = 'array' === ($schema['type'] ?? null) && \in_array(
×
UNCOV
730
                $description['type'],
×
UNCOV
731
                [$arrayValueType, $objectValueType],
×
UNCOV
732
                true
×
UNCOV
733
            ) ? 'deepObject' : 'form';
×
734

UNCOV
735
            $parameter = isset($description['openapi']) && $description['openapi'] instanceof Parameter ? $description['openapi'] : new Parameter(in: 'query', name: $name, style: $style, explode: $description['is_collection'] ?? false);
×
736

UNCOV
737
            if ('' === $parameter->getDescription() && ($str = $description['description'] ?? '')) {
×
738
                $parameter = $parameter->withDescription($str);
×
739
            }
740

UNCOV
741
            if (false === $parameter->getRequired() && false !== ($required = $description['required'] ?? false)) {
×
742
                $parameter = $parameter->withRequired($required);
×
743
            }
744

UNCOV
745
            return $parameter->withSchema($schema);
×
746
        }
747

748
        trigger_deprecation('api-platform/core', '4.0', \sprintf('Not using "%s" on the "openapi" field of the %s::getDescription() (%s) is deprecated.', Parameter::class, $filter, $shortName));
×
749

750
        $schema = $description['schema'] ?? null;
×
751

752
        if (!$schema) {
×
753
            if (method_exists(PropertyInfoExtractor::class, 'getType')) {
×
754
                if (isset($description['type']) && \in_array($description['type'], TypeIdentifier::values(), true)) {
×
755
                    $type = Type::builtin($description['type']);
×
756
                    if ($description['is_collection'] ?? false) {
×
757
                        $type = Type::array($type, key: Type::int());
×
758
                    }
759
                    $schema = $this->getType($type);
×
760
                } else {
761
                    $schema = ['type' => 'string'];
×
762
                }
763
            // TODO: remove in 5.x
764
            } else {
765
                $schema = isset($description['type']) && \in_array($description['type'], LegacyType::$builtinTypes, true)
×
766
                    ? $this->getType(new LegacyType($description['type'], false, null, $description['is_collection'] ?? false))
×
767
                    : ['type' => 'string'];
×
768
            }
769
        }
770

771
        $arrayValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::ARRAY->value : LegacyType::BUILTIN_TYPE_ARRAY;
×
772
        $objectValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::OBJECT->value : LegacyType::BUILTIN_TYPE_OBJECT;
×
773

774
        return new Parameter(
×
775
            $name,
×
776
            'query',
×
777
            $description['description'] ?? '',
×
778
            $description['required'] ?? false,
×
779
            $description['openapi']['deprecated'] ?? false,
×
780
            $description['openapi']['allowEmptyValue'] ?? null,
×
781
            $schema,
×
782
            'array' === $schema['type'] && \in_array(
×
783
                $description['type'],
×
784
                [$arrayValueType, $objectValueType],
×
785
                true
×
786
            ) ? 'deepObject' : 'form',
×
787
            $description['openapi']['explode'] ?? ('array' === $schema['type']),
×
788
            $description['openapi']['allowReserved'] ?? null,
×
789
            $description['openapi']['example'] ?? null,
×
790
            isset(
×
791
                $description['openapi']['examples']
×
792
            ) ? new \ArrayObject($description['openapi']['examples']) : null
×
793
        );
×
794
    }
795

796
    private function getPaginationParameters(CollectionOperationInterface|HttpOperation $operation): array
797
    {
UNCOV
798
        if (!$this->paginationOptions->isPaginationEnabled()) {
×
799
            return [];
×
800
        }
801

UNCOV
802
        $parameters = [];
×
803

UNCOV
804
        if ($operation->getPaginationEnabled() ?? $this->paginationOptions->isPaginationEnabled()) {
×
UNCOV
805
            $parameters[] = new Parameter(
×
UNCOV
806
                $this->paginationOptions->getPaginationPageParameterName(),
×
UNCOV
807
                'query',
×
UNCOV
808
                'The collection page number',
×
UNCOV
809
                false,
×
UNCOV
810
                false,
×
UNCOV
811
                null,
×
UNCOV
812
                ['type' => 'integer', 'default' => 1],
×
UNCOV
813
            );
×
814

UNCOV
815
            if ($operation->getPaginationClientItemsPerPage() ?? $this->paginationOptions->getClientItemsPerPage()) {
×
UNCOV
816
                $schema = [
×
UNCOV
817
                    'type' => 'integer',
×
UNCOV
818
                    'default' => $operation->getPaginationItemsPerPage() ?? $this->paginationOptions->getItemsPerPage(),
×
UNCOV
819
                    'minimum' => 0,
×
UNCOV
820
                ];
×
821

UNCOV
822
                if (null !== $maxItemsPerPage = ($operation->getPaginationMaximumItemsPerPage() ?? $this->paginationOptions->getMaximumItemsPerPage())) {
×
823
                    $schema['maximum'] = $maxItemsPerPage;
×
824
                }
825

UNCOV
826
                $parameters[] = new Parameter(
×
UNCOV
827
                    $this->paginationOptions->getItemsPerPageParameterName(),
×
UNCOV
828
                    'query',
×
UNCOV
829
                    'The number of items per page',
×
UNCOV
830
                    false,
×
UNCOV
831
                    false,
×
UNCOV
832
                    null,
×
UNCOV
833
                    $schema,
×
UNCOV
834
                );
×
835
            }
836
        }
837

UNCOV
838
        if ($operation->getPaginationClientEnabled() ?? $this->paginationOptions->isPaginationClientEnabled()) {
×
UNCOV
839
            $parameters[] = new Parameter(
×
UNCOV
840
                $this->paginationOptions->getPaginationClientEnabledParameterName(),
×
UNCOV
841
                'query',
×
UNCOV
842
                'Enable or disable pagination',
×
UNCOV
843
                false,
×
UNCOV
844
                false,
×
UNCOV
845
                null,
×
UNCOV
846
                ['type' => 'boolean'],
×
UNCOV
847
            );
×
848
        }
849

UNCOV
850
        return $parameters;
×
851
    }
852

853
    private function getOauthSecurityScheme(): SecurityScheme
854
    {
UNCOV
855
        $oauthFlow = new OAuthFlow($this->openApiOptions->getOAuthAuthorizationUrl(), $this->openApiOptions->getOAuthTokenUrl() ?: null, $this->openApiOptions->getOAuthRefreshUrl() ?: null, new \ArrayObject($this->openApiOptions->getOAuthScopes()));
×
UNCOV
856
        $description = \sprintf(
×
UNCOV
857
            'OAuth 2.0 %s Grant',
×
UNCOV
858
            strtolower(preg_replace('/[A-Z]/', ' \\0', lcfirst($this->openApiOptions->getOAuthFlow())))
×
UNCOV
859
        );
×
UNCOV
860
        $implicit = $password = $clientCredentials = $authorizationCode = null;
×
861

UNCOV
862
        switch ($this->openApiOptions->getOAuthFlow()) {
×
UNCOV
863
            case 'implicit':
×
UNCOV
864
                $implicit = $oauthFlow;
×
UNCOV
865
                break;
×
866
            case 'password':
×
867
                $password = $oauthFlow;
×
868
                break;
×
869
            case 'application':
×
870
            case 'clientCredentials':
×
871
                $clientCredentials = $oauthFlow;
×
872
                break;
×
873
            case 'accessCode':
×
874
            case 'authorizationCode':
×
875
                $authorizationCode = $oauthFlow;
×
876
                break;
×
877
            default:
878
                throw new \LogicException('OAuth flow must be one of: implicit, password, clientCredentials, authorizationCode');
×
879
        }
880

UNCOV
881
        return new SecurityScheme($this->openApiOptions->getOAuthType(), $description, null, null, null, null, new OAuthFlows($implicit, $password, $clientCredentials, $authorizationCode), null);
×
882
    }
883

884
    private function getSecuritySchemes(): array
885
    {
UNCOV
886
        $securitySchemes = [];
×
887

UNCOV
888
        if ($this->openApiOptions->getOAuthEnabled()) {
×
UNCOV
889
            $securitySchemes['oauth'] = $this->getOauthSecurityScheme();
×
890
        }
891

UNCOV
892
        foreach ($this->openApiOptions->getApiKeys() as $key => $apiKey) {
×
UNCOV
893
            $description = \sprintf('Value for the %s %s parameter.', $apiKey['name'], $apiKey['type']);
×
UNCOV
894
            $securitySchemes[$key] = new SecurityScheme('apiKey', $description, $apiKey['name'], $apiKey['type']);
×
895
        }
896

UNCOV
897
        foreach ($this->openApiOptions->getHttpAuth() as $key => $httpAuth) {
×
898
            $description = \sprintf('Value for the http %s parameter.', $httpAuth['scheme']);
×
899
            $securitySchemes[$key] = new SecurityScheme('http', $description, null, null, $httpAuth['scheme'], $httpAuth['bearerFormat'] ?? null);
×
900
        }
901

UNCOV
902
        return $securitySchemes;
×
903
    }
904

905
    /**
906
     * @param \ArrayObject<string, mixed> $schemas
907
     * @param \ArrayObject<string, mixed> $definitions
908
     */
909
    private function appendSchemaDefinitions(\ArrayObject $schemas, \ArrayObject $definitions): void
910
    {
UNCOV
911
        foreach ($definitions as $key => $value) {
×
UNCOV
912
            $schemas[$key] = $value;
×
913
        }
914
    }
915

916
    /**
917
     * @return array{0: int, 1: Parameter}|null
918
     */
919
    private function hasParameter(Operation $operation, Parameter $parameter): ?array
920
    {
UNCOV
921
        foreach ($operation->getParameters() as $key => $existingParameter) {
×
UNCOV
922
            if ($existingParameter->getName() === $parameter->getName() && $existingParameter->getIn() === $parameter->getIn()) {
×
923
                return [$key, $existingParameter];
×
924
            }
925
        }
926

UNCOV
927
        return null;
×
928
    }
929

930
    private function mergeParameter(Parameter $actual, Parameter $defined): Parameter
931
    {
932
        foreach (
UNCOV
933
            [
×
UNCOV
934
                'name',
×
UNCOV
935
                'in',
×
UNCOV
936
                'description',
×
UNCOV
937
                'required',
×
UNCOV
938
                'deprecated',
×
UNCOV
939
                'allowEmptyValue',
×
UNCOV
940
                'style',
×
UNCOV
941
                'explode',
×
UNCOV
942
                'allowReserved',
×
UNCOV
943
                'example',
×
UNCOV
944
            ] as $method
×
945
        ) {
UNCOV
946
            $newValue = $defined->{"get$method"}();
×
UNCOV
947
            if (null !== $newValue && $actual->{"get$method"}() !== $newValue) {
×
UNCOV
948
                $actual = $actual->{"with$method"}($newValue);
×
949
            }
950
        }
951

UNCOV
952
        foreach (['examples', 'content', 'schema'] as $method) {
×
UNCOV
953
            $newValue = $defined->{"get$method"}();
×
UNCOV
954
            if ($newValue && \count($newValue) > 0 && $actual->{"get$method"}() !== $newValue) {
×
955
                $actual = $actual->{"with$method"}($newValue);
×
956
            }
957
        }
958

UNCOV
959
        return $actual;
×
960
    }
961

962
    /**
963
     * @param ErrorResource[]              $errors
964
     * @param \ArrayObject<string, Schema> $schemas
965
     */
966
    private function addOperationErrors(
967
        Operation $operation,
968
        array $errors,
969
        ResourceMetadataCollection $resourceMetadataCollection,
970
        Schema $schema,
971
        \ArrayObject $schemas,
972
        HttpOperation $originalOperation,
973
    ): Operation {
UNCOV
974
        foreach ($errors as $errorResource) {
×
UNCOV
975
            $responseMimeTypes = $this->flattenMimeTypes($errorResource->getOutputFormats() ?: $this->errorFormats);
×
UNCOV
976
            foreach ($errorResource->getOperations() as $errorOperation) {
×
UNCOV
977
                if (false === $errorOperation->getOpenApi()) {
×
UNCOV
978
                    continue;
×
979
                }
980

981
                $responseMimeTypes += $this->flattenMimeTypes($errorOperation->getOutputFormats() ?: $this->errorFormats);
×
982
            }
983

UNCOV
984
            foreach ($responseMimeTypes as $mime => $format) {
×
UNCOV
985
                if (!isset($this->errorFormats[$format])) {
×
986
                    unset($responseMimeTypes[$mime]);
×
987
                }
988
            }
989

UNCOV
990
            $operationErrorSchemas = [];
×
UNCOV
991
            foreach ($responseMimeTypes as $operationFormat) {
×
UNCOV
992
                $operationErrorSchema = null;
×
993
                // Having JSONSchema for non-json schema makes no sense
UNCOV
994
                if (str_starts_with($operationFormat, 'json')) {
×
UNCOV
995
                    $operationErrorSchema = $this->jsonSchemaFactory->buildSchema($errorResource->getClass(), $operationFormat, Schema::TYPE_OUTPUT, null, $schema);
×
UNCOV
996
                    $this->appendSchemaDefinitions($schemas, $operationErrorSchema->getDefinitions());
×
997
                }
UNCOV
998
                $operationErrorSchemas[$operationFormat] = $operationErrorSchema;
×
999
            }
1000

UNCOV
1001
            if (!$status = $errorResource->getStatus()) {
×
1002
                throw new RuntimeException(\sprintf('The error class "%s" has no status defined, please either implement ProblemExceptionInterface, or make it an ErrorResource with a status', $errorResource->getClass()));
×
1003
            }
1004

UNCOV
1005
            $operation = $this->buildOpenApiResponse($operation->getResponses() ?: [], $status, $errorResource->getDescription() ?? '', $operation, $originalOperation, $responseMimeTypes, $operationErrorSchemas, $resourceMetadataCollection);
×
1006
        }
1007

UNCOV
1008
        return $operation;
×
1009
    }
1010

1011
    /**
1012
     * @param string|class-string $error
1013
     */
1014
    private function getErrorResource(string $error, ?int $status = null, ?string $description = null): ErrorResource
1015
    {
UNCOV
1016
        if ($this->localErrorResourceCache[$error] ?? null) {
×
UNCOV
1017
            return $this->localErrorResourceCache[$error];
×
1018
        }
1019

UNCOV
1020
        if (is_a($error, ProblemExceptionInterface::class, true)) {
×
1021
            try {
1022
                /** @var ProblemExceptionInterface $exception */
UNCOV
1023
                $exception = new $error();
×
UNCOV
1024
                $status = $exception->getStatus();
×
UNCOV
1025
                $description = $exception->getTitle();
×
UNCOV
1026
            } catch (\TypeError) {
×
1027
            }
1028
        } elseif (class_exists($error)) {
×
1029
            throw new RuntimeException(\sprintf('The error class "%s" does not implement "%s". Did you forget a use statement?', $error, ProblemExceptionInterface::class));
×
1030
        }
1031

UNCOV
1032
        $defaultErrorResourceClass = $this->openApiOptions->getErrorResourceClass() ?? ApiResourceError::class;
×
1033

1034
        try {
UNCOV
1035
            $errorResource = $this->resourceMetadataFactory->create($error)[0] ?? new ErrorResource(status: $status, description: $description, class: $defaultErrorResourceClass);
×
UNCOV
1036
            if (!($errorResource instanceof ErrorResource)) {
×
1037
                throw new RuntimeException(\sprintf('The error class %s is not an ErrorResource', $error));
×
1038
            }
1039

1040
            // Here we want the exception status and expression to override the resource one when available
UNCOV
1041
            if ($status) {
×
UNCOV
1042
                $errorResource = $errorResource->withStatus($status);
×
1043
            }
1044

UNCOV
1045
            if ($description) {
×
UNCOV
1046
                $errorResource = $errorResource->withDescription($description);
×
1047
            }
1048
        } catch (ResourceClassNotFoundException|OperationNotFoundException) {
×
1049
            $errorResource = new ErrorResource(status: $status, description: $description, class: $defaultErrorResourceClass);
×
1050
        }
1051

UNCOV
1052
        if (!$errorResource->getClass()) {
×
1053
            $errorResource = $errorResource->withClass($error);
×
1054
        }
1055

UNCOV
1056
        return $this->localErrorResourceCache[$error] = $errorResource;
×
1057
    }
1058
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc