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

api-platform / core / 15775135891

20 Jun 2025 08:42AM UTC coverage: 22.065% (+0.2%) from 21.876%
15775135891

push

github

soyuka
Merge 4.1

13 of 103 new or added lines in 10 files covered. (12.62%)

868 existing lines in 35 files now uncovered.

11487 of 52060 relevant lines covered (22.06%)

21.72 hits per line

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

76.59
/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
    ) {
103
        $this->filterLocator = $filterLocator;
499✔
104
        $this->openApiOptions = $openApiOptions ?: new Options('API Platform');
499✔
105
        $this->paginationOptions = $paginationOptions ?: new PaginationOptions();
499✔
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
    {
117
        $baseUrl = $context[self::BASE_URL] ?? '/';
22✔
118
        $contact = null === $this->openApiOptions->getContactUrl() || null === $this->openApiOptions->getContactEmail() ? null : new Contact($this->openApiOptions->getContactName(), $this->openApiOptions->getContactUrl(), $this->openApiOptions->getContactEmail());
22✔
119
        $license = null === $this->openApiOptions->getLicenseName() ? null : new License($this->openApiOptions->getLicenseName(), $this->openApiOptions->getLicenseUrl(), $this->openApiOptions->getLicenseIdentifier());
22✔
120
        $info = new Info($this->openApiOptions->getTitle(), $this->openApiOptions->getVersion(), trim($this->openApiOptions->getDescription()), $this->openApiOptions->getTermsOfService(), $contact, $license);
22✔
121
        $servers = '/' === $baseUrl || '' === $baseUrl ? [new Server('/')] : [new Server($baseUrl)];
22✔
122
        $paths = new Paths();
22✔
123
        $schemas = new \ArrayObject();
22✔
124
        $webhooks = new \ArrayObject();
22✔
125
        $tags = [];
22✔
126

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

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

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

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

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

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

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

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

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

186
            $openapiAttribute = $operation->getOpenapi();
22✔
187

188
            // Operation ignored from OpenApi
189
            if ($operation instanceof HttpOperation && false === $openapiAttribute) {
22✔
190
                continue;
22✔
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
194
            $operationTag = !\is_object($openapiAttribute) ? [] : ($openapiAttribute->getExtensionProperties()[self::API_PLATFORM_TAG] ?? []);
22✔
195
            if (!\is_array($operationTag)) {
22✔
196
                $operationTag = [$operationTag];
16✔
197
            }
198

199
            if ($filteredTags && $filteredTags !== array_intersect($filteredTags, $operationTag)) {
22✔
200
                continue;
6✔
201
            }
202

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

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

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

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

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

223
            $pathItem = null;
22✔
224

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

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

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

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

257
            if (null === $pathItem) {
22✔
258
                $pathItem = $paths->getPath($path) ?? new PathItem();
22✔
259
            }
260

261
            $forceSchemaCollection = $operation instanceof CollectionOperationInterface && 'GET' === $method;
22✔
262
            $schema = new Schema('openapi');
22✔
263
            $schema->setDefinitions($schemas);
22✔
264

265
            $operationOutputSchemas = [];
22✔
266

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

275
                $operationOutputSchemas[$operationFormat] = $operationOutputSchema;
22✔
276
            }
277

278
            // Set up parameters
279
            $openapiParameters = $openapiOperation->getParameters();
22✔
280
            foreach ($operation->getUriVariables() ?? [] as $parameterName => $uriVariable) {
22✔
281
                if ($uriVariable->getExpandedValue() ?? false) {
18✔
282
                    continue;
4✔
283
                }
284

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

295
                if ($linkParameter = $uriVariable->getOpenApi()) {
18✔
UNCOV
296
                    $parameter = $this->mergeParameter($parameter, $linkParameter);
×
297
                }
298

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

304
                $openapiParameters[] = $parameter;
18✔
305
            }
306

307
            $openapiOperation = $openapiOperation->withParameters($openapiParameters);
22✔
308

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

315
                    $openapiOperation = $openapiOperation->withParameter($parameter);
22✔
316
                }
317
            }
318

319
            $entityClass = $this->getStateOptionsClass($operation, $operation->getClass());
22✔
320
            $openapiParameters = $openapiOperation->getParameters();
22✔
321
            foreach ($operation->getParameters() ?? [] as $key => $p) {
22✔
322
                if (false === $p->getOpenApi()) {
6✔
323
                    continue;
6✔
324
                }
325

326
                if (($f = $p->getFilter()) && \is_string($f) && $this->filterLocator && $this->filterLocator->has($f)) {
2✔
327
                    $filter = $this->filterLocator->get($f);
2✔
328

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

335
                            $openapiParameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $f);
2✔
336
                        }
337

338
                        continue;
2✔
339
                    }
340
                }
341

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

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

361
                    continue;
2✔
362
                }
363

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

UNCOV
372
                        $openapiParameters[] = $parameter;
×
373
                    }
374
                    continue;
×
375
                }
376

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

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

UNCOV
396
                $openapiOperation = $this->addOperationErrors($openapiOperation, $errorOperations, $resourceMetadataCollection, $schema, $schemas, $operation);
×
397
            }
398

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

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

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

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

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

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

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

466
                        $operationInputSchemas[$operationFormat] = $operationInputSchema;
18✔
467
                    }
468
                    $content = $this->buildContent($requestMimeTypes, $operationInputSchemas);
18✔
469
                }
470

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

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

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

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

UNCOV
492
                $openapiOperation = $existingOperation->withResponse(200, $currentResponse->withContent($currentResponseContent));
×
493
            }
494

495
            $paths->addPath($path, $pathItem->{'with'.ucfirst($method)}($openapiOperation));
22✔
496
        }
497
    }
498

499
    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
500
    {
501
        if (isset($existingResponses[$status])) {
22✔
UNCOV
502
            return $openapiOperation;
×
503
        }
504
        $responseLinks = $responseContent = null;
22✔
505
        if ($responseMimeTypes && $operationOutputSchemas) {
22✔
506
            $responseContent = $this->buildContent($responseMimeTypes, $operationOutputSchemas);
22✔
507
        }
508
        if ($resourceMetadataCollection && $operation) {
22✔
509
            $responseLinks = $this->getLinks($resourceMetadataCollection, $operation);
20✔
510
        }
511

512
        return $openapiOperation->withResponse($status, new Response($description, $responseContent, null, $responseLinks));
22✔
513
    }
514

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

526
        foreach ($responseMimeTypes as $mimeType => $format) {
22✔
527
            $content[$mimeType] = isset($operationSchemas[$format]) ? new MediaType(schema: new \ArrayObject($operationSchemas[$format]->getArrayCopy(false))) : new \ArrayObject();
22✔
528
        }
529

530
        return $content;
22✔
531
    }
532

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

541
        $requestMimeTypes = $this->flattenMimeTypes($requestFormats);
22✔
542
        $responseMimeTypes = $this->flattenMimeTypes($responseFormats);
22✔
543

544
        return [$requestMimeTypes, $responseMimeTypes];
22✔
545
    }
546

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

561
        return $responseMimeTypes;
22✔
562
    }
563

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

579
        return str_starts_with($path, '/') ? $path : '/'.$path;
22✔
580
    }
581

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

604
        return \sprintf($pathSummary, $resourceShortName);
22✔
605
    }
606

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

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

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

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

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

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

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

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

666
        return $links;
20✔
667
    }
668

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

678
        foreach ($resourceFilters ?? [] as $filterId) {
22✔
679
            if (!$this->filterLocator->has($filterId)) {
4✔
UNCOV
680
                continue;
×
681
            }
682

683
            $filter = $this->filterLocator->get($filterId);
4✔
684
            foreach ($filter->getDescription($entityClass) as $name => $description) {
4✔
685
                $parameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $filterId);
4✔
686
            }
687
        }
688

689
        return $parameters;
22✔
690
    }
691

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

701
        if (!isset($description['openapi']) || $description['openapi'] instanceof Parameter) {
6✔
702
            $schema = $description['schema'] ?? [];
6✔
703

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

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

720
            if (!isset($schema['type'])) {
6✔
721
                $schema['type'] = 'string';
4✔
722
            }
723

724
            $arrayValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::ARRAY->value : LegacyType::BUILTIN_TYPE_ARRAY;
6✔
725
            $objectValueType = method_exists(PropertyInfoExtractor::class, 'getType') ? TypeIdentifier::OBJECT->value : LegacyType::BUILTIN_TYPE_OBJECT;
6✔
726

727
            $style = 'array' === ($schema['type'] ?? null) && \in_array(
6✔
728
                $description['type'],
6✔
729
                [$arrayValueType, $objectValueType],
6✔
730
                true
6✔
731
            ) ? 'deepObject' : 'form';
6✔
732

733
            $parameter = isset($description['openapi']) && $description['openapi'] instanceof Parameter ? $description['openapi'] : new Parameter(in: 'query', name: $name, style: $style, explode: $description['is_collection'] ?? false);
6✔
734

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

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

743
            return $parameter->withSchema($schema);
6✔
744
        }
745

UNCOV
746
        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));
×
747

748
        $schema = $description['schema'] ?? null;
×
749

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

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

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

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

800
        $parameters = [];
22✔
801

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

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

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

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

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

848
        return $parameters;
22✔
849
    }
850

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

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

879
        return new SecurityScheme($this->openApiOptions->getOAuthType(), $description, null, null, null, null, new OAuthFlows($implicit, $password, $clientCredentials, $authorizationCode), null);
22✔
880
    }
881

882
    private function getSecuritySchemes(): array
883
    {
884
        $securitySchemes = [];
22✔
885

886
        if ($this->openApiOptions->getOAuthEnabled()) {
22✔
887
            $securitySchemes['oauth'] = $this->getOauthSecurityScheme();
22✔
888
        }
889

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

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

900
        return $securitySchemes;
22✔
901
    }
902

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

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

925
        return null;
22✔
926
    }
927

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

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

957
        return $actual;
2✔
958
    }
959

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

UNCOV
979
                $responseMimeTypes += $this->flattenMimeTypes($errorOperation->getOutputFormats() ?: $this->errorFormats);
×
980
            }
981

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

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

999
            if (!$status = $errorResource->getStatus()) {
20✔
UNCOV
1000
                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()));
×
1001
            }
1002

1003
            $operation = $this->buildOpenApiResponse($operation->getResponses() ?: [], $status, $errorResource->getDescription() ?? '', $operation, $originalOperation, $responseMimeTypes, $operationErrorSchemas, $resourceMetadataCollection);
20✔
1004
        }
1005

1006
        return $operation;
20✔
1007
    }
1008

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

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

1030
        $defaultErrorResourceClass = $this->openApiOptions->getErrorResourceClass() ?? ApiResourceError::class;
22✔
1031

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

1038
            // Here we want the exception status and expression to override the resource one when available
1039
            if ($status) {
22✔
1040
                $errorResource = $errorResource->withStatus($status);
22✔
1041
            }
1042

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

1050
        if (!$errorResource->getClass()) {
22✔
UNCOV
1051
            $errorResource = $errorResource->withClass($error);
×
1052
        }
1053

1054
        return $this->localErrorResourceCache[$error] = $errorResource;
22✔
1055
    }
1056
}
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