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

api-platform / core / 14910337627

08 May 2025 03:36PM UTC coverage: 6.873% (-1.6%) from 8.457%
14910337627

Pull #7135

github

web-flow
Merge b0ee9f38d into 613bb5b75
Pull Request #7135: fix(error_status_code): InvalidUriVariableException status code (e400)

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

34 existing lines in 1 file now uncovered.

10887 of 158407 relevant lines covered (6.87%)

6.19 hits per line

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

70.3
/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
    ) {
63
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
448✔
64
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
448✔
65
        $this->negotiator = $negotiator ?? new Negotiator();
448✔
66
    }
67

68
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
69
    {
70
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
46✔
71
        // Because ErrorFormatGuesser is buggy in some cases
72
        $request->setRequestFormat($format);
46✔
73
        $apiOperation = $this->initializeOperation($request);
46✔
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
81
        if (false === ($apiOperation?->getExtraProperties()['_api_error_handler'] ?? true) || 'html' === $format) {
46✔
82
            $this->controller = 'error_controller';
2✔
83

84
            return parent::duplicateRequest($exception, $request);
2✔
85
        }
86

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

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

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

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

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

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

111
        $operation = $operation->withNormalizationContext($normalizationContext);
44✔
112

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

125
        return $dup;
44✔
126
    }
127

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

135
        if ([] === $attributes) {
2✔
136
            return [];
2✔
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
    {
158
        $exceptionToStatus = array_merge(
44✔
159
            $this->exceptionToStatus,
44✔
160
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
44✔
161
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
44✔
162
        );
44✔
163

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

170
        if ($exception instanceof SymfonyHttpExceptionInterface) {
44✔
171
            return $exception->getStatusCode();
40✔
172
        }
173

174
        if ($exception instanceof ProblemExceptionInterface && $status = $exception->getStatus()) {
4✔
175
            return $status;
4✔
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
    {
199
        return match ($format) {
14✔
200
            'json' => '_api_errors_problem',
2✔
201
            'jsonproblem' => '_api_errors_problem',
×
202
            'jsonld' => '_api_errors_hydra',
12✔
203
            'jsonapi' => '_api_errors_jsonapi',
×
204
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
205
            default => '_api_errors_problem',
14✔
206
        };
14✔
207
    }
208

209
    private function initializeExceptionOperation(?Request $request, \Throwable $exception, string $format, ?HttpOperation $apiOperation): Operation
210
    {
211
        if (!$this->resourceMetadataCollectionFactory) {
44✔
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

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

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

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

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

245
            return $operation;
×
246
        }
247

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

257
        return $operation;
14✔
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