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

api-platform / core / 14954769666

11 May 2025 10:14AM UTC coverage: 0.0% (-8.5%) from 8.457%
14954769666

Pull #7135

github

web-flow
Merge bf21e0bc7 into 4dd0cdfc4
Pull Request #7135: fix(symfony,laravel): InvalidUriVariableException status code (e400)

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

11040 existing lines in 370 files now uncovered.

0 of 48303 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/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\InvalidUriVariableException;
19
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
22
use ApiPlatform\Metadata\Operation;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
26
use ApiPlatform\State\ApiResource\Error;
27
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
28
use ApiPlatform\State\Util\RequestAttributesExtractor;
29
use ApiPlatform\Validator\Exception\ConstraintViolationListAwareExceptionInterface;
30
use Negotiation\Negotiator;
31
use Psr\Log\LoggerInterface;
32
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpKernel\EventListener\ErrorListener as SymfonyErrorListener;
35
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
36
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
37

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

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

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

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

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

UNCOV
84
            return parent::duplicateRequest($exception, $request);
×
85
        }
86

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

UNCOV
91
        $dup = parent::duplicateRequest($exception, $request);
×
UNCOV
92
        $operation = $this->initializeExceptionOperation($request, $exception, $format, $apiOperation);
×
93

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

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

UNCOV
103
        if (isset($normalizationContext['item_uri_template'])) {
×
104
            unset($normalizationContext['item_uri_template']);
×
105
        }
106

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

UNCOV
111
        $operation = $operation->withNormalizationContext($normalizationContext);
×
112

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

UNCOV
125
        return $dup;
×
126
    }
127

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

UNCOV
135
        if ([] === $attributes) {
×
UNCOV
136
            return [];
×
137
        }
138

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

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

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

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

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

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

UNCOV
164
        foreach ($exceptionToStatus as $class => $status) {
×
UNCOV
165
            if (is_a($exception::class, $class, true)) {
×
166
                return $status;
×
167
            }
168
        }
169

UNCOV
170
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
UNCOV
171
            return $exception->getStatusCode();
×
172
        }
173

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

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

NEW
182
        if ($exception instanceof RequestExceptionInterface || $exception instanceof InvalidUriVariableException) {
×
183
            return 400;
×
184
        }
185

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

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

194
        return 500;
×
195
    }
196

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

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

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

UNCOV
222
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
×
UNCOV
223
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
×
224

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

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

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

245
            return $operation;
×
246
        }
247

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

UNCOV
257
        return $operation;
×
258
    }
259
}
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