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

api-platform / core / 13724522058

07 Mar 2025 04:04PM UTC coverage: 8.175% (-0.3%) from 8.518%
13724522058

Pull #7005

github

web-flow
Merge 322407532 into 1e0bc9dc8
Pull Request #7005: fix(validation): deprecate string message for ValidationException con…

4 of 6 new or added lines in 1 file covered. (66.67%)

159 existing lines in 24 files now uncovered.

12839 of 157045 relevant lines covered (8.18%)

13.55 hits per line

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

78.22
/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);
1,139✔
63
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
1,139✔
64
        $this->negotiator = $negotiator ?? new Negotiator();
1,139✔
65
    }
66

67
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
68
    {
69
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
114✔
70
        // Because ErrorFormatGuesser is buggy in some cases
71
        $request->setRequestFormat($format);
114✔
72
        $apiOperation = $this->initializeOperation($request);
114✔
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) {
114✔
81
            $this->controller = 'error_controller';
3✔
82

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

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

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

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

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

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

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

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

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

124
        return $dup;
111✔
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);
4✔
133

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

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

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

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

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

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

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

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

193
        return 500;
2✔
194
    }
195

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

208
    private function initializeExceptionOperation(?Request $request, \Throwable $exception, string $format, ?HttpOperation $apiOperation): Operation
209
    {
210
        if (!$this->resourceMetadataCollectionFactory) {
111✔
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)) {
111✔
222
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
42✔
223

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

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

240
            if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
42✔
241
                return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
42✔
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));
69✔
249
        // status code may be overridden by the exceptionToStatus option
250
        $statusCode = 500;
69✔
251
        if ($operation instanceof HttpOperation) {
69✔
252
            $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
69✔
253
            $operation = $operation->withStatus($statusCode);
69✔
254
        }
255

256
        return $operation;
69✔
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