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

api-platform / core / 17723449516

15 Sep 2025 05:52AM UTC coverage: 0.0% (-22.6%) from 22.578%
17723449516

Pull #7383

github

web-flow
Merge fa5b61e35 into 949c3c975
Pull Request #7383: fix(metadata): compute isWritable during updates

0 of 6 new or added lines in 4 files covered. (0.0%)

11356 existing lines in 371 files now uncovered.

0 of 48868 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\Type;
60
use Symfony\Component\Routing\RouteCollection;
61
use Symfony\Component\Routing\RouterInterface;
62

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

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

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

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

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

UNCOV
131
        $securitySchemes = $this->getSecuritySchemes();
×
UNCOV
132
        $securityRequirements = [];
×
133

UNCOV
134
        foreach (array_keys($securitySchemes) as $key) {
×
UNCOV
135
            $securityRequirements[] = [$key => []];
×
136
        }
137

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

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

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

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

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

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

UNCOV
183
            $openapiAttribute = $operation->getOpenapi();
×
184

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

190
            // 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
191
            $operationTag = !\is_object($openapiAttribute) ? [] : ($openapiAttribute->getExtensionProperties()[self::API_PLATFORM_TAG] ?? []);
×
UNCOV
192
            if (!\is_array($operationTag)) {
×
UNCOV
193
                $operationTag = [$operationTag];
×
194
            }
195

UNCOV
196
            if ($filteredTags && $filteredTags !== array_intersect($filteredTags, $operationTag)) {
×
UNCOV
197
                continue;
×
198
            }
199

UNCOV
200
            $resourceClass = $operation->getClass() ?? $resource->getClass();
×
UNCOV
201
            $routeName = $operation->getRouteName() ?? $operation->getName();
×
202

UNCOV
203
            if (!$this->routeCollection && $this->router) {
×
UNCOV
204
                $this->routeCollection = $this->router->getRouteCollection();
×
205
            }
206

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

UNCOV
213
            $path = $this->getPath($path);
×
UNCOV
214
            $method = $operation->getMethod() ?? 'GET';
×
215

UNCOV
216
            if (!\in_array($method, PathItem::$methods, true)) {
×
217
                continue;
×
218
            }
219

UNCOV
220
            $pathItem = null;
×
221

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

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

UNCOV
248
            foreach ($openapiOperation->getTags() as $v) {
×
UNCOV
249
                $tags[$v] = new Tag(name: $v, description: $resource->getDescription());
×
250
            }
251

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

UNCOV
254
            if (null === $pathItem) {
×
UNCOV
255
                $pathItem = $paths->getPath($path) ?? new PathItem();
×
256
            }
257

UNCOV
258
            $forceSchemaCollection = $operation instanceof CollectionOperationInterface && 'GET' === $method;
×
UNCOV
259
            $schema = new Schema('openapi');
×
UNCOV
260
            $schema->setDefinitions($schemas);
×
261

UNCOV
262
            $operationOutputSchemas = [];
×
263

UNCOV
264
            foreach ($responseMimeTypes as $operationFormat) {
×
UNCOV
265
                $operationOutputSchema = $this->jsonSchemaFactory->buildSchema($resourceClass, $operationFormat, Schema::TYPE_OUTPUT, $operation, $schema, null, $forceSchemaCollection);
×
UNCOV
266
                $operationOutputSchemas[$operationFormat] = $operationOutputSchema;
×
UNCOV
267
                $this->appendSchemaDefinitions($schemas, $operationOutputSchema->getDefinitions());
×
268
            }
269

270
            // Set up parameters
UNCOV
271
            $openapiParameters = $openapiOperation->getParameters();
×
UNCOV
272
            foreach ($operation->getUriVariables() ?? [] as $parameterName => $uriVariable) {
×
UNCOV
273
                if ($uriVariable->getExpandedValue() ?? false) {
×
UNCOV
274
                    continue;
×
275
                }
276

UNCOV
277
                $parameter = new Parameter($parameterName, 'path', $uriVariable->getDescription() ?? "$resourceShortName identifier", $uriVariable->getRequired() ?? true, false, false, $uriVariable->getSchema() ?? ['type' => 'string']);
×
278

UNCOV
279
                if ($linkParameter = $uriVariable->getOpenApi()) {
×
280
                    $parameter = $this->mergeParameter($parameter, $linkParameter);
×
281
                }
282

UNCOV
283
                if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $parameter)) {
×
284
                    $openapiParameters[$i] = $this->mergeParameter($parameter, $operationParameter);
×
285
                    continue;
×
286
                }
287

UNCOV
288
                $openapiParameters[] = $parameter;
×
289
            }
290

UNCOV
291
            $openapiOperation = $openapiOperation->withParameters($openapiParameters);
×
292

UNCOV
293
            if ($operation instanceof CollectionOperationInterface && 'POST' !== $method) {
×
UNCOV
294
                foreach (array_merge($this->getPaginationParameters($operation), $this->getFiltersParameters($operation)) as $parameter) {
×
UNCOV
295
                    if ($operationParameter = $this->hasParameter($openapiOperation, $parameter)) {
×
296
                        continue;
×
297
                    }
298

UNCOV
299
                    $openapiOperation = $openapiOperation->withParameter($parameter);
×
300
                }
301
            }
302

UNCOV
303
            $entityClass = $this->getStateOptionsClass($operation, $operation->getClass());
×
UNCOV
304
            $openapiParameters = $openapiOperation->getParameters();
×
UNCOV
305
            foreach ($operation->getParameters() ?? [] as $key => $p) {
×
UNCOV
306
                if (false === $p->getOpenApi()) {
×
UNCOV
307
                    continue;
×
308
                }
309

UNCOV
310
                if (($f = $p->getFilter()) && \is_string($f) && $this->filterLocator && $this->filterLocator->has($f)) {
×
UNCOV
311
                    $filter = $this->filterLocator->get($f);
×
312

UNCOV
313
                    if ($d = $filter->getDescription($entityClass)) {
×
UNCOV
314
                        foreach ($d as $name => $description) {
×
UNCOV
315
                            if ($prop = $p->getProperty()) {
×
316
                                $name = str_replace($prop, $key, $name);
×
317
                            }
318

UNCOV
319
                            $openapiParameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $f);
×
320
                        }
321

UNCOV
322
                        continue;
×
323
                    }
324
                }
325

UNCOV
326
                $in = $p instanceof HeaderParameterInterface ? 'header' : 'query';
×
UNCOV
327
                $defaultParameter = new Parameter($key, $in, $p->getDescription() ?? "$resourceShortName $key", $p->getRequired() ?? false, false, false, $p->getSchema() ?? ['type' => 'string']);
×
328

UNCOV
329
                $linkParameter = $p->getOpenApi();
×
UNCOV
330
                if (null === $linkParameter) {
×
UNCOV
331
                    if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $defaultParameter)) {
×
332
                        $openapiParameters[$i] = $this->mergeParameter($defaultParameter, $operationParameter);
×
333
                    } else {
UNCOV
334
                        $openapiParameters[] = $defaultParameter;
×
335
                    }
336

UNCOV
337
                    continue;
×
338
                }
339

UNCOV
340
                if (\is_array($linkParameter)) {
×
341
                    foreach ($linkParameter as $lp) {
×
342
                        $parameter = $this->mergeParameter($defaultParameter, $lp);
×
343
                        if ([$i, $operationParameter] = $this->hasParameter($openapiOperation, $parameter)) {
×
344
                            $openapiParameters[$i] = $this->mergeParameter($parameter, $operationParameter);
×
345
                            continue;
×
346
                        }
347

348
                        $openapiParameters[] = $parameter;
×
349
                    }
350
                    continue;
×
351
                }
352

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

UNCOV
361
            $openapiOperation = $openapiOperation->withParameters($openapiParameters);
×
UNCOV
362
            $existingResponses = $openapiOperation->getResponses() ?: [];
×
UNCOV
363
            $overrideResponses = $operation->getExtraProperties()[self::OVERRIDE_OPENAPI_RESPONSES] ?? $this->openApiOptions->getOverrideResponses();
×
UNCOV
364
            $errors = null;
×
UNCOV
365
            if ($operation instanceof HttpOperation && null !== ($errors = $operation->getErrors())) {
×
366
                /** @var array<class-string|string, Error> */
367
                $errorOperations = [];
×
368
                foreach ($errors as $error) {
×
369
                    $errorOperations[$error] = $this->getErrorResource($error);
×
370
                }
371

372
                $openapiOperation = $this->addOperationErrors($openapiOperation, $errorOperations, $resourceMetadataCollection, $schema, $schemas, $operation);
×
373
            }
374

UNCOV
375
            if ($overrideResponses || !$existingResponses) {
×
376
                // Create responses
377
                switch ($method) {
UNCOV
378
                    case 'GET':
×
UNCOV
379
                        $successStatus = (string) $operation->getStatus() ?: 200;
×
UNCOV
380
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s %s', $resourceShortName, $operation instanceof CollectionOperationInterface ? 'collection' : 'resource'), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas);
×
UNCOV
381
                        break;
×
UNCOV
382
                    case 'POST':
×
UNCOV
383
                        $successStatus = (string) $operation->getStatus() ?: 201;
×
UNCOV
384
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource created', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
×
385

UNCOV
386
                        if (null === $errors) {
×
UNCOV
387
                            $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
388
                                $defaultError->withStatus(400)->withDescription('Invalid input'),
×
UNCOV
389
                                $defaultValidationError,
×
UNCOV
390
                            ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
391
                        }
UNCOV
392
                        break;
×
UNCOV
393
                    case 'PATCH':
×
UNCOV
394
                    case 'PUT':
×
UNCOV
395
                        $successStatus = (string) $operation->getStatus() ?: 200;
×
UNCOV
396
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource updated', $resourceShortName), $openapiOperation, $operation, $responseMimeTypes, $operationOutputSchemas, $resourceMetadataCollection);
×
397

UNCOV
398
                        if (null === $errors) {
×
UNCOV
399
                            $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
400
                                $defaultError->withStatus(400)->withDescription('Invalid input'),
×
UNCOV
401
                                $defaultValidationError,
×
UNCOV
402
                            ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
403
                        }
UNCOV
404
                        break;
×
UNCOV
405
                    case 'DELETE':
×
UNCOV
406
                        $successStatus = (string) $operation->getStatus() ?: 204;
×
UNCOV
407
                        $openapiOperation = $this->buildOpenApiResponse($existingResponses, $successStatus, \sprintf('%s resource deleted', $resourceShortName), $openapiOperation);
×
UNCOV
408
                        break;
×
409
                }
410
            }
411

UNCOV
412
            if ($overrideResponses && !isset($existingResponses[403]) && $operation->getSecurity()) {
×
413
                $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
414
                    $defaultError->withStatus(403)->withDescription('Forbidden'),
×
415
                ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
416
            }
417

UNCOV
418
            if ($overrideResponses && !$operation instanceof CollectionOperationInterface && 'POST' !== $operation->getMethod() && !isset($existingResponses[404]) && null === $errors) {
×
UNCOV
419
                $openapiOperation = $this->addOperationErrors($openapiOperation, [
×
UNCOV
420
                    $defaultError->withStatus(404)->withDescription('Not found'),
×
UNCOV
421
                ], $resourceMetadataCollection, $schema, $schemas, $operation);
×
422
            }
423

UNCOV
424
            if (!$openapiOperation->getResponses()) {
×
425
                $openapiOperation = $openapiOperation->withResponse('default', new Response('Unexpected error'));
×
426
            }
427

428
            if (
UNCOV
429
                \in_array($method, ['PATCH', 'PUT', 'POST'], true)
×
UNCOV
430
                && !(false === ($input = $operation->getInput()) || (\is_array($input) && null === $input['class']))
×
431
            ) {
UNCOV
432
                $content = $openapiOperation->getRequestBody()?->getContent();
×
UNCOV
433
                if (null === $content) {
×
UNCOV
434
                    $operationInputSchemas = [];
×
UNCOV
435
                    foreach ($requestMimeTypes as $operationFormat) {
×
UNCOV
436
                        $operationInputSchema = $this->jsonSchemaFactory->buildSchema($resourceClass, $operationFormat, Schema::TYPE_INPUT, $operation, $schema, null, $forceSchemaCollection);
×
UNCOV
437
                        $operationInputSchemas[$operationFormat] = $operationInputSchema;
×
UNCOV
438
                        $this->appendSchemaDefinitions($schemas, $operationInputSchema->getDefinitions());
×
439
                    }
UNCOV
440
                    $content = $this->buildContent($requestMimeTypes, $operationInputSchemas);
×
441
                }
442

UNCOV
443
                $openapiOperation = $openapiOperation->withRequestBody(new RequestBody(
×
UNCOV
444
                    description: $openapiOperation->getRequestBody()?->getDescription() ?? \sprintf('The %s %s resource', 'POST' === $method ? 'new' : 'updated', $resourceShortName),
×
UNCOV
445
                    content: $content,
×
UNCOV
446
                    required: $openapiOperation->getRequestBody()?->getRequired() ?? true,
×
UNCOV
447
                ));
×
448
            }
449

UNCOV
450
            if ($openapiAttribute instanceof Webhook) {
×
451
                $webhooks[$openapiAttribute->getName()] = $pathItem->{'with'.ucfirst($method)}($openapiOperation);
×
452
                continue;
×
453
            }
454

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

460
                foreach ($errorResponse->getContent() as $mime => $content) {
×
461
                    $currentResponseContent[$mime] = $content;
×
462
                }
463

464
                $openapiOperation = $existingOperation->withResponse(200, $currentResponse->withContent($currentResponseContent));
×
465
            }
466

UNCOV
467
            $paths->addPath($path, $pathItem->{'with'.ucfirst($method)}($openapiOperation));
×
468
        }
469
    }
470

471
    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
472
    {
UNCOV
473
        if (isset($existingResponses[$status])) {
×
474
            return $openapiOperation;
×
475
        }
UNCOV
476
        $responseLinks = $responseContent = null;
×
UNCOV
477
        if ($responseMimeTypes && $operationOutputSchemas) {
×
UNCOV
478
            $responseContent = $this->buildContent($responseMimeTypes, $operationOutputSchemas);
×
479
        }
UNCOV
480
        if ($resourceMetadataCollection && $operation) {
×
UNCOV
481
            $responseLinks = $this->getLinks($resourceMetadataCollection, $operation);
×
482
        }
483

UNCOV
484
        return $openapiOperation->withResponse($status, new Response($description, $responseContent, null, $responseLinks));
×
485
    }
486

487
    /**
488
     * @param array<string, string> $responseMimeTypes
489
     * @param array<string, Schema> $operationSchemas
490
     *
491
     * @return \ArrayObject<MediaType>
492
     */
493
    private function buildContent(array $responseMimeTypes, array $operationSchemas): \ArrayObject
494
    {
495
        /** @var \ArrayObject<MediaType> $content */
UNCOV
496
        $content = new \ArrayObject();
×
497

UNCOV
498
        foreach ($responseMimeTypes as $mimeType => $format) {
×
UNCOV
499
            $content[$mimeType] = new MediaType(new \ArrayObject($operationSchemas[$format]->getArrayCopy(false)));
×
500
        }
501

UNCOV
502
        return $content;
×
503
    }
504

505
    /**
506
     * @return array[array<string, string>, array<string, string>]
507
     */
508
    private function getMimeTypes(HttpOperation $operation): array
509
    {
UNCOV
510
        $requestFormats = $operation->getInputFormats() ?: [];
×
UNCOV
511
        $responseFormats = $operation->getOutputFormats() ?: [];
×
512

UNCOV
513
        $requestMimeTypes = $this->flattenMimeTypes($requestFormats);
×
UNCOV
514
        $responseMimeTypes = $this->flattenMimeTypes($responseFormats);
×
515

UNCOV
516
        return [$requestMimeTypes, $responseMimeTypes];
×
517
    }
518

519
    /**
520
     * @param array<string, string[]> $responseFormats
521
     *
522
     * @return array<string, string>
523
     */
524
    private function flattenMimeTypes(array $responseFormats): array
525
    {
UNCOV
526
        $responseMimeTypes = [];
×
UNCOV
527
        foreach ($responseFormats as $responseFormat => $mimeTypes) {
×
UNCOV
528
            foreach ($mimeTypes as $mimeType) {
×
UNCOV
529
                $responseMimeTypes[$mimeType] = $responseFormat;
×
530
            }
531
        }
532

UNCOV
533
        return $responseMimeTypes;
×
534
    }
535

536
    /**
537
     * Gets the path for an operation.
538
     *
539
     * If the path ends with the optional _format parameter, it is removed
540
     * as optional path parameters are not yet supported.
541
     *
542
     * @see https://github.com/OAI/OpenAPI-Specification/issues/93
543
     */
544
    private function getPath(string $path): string
545
    {
546
        // Handle either API Platform's URI Template (rfc6570) or Symfony's route
UNCOV
547
        if (str_ends_with($path, '{._format}') || str_ends_with($path, '.{_format}')) {
×
UNCOV
548
            $path = substr($path, 0, -10);
×
549
        }
550

UNCOV
551
        return str_starts_with($path, '/') ? $path : '/'.$path;
×
552
    }
553

554
    private function getPathDescription(string $resourceShortName, string $method, bool $isCollection): string
555
    {
556
        switch ($method) {
UNCOV
557
            case 'GET':
×
UNCOV
558
                $pathSummary = $isCollection ? 'Retrieves the collection of %s resources.' : 'Retrieves a %s resource.';
×
UNCOV
559
                break;
×
UNCOV
560
            case 'POST':
×
UNCOV
561
                $pathSummary = 'Creates a %s resource.';
×
UNCOV
562
                break;
×
UNCOV
563
            case 'PATCH':
×
UNCOV
564
                $pathSummary = 'Updates the %s resource.';
×
UNCOV
565
                break;
×
UNCOV
566
            case 'PUT':
×
UNCOV
567
                $pathSummary = 'Replaces the %s resource.';
×
UNCOV
568
                break;
×
UNCOV
569
            case 'DELETE':
×
UNCOV
570
                $pathSummary = 'Removes the %s resource.';
×
UNCOV
571
                break;
×
572
            default:
573
                return $resourceShortName;
×
574
        }
575

UNCOV
576
        return \sprintf($pathSummary, $resourceShortName);
×
577
    }
578

579
    /**
580
     * @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#linkObject.
581
     *
582
     * @return \ArrayObject<Link>
583
     */
584
    private function getLinks(ResourceMetadataCollection $resourceMetadataCollection, HttpOperation $currentOperation): \ArrayObject
585
    {
586
        /** @var \ArrayObject<Link> $links */
UNCOV
587
        $links = new \ArrayObject();
×
588

589
        // Only compute get links for now
UNCOV
590
        foreach ($resourceMetadataCollection as $resource) {
×
UNCOV
591
            foreach ($resource->getOperations() as $operationName => $operation) {
×
UNCOV
592
                $parameters = [];
×
UNCOV
593
                $method = $operation instanceof HttpOperation ? $operation->getMethod() : 'GET';
×
594
                if (
UNCOV
595
                    $operationName === $operation->getName()
×
UNCOV
596
                    || isset($links[$operationName])
×
UNCOV
597
                    || $operation instanceof CollectionOperationInterface
×
UNCOV
598
                    || 'GET' !== $method
×
599
                ) {
UNCOV
600
                    continue;
×
601
                }
602

603
                // Operation ignored from OpenApi
604
                if ($operation instanceof HttpOperation && (false === $operation->getOpenapi() || $operation->getOpenapi() instanceof Webhook)) {
×
605
                    continue;
×
606
                }
607

608
                $operationUriVariables = $operation->getUriVariables();
×
609
                foreach ($currentOperation->getUriVariables() ?? [] as $parameterName => $uriVariableDefinition) {
×
610
                    if (!isset($operationUriVariables[$parameterName])) {
×
611
                        continue;
×
612
                    }
613

614
                    if ($operationUriVariables[$parameterName]->getIdentifiers() === $uriVariableDefinition->getIdentifiers() && $operationUriVariables[$parameterName]->getFromClass() === $uriVariableDefinition->getFromClass()) {
×
615
                        $parameters[$parameterName] = '$request.path.'.($uriVariableDefinition->getIdentifiers()[0] ?? 'id');
×
616
                    }
617
                }
618

619
                foreach ($operationUriVariables ?? [] as $parameterName => $uriVariableDefinition) {
×
620
                    if (isset($parameters[$parameterName])) {
×
621
                        continue;
×
622
                    }
623

624
                    if ($uriVariableDefinition->getFromClass() === $currentOperation->getClass()) {
×
625
                        $parameters[$parameterName] = '$response.body#/'.($uriVariableDefinition->getIdentifiers()[0] ?? 'id');
×
626
                    }
627
                }
628

629
                $links[$operationName] = new Link(
×
630
                    $operationName,
×
631
                    new \ArrayObject($parameters),
×
632
                    null,
×
633
                    $operation->getDescription() ?? ''
×
634
                );
×
635
            }
636
        }
637

UNCOV
638
        return $links;
×
639
    }
640

641
    /**
642
     * Gets parameters corresponding to enabled filters.
643
     */
644
    private function getFiltersParameters(CollectionOperationInterface|HttpOperation $operation): array
645
    {
UNCOV
646
        $parameters = [];
×
UNCOV
647
        $resourceFilters = $operation->getFilters();
×
UNCOV
648
        $entityClass = $this->getStateOptionsClass($operation, $operation->getClass());
×
649

UNCOV
650
        foreach ($resourceFilters ?? [] as $filterId) {
×
UNCOV
651
            if (!$this->filterLocator->has($filterId)) {
×
652
                continue;
×
653
            }
654

UNCOV
655
            $filter = $this->filterLocator->get($filterId);
×
UNCOV
656
            foreach ($filter->getDescription($entityClass) as $name => $description) {
×
UNCOV
657
                $parameters[] = $this->getFilterParameter($name, $description, $operation->getShortName(), $filterId);
×
658
            }
659
        }
660

UNCOV
661
        return $parameters;
×
662
    }
663

664
    /**
665
     * @param array<string, mixed> $description
666
     */
667
    private function getFilterParameter(string $name, array $description, string $shortName, string $filter): Parameter
668
    {
UNCOV
669
        if (isset($description['swagger'])) {
×
670
            trigger_deprecation('api-platform/core', '4.0', \sprintf('Using the "swagger" field of the %s::getDescription() (%s) is deprecated.', $filter, $shortName));
×
671
        }
672

UNCOV
673
        if (!isset($description['openapi']) || $description['openapi'] instanceof Parameter) {
×
UNCOV
674
            $schema = $description['schema'] ?? [];
×
675

UNCOV
676
            if (isset($description['type']) && \in_array($description['type'], Type::$builtinTypes, true) && !isset($schema['type'])) {
×
UNCOV
677
                $schema += $this->getType(new Type($description['type'], false, null, $description['is_collection'] ?? false));
×
678
            }
679

UNCOV
680
            if (!isset($schema['type'])) {
×
UNCOV
681
                $schema['type'] = 'string';
×
682
            }
683

UNCOV
684
            $style = 'array' === ($schema['type'] ?? null) && \in_array(
×
UNCOV
685
                $description['type'],
×
UNCOV
686
                [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_OBJECT],
×
UNCOV
687
                true
×
UNCOV
688
            ) ? 'deepObject' : 'form';
×
689

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

UNCOV
692
            if ('' === $parameter->getDescription() && ($str = $description['description'] ?? '')) {
×
693
                $parameter = $parameter->withDescription($str);
×
694
            }
695

UNCOV
696
            if (false === $parameter->getRequired() && false !== ($required = $description['required'] ?? false)) {
×
UNCOV
697
                $parameter = $parameter->withRequired($required);
×
698
            }
699

UNCOV
700
            return $parameter->withSchema($schema);
×
701
        }
702

703
        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));
×
704
        $schema = $description['schema'] ?? (\in_array($description['type'], Type::$builtinTypes, true) ? $this->getType(new Type($description['type'], false, null, $description['is_collection'] ?? false)) : ['type' => 'string']);
×
705

706
        return new Parameter(
×
707
            $name,
×
708
            'query',
×
709
            $description['description'] ?? '',
×
710
            $description['required'] ?? false,
×
711
            $description['openapi']['deprecated'] ?? false,
×
712
            $description['openapi']['allowEmptyValue'] ?? true,
×
713
            $schema,
×
714
            'array' === $schema['type'] && \in_array(
×
715
                $description['type'],
×
716
                [Type::BUILTIN_TYPE_ARRAY, Type::BUILTIN_TYPE_OBJECT],
×
717
                true
×
718
            ) ? 'deepObject' : 'form',
×
719
            $description['openapi']['explode'] ?? ('array' === $schema['type']),
×
720
            $description['openapi']['allowReserved'] ?? false,
×
721
            $description['openapi']['example'] ?? null,
×
722
            isset(
×
723
                $description['openapi']['examples']
×
724
            ) ? new \ArrayObject($description['openapi']['examples']) : null
×
725
        );
×
726
    }
727

728
    private function getPaginationParameters(CollectionOperationInterface|HttpOperation $operation): array
729
    {
UNCOV
730
        if (!$this->paginationOptions->isPaginationEnabled()) {
×
731
            return [];
×
732
        }
733

UNCOV
734
        $parameters = [];
×
735

UNCOV
736
        if ($operation->getPaginationEnabled() ?? $this->paginationOptions->isPaginationEnabled()) {
×
UNCOV
737
            $parameters[] = new Parameter($this->paginationOptions->getPaginationPageParameterName(), 'query', 'The collection page number', false, false, true, ['type' => 'integer', 'default' => 1]);
×
738

UNCOV
739
            if ($operation->getPaginationClientItemsPerPage() ?? $this->paginationOptions->getClientItemsPerPage()) {
×
UNCOV
740
                $schema = [
×
UNCOV
741
                    'type' => 'integer',
×
UNCOV
742
                    'default' => $operation->getPaginationItemsPerPage() ?? $this->paginationOptions->getItemsPerPage(),
×
UNCOV
743
                    'minimum' => 0,
×
UNCOV
744
                ];
×
745

UNCOV
746
                if (null !== $maxItemsPerPage = ($operation->getPaginationMaximumItemsPerPage() ?? $this->paginationOptions->getMaximumItemsPerPage())) {
×
747
                    $schema['maximum'] = $maxItemsPerPage;
×
748
                }
749

UNCOV
750
                $parameters[] = new Parameter($this->paginationOptions->getItemsPerPageParameterName(), 'query', 'The number of items per page', false, false, true, $schema);
×
751
            }
752
        }
753

UNCOV
754
        if ($operation->getPaginationClientEnabled() ?? $this->paginationOptions->isPaginationClientEnabled()) {
×
UNCOV
755
            $parameters[] = new Parameter($this->paginationOptions->getPaginationClientEnabledParameterName(), 'query', 'Enable or disable pagination', false, false, true, ['type' => 'boolean']);
×
756
        }
757

UNCOV
758
        if ($operation->getPaginationClientPartial() ?? $this->paginationOptions->isClientPartialPaginationEnabled()) {
×
UNCOV
759
            $parameters[] = new Parameter($this->paginationOptions->getPartialPaginationParameterName(), 'query', 'Enable or disable partial pagination', false, false, true, ['type' => 'boolean']);
×
760
        }
761

UNCOV
762
        return $parameters;
×
763
    }
764

765
    private function getOauthSecurityScheme(): SecurityScheme
766
    {
UNCOV
767
        $oauthFlow = new OAuthFlow($this->openApiOptions->getOAuthAuthorizationUrl(), $this->openApiOptions->getOAuthTokenUrl() ?: null, $this->openApiOptions->getOAuthRefreshUrl() ?: null, new \ArrayObject($this->openApiOptions->getOAuthScopes()));
×
UNCOV
768
        $description = \sprintf(
×
UNCOV
769
            'OAuth 2.0 %s Grant',
×
UNCOV
770
            strtolower(preg_replace('/[A-Z]/', ' \\0', lcfirst($this->openApiOptions->getOAuthFlow())))
×
UNCOV
771
        );
×
UNCOV
772
        $implicit = $password = $clientCredentials = $authorizationCode = null;
×
773

UNCOV
774
        switch ($this->openApiOptions->getOAuthFlow()) {
×
UNCOV
775
            case 'implicit':
×
UNCOV
776
                $implicit = $oauthFlow;
×
UNCOV
777
                break;
×
778
            case 'password':
×
779
                $password = $oauthFlow;
×
780
                break;
×
781
            case 'application':
×
782
            case 'clientCredentials':
×
783
                $clientCredentials = $oauthFlow;
×
784
                break;
×
785
            case 'accessCode':
×
786
            case 'authorizationCode':
×
787
                $authorizationCode = $oauthFlow;
×
788
                break;
×
789
            default:
790
                throw new \LogicException('OAuth flow must be one of: implicit, password, clientCredentials, authorizationCode');
×
791
        }
792

UNCOV
793
        return new SecurityScheme($this->openApiOptions->getOAuthType(), $description, null, null, null, null, new OAuthFlows($implicit, $password, $clientCredentials, $authorizationCode), null);
×
794
    }
795

796
    private function getSecuritySchemes(): array
797
    {
UNCOV
798
        $securitySchemes = [];
×
799

UNCOV
800
        if ($this->openApiOptions->getOAuthEnabled()) {
×
UNCOV
801
            $securitySchemes['oauth'] = $this->getOauthSecurityScheme();
×
802
        }
803

UNCOV
804
        foreach ($this->openApiOptions->getApiKeys() as $key => $apiKey) {
×
UNCOV
805
            $description = \sprintf('Value for the %s %s parameter.', $apiKey['name'], $apiKey['type']);
×
UNCOV
806
            $securitySchemes[$key] = new SecurityScheme('apiKey', $description, $apiKey['name'], $apiKey['type']);
×
807
        }
808

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

UNCOV
814
        return $securitySchemes;
×
815
    }
816

817
    /**
818
     * @param \ArrayObject<string, mixed> $schemas
819
     * @param \ArrayObject<string, mixed> $definitions
820
     */
821
    private function appendSchemaDefinitions(\ArrayObject $schemas, \ArrayObject $definitions): void
822
    {
UNCOV
823
        foreach ($definitions as $key => $value) {
×
UNCOV
824
            $schemas[$key] = $value;
×
825
        }
826
    }
827

828
    /**
829
     * @return array{0: int, 1: Parameter}|null
830
     */
831
    private function hasParameter(Operation $operation, Parameter $parameter): ?array
832
    {
UNCOV
833
        foreach ($operation->getParameters() as $key => $existingParameter) {
×
UNCOV
834
            if ($existingParameter->getName() === $parameter->getName() && $existingParameter->getIn() === $parameter->getIn()) {
×
835
                return [$key, $existingParameter];
×
836
            }
837
        }
838

UNCOV
839
        return null;
×
840
    }
841

842
    private function mergeParameter(Parameter $actual, Parameter $defined): Parameter
843
    {
844
        foreach (
UNCOV
845
            [
×
UNCOV
846
                'name',
×
UNCOV
847
                'in',
×
UNCOV
848
                'description',
×
UNCOV
849
                'required',
×
UNCOV
850
                'deprecated',
×
UNCOV
851
                'allowEmptyValue',
×
UNCOV
852
                'style',
×
UNCOV
853
                'explode',
×
UNCOV
854
                'allowReserved',
×
UNCOV
855
                'example',
×
UNCOV
856
            ] as $method
×
857
        ) {
UNCOV
858
            $newValue = $defined->{"get$method"}();
×
UNCOV
859
            if (null !== $newValue && $actual->{"get$method"}() !== $newValue) {
×
UNCOV
860
                $actual = $actual->{"with$method"}($newValue);
×
861
            }
862
        }
863

UNCOV
864
        foreach (['examples', 'content', 'schema'] as $method) {
×
UNCOV
865
            $newValue = $defined->{"get$method"}();
×
UNCOV
866
            if ($newValue && \count($newValue) > 0 && $actual->{"get$method"}() !== $newValue) {
×
867
                $actual = $actual->{"with$method"}($newValue);
×
868
            }
869
        }
870

UNCOV
871
        return $actual;
×
872
    }
873

874
    /**
875
     * @param ErrorResource[]              $errors
876
     * @param \ArrayObject<string, Schema> $schemas
877
     */
878
    private function addOperationErrors(
879
        Operation $operation,
880
        array $errors,
881
        ResourceMetadataCollection $resourceMetadataCollection,
882
        Schema $schema,
883
        \ArrayObject $schemas,
884
        HttpOperation $originalOperation,
885
    ): Operation {
UNCOV
886
        foreach ($errors as $errorResource) {
×
UNCOV
887
            $responseMimeTypes = $this->flattenMimeTypes($errorResource->getOutputFormats() ?: $this->errorFormats);
×
UNCOV
888
            foreach ($errorResource->getOperations() as $errorOperation) {
×
UNCOV
889
                if (false === $errorOperation->getOpenApi()) {
×
UNCOV
890
                    continue;
×
891
                }
892

893
                $responseMimeTypes += $this->flattenMimeTypes($errorOperation->getOutputFormats() ?: $this->errorFormats);
×
894
            }
895

UNCOV
896
            foreach ($responseMimeTypes as $mime => $format) {
×
UNCOV
897
                if (!isset($this->errorFormats[$format])) {
×
898
                    unset($responseMimeTypes[$mime]);
×
899
                }
900
            }
901

UNCOV
902
            $operationErrorSchemas = [];
×
UNCOV
903
            foreach ($responseMimeTypes as $operationFormat) {
×
UNCOV
904
                $operationErrorSchema = $this->jsonSchemaFactory->buildSchema($errorResource->getClass(), $operationFormat, Schema::TYPE_OUTPUT, null, $schema);
×
UNCOV
905
                $operationErrorSchemas[$operationFormat] = $operationErrorSchema;
×
UNCOV
906
                $this->appendSchemaDefinitions($schemas, $operationErrorSchema->getDefinitions());
×
907
            }
908

UNCOV
909
            if (!$status = $errorResource->getStatus()) {
×
910
                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()));
×
911
            }
912

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

UNCOV
916
        return $operation;
×
917
    }
918

919
    /**
920
     * @param string|class-string $error
921
     */
922
    private function getErrorResource(string $error, ?int $status = null, ?string $description = null): ErrorResource
923
    {
UNCOV
924
        if ($this->localErrorResourceCache[$error] ?? null) {
×
UNCOV
925
            return $this->localErrorResourceCache[$error];
×
926
        }
927

UNCOV
928
        if (is_a($error, ProblemExceptionInterface::class, true)) {
×
929
            try {
930
                /** @var ProblemExceptionInterface $exception */
UNCOV
931
                $exception = new $error();
×
UNCOV
932
                $status = $exception->getStatus();
×
UNCOV
933
                $description = $exception->getTitle();
×
UNCOV
934
            } catch (\TypeError) {
×
935
            }
936
        } elseif (class_exists($error)) {
×
937
            throw new RuntimeException(\sprintf('The error class "%s" does not implement "%s". Did you forget a use statement?', $error, ProblemExceptionInterface::class));
×
938
        }
939

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

942
        try {
UNCOV
943
            $errorResource = $this->resourceMetadataFactory->create($error)[0] ?? new ErrorResource(status: $status, description: $description, class: $defaultErrorResourceClass);
×
UNCOV
944
            if (!($errorResource instanceof ErrorResource)) {
×
945
                throw new RuntimeException(\sprintf('The error class %s is not an ErrorResource', $error));
×
946
            }
947

948
            // Here we want the exception status and expression to override the resource one when available
UNCOV
949
            if ($status) {
×
UNCOV
950
                $errorResource = $errorResource->withStatus($status);
×
951
            }
952

UNCOV
953
            if ($description) {
×
UNCOV
954
                $errorResource = $errorResource->withDescription($description);
×
955
            }
956
        } catch (ResourceClassNotFoundException|OperationNotFoundException) {
×
957
            $errorResource = new ErrorResource(status: $status, description: $description, class: $defaultErrorResourceClass);
×
958
        }
959

UNCOV
960
        if (!$errorResource->getClass()) {
×
961
            $errorResource = $errorResource->withClass($error);
×
962
        }
963

UNCOV
964
        return $this->localErrorResourceCache[$error] = $errorResource;
×
965
    }
966
}
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