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

api-platform / core / 15040977736

15 May 2025 09:02AM UTC coverage: 21.754% (+13.3%) from 8.423%
15040977736

Pull #6960

github

web-flow
Merge 7a7a13526 into 1862d03b7
Pull Request #6960: feat(json-schema): mutualize json schema between formats

320 of 460 new or added lines in 24 files covered. (69.57%)

1863 existing lines in 109 files now uncovered.

11069 of 50882 relevant lines covered (21.75%)

29.49 hits per line

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

69.31
/src/Symfony/EventListener/ErrorListener.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\Symfony\EventListener;
15

16
use ApiPlatform\Metadata\Error as ErrorOperation;
17
use ApiPlatform\Metadata\Exception\HttpExceptionInterface;
18
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
19
use ApiPlatform\Metadata\HttpOperation;
20
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
21
use ApiPlatform\Metadata\Operation;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceClassResolverInterface;
24
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
25
use ApiPlatform\State\ApiResource\Error;
26
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
27
use ApiPlatform\State\Util\RequestAttributesExtractor;
28
use ApiPlatform\Validator\Exception\ConstraintViolationListAwareExceptionInterface;
29
use Negotiation\Negotiator;
30
use Psr\Log\LoggerInterface;
31
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
32
use Symfony\Component\HttpFoundation\Request;
33
use Symfony\Component\HttpKernel\EventListener\ErrorListener as SymfonyErrorListener;
34
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
35
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
36

37
/**
38
 * This error listener extends the Symfony one in order to add
39
 * the `_api_operation` attribute when the request is duplicated.
40
 * It will later be used to retrieve the exceptionToStatus from the operation ({@see ApiPlatform\Action\ExceptionAction}).
41
 *
42
 * @internal since API Platform 3.2
43
 */
44
final class ErrorListener extends SymfonyErrorListener
45
{
46
    use ContentNegotiationTrait;
47
    use OperationRequestInitiatorTrait;
48

49
    public function __construct(
50
        object|array|string|null $controller,
51
        ?LoggerInterface $logger = null,
52
        bool $debug = false,
53
        array $exceptionsMapping = [],
54
        ?ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null,
55
        private readonly array $errorFormats = [],
56
        private readonly array $exceptionToStatus = [],
57
        /** @phpstan-ignore-next-line we're not using this anymore but keeping for bc layer */
58
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
59
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
60
        ?Negotiator $negotiator = null,
61
    ) {
62
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
856✔
63
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
856✔
64
        $this->negotiator = $negotiator ?? new Negotiator();
856✔
65
    }
66

67
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
68
    {
69
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
97✔
70
        // Because ErrorFormatGuesser is buggy in some cases
71
        $request->setRequestFormat($format);
97✔
72
        $apiOperation = $this->initializeOperation($request);
97✔
73

74
        // TODO: add configuration flag to:
75
        //   - always use symfony error handler (skips this listener)
76
        //   - use symfony error handler if it's not an api error, ie apiOperation is null
77
        //   - use api platform to handle errors (the default behavior we handle firewall errors for example but they're out of our scope)
78

79
        // Let the error handler take this we don't handle HTML nor non-api platform requests
80
        if (false === ($apiOperation?->getExtraProperties()['_api_error_handler'] ?? true) || 'html' === $format) {
97✔
81
            $this->controller = 'error_controller';
1✔
82

83
            return parent::duplicateRequest($exception, $request);
1✔
84
        }
85

86
        if ($this->debug) {
96✔
87
            $this->logger?->error('An exception occured, transforming to an Error resource.', ['exception' => $exception, 'operation' => $apiOperation]);
96✔
88
        }
89

90
        $dup = parent::duplicateRequest($exception, $request);
96✔
91
        $operation = $this->initializeExceptionOperation($request, $exception, $format, $apiOperation);
96✔
92

93
        if (null === $operation->getProvider()) {
96✔
UNCOV
94
            $operation = $operation->withProvider('api_platform.state.error_provider');
×
95
        }
96

97
        $normalizationContext = $operation->getNormalizationContext() ?? [];
96✔
98
        if (!($normalizationContext['api_error_resource'] ?? false)) {
96✔
99
            $normalizationContext += ['api_error_resource' => true];
96✔
100
        }
101

102
        if (isset($normalizationContext['item_uri_template'])) {
96✔
103
            unset($normalizationContext['item_uri_template']);
×
104
        }
105

106
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
96✔
UNCOV
107
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = ['trace', 'file', 'line', 'code', 'message', 'traceAsString'];
×
108
        }
109

110
        $operation = $operation->withNormalizationContext($normalizationContext);
96✔
111

112
        $dup->attributes->set('_api_resource_class', $operation->getClass());
96✔
113
        $dup->attributes->set('_api_previous_operation', $apiOperation);
96✔
114
        $dup->attributes->set('_api_operation', $operation);
96✔
115
        $dup->attributes->set('_api_operation_name', $operation->getName());
96✔
116
        $dup->attributes->set('exception', $exception);
96✔
117
        // These are for swagger
118
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
96✔
119
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
96✔
120
        $dup->attributes->set('_api_original_uri_variables', $request->attributes->get('_api_uri_variables'));
96✔
121
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
96✔
122
        $dup->attributes->set('_api_platform_disable_listeners', true);
96✔
123

124
        return $dup;
96✔
125
    }
126

127
    /**
128
     * @return array<int, array<class-string, int>>
129
     */
130
    private function getOperationExceptionToStatus(Request $request): array
131
    {
132
        $attributes = RequestAttributesExtractor::extractAttributes($request);
5✔
133

134
        if ([] === $attributes) {
5✔
135
            return [];
5✔
136
        }
137

138
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
139
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
140

141
        if (!$operation instanceof HttpOperation) {
×
142
            return [];
×
143
        }
144

145
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
146

147
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
148
            /* @var \ApiPlatform\Metadata\ApiResource; $resourceMetadata */
149
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
150
        }
151

152
        return array_merge(...$exceptionToStatus);
×
153
    }
154

155
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
156
    {
157
        $exceptionToStatus = array_merge(
96✔
158
            $this->exceptionToStatus,
96✔
159
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
96✔
160
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
96✔
161
        );
96✔
162

163
        foreach ($exceptionToStatus as $class => $status) {
96✔
164
            if (is_a($exception::class, $class, true)) {
96✔
165
                return $status;
29✔
166
            }
167
        }
168

169
        if ($exception instanceof SymfonyHttpExceptionInterface) {
67✔
170
            return $exception->getStatusCode();
67✔
171
        }
172

UNCOV
173
        if ($exception instanceof ProblemExceptionInterface && $status = $exception->getStatus()) {
×
UNCOV
174
            return $status;
×
175
        }
176

177
        if ($exception instanceof HttpExceptionInterface) {
×
178
            return $exception->getStatusCode();
×
179
        }
180

181
        if ($exception instanceof RequestExceptionInterface) {
×
182
            return 400;
×
183
        }
184

185
        if ($exception instanceof ConstraintViolationListAwareExceptionInterface) {
×
186
            return 422;
×
187
        }
188

189
        if ($status = $errorOperation?->getStatus()) {
×
190
            return $status;
×
191
        }
192

193
        return 500;
×
194
    }
195

196
    private function getFormatOperation(?string $format): string
197
    {
198
        return match ($format) {
72✔
199
            'json' => '_api_errors_problem',
4✔
200
            'jsonproblem' => '_api_errors_problem',
9✔
201
            'jsonld' => '_api_errors_hydra',
55✔
202
            'jsonapi' => '_api_errors_jsonapi',
4✔
203
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
204
            default => '_api_errors_problem',
72✔
205
        };
72✔
206
    }
207

208
    private function initializeExceptionOperation(?Request $request, \Throwable $exception, string $format, ?HttpOperation $apiOperation): Operation
209
    {
210
        if (!$this->resourceMetadataCollectionFactory) {
96✔
211
            $operation = new ErrorOperation(
×
212
                name: '_api_errors_problem',
×
213
                class: Error::class,
×
214
                outputFormats: ['jsonld' => ['application/problem+json']],
×
215
                normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]
×
216
            );
×
217

218
            return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
219
        }
220

221
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
96✔
222
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
24✔
223

224
            $operation = null;
24✔
225
            // TODO: move this to ResourceMetadataCollection?
226
            foreach ($resourceCollection as $resource) {
24✔
227
                foreach ($resource->getOperations() as $op) {
24✔
228
                    foreach ($op->getOutputFormats() as $key => $value) {
24✔
229
                        if ($key === $format) {
24✔
230
                            $operation = $op;
24✔
231
                            break 3;
24✔
232
                        }
233
                    }
234
                }
235
            }
236

237
            // No operation found for the requested format, we take the first available
238
            $operation ??= $resourceCollection->getOperation();
24✔
239

240
            if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
24✔
241
                return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
24✔
242
            }
243

244
            return $operation;
×
245
        }
246

247
        // Create a generic, rfc7807 compatible error according to the wanted format
248
        $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
72✔
249
        // status code may be overridden by the exceptionToStatus option
250
        $statusCode = 500;
72✔
251
        if ($operation instanceof HttpOperation) {
72✔
252
            $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
72✔
253
            $operation = $operation->withStatus($statusCode);
72✔
254
        }
255

256
        return $operation;
72✔
257
    }
258
}
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