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

api-platform / core / 9710836697

28 Jun 2024 09:35AM UTC coverage: 63.285% (+1.2%) from 62.122%
9710836697

push

github

soyuka
docs: changelog v3.3.7

11104 of 17546 relevant lines covered (63.29%)

52.26 hits per line

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

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

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

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

71
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
72
    {
73
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
56✔
74
        // Because ErrorFormatGuesser is buggy in some cases
75
        $request->setRequestFormat($format);
56✔
76
        $apiOperation = $this->initializeOperation($request);
56✔
77

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

83
        // Let the error handler take this we don't handle HTML nor non-api platform requests
84
        if ('html' === $format) {
56✔
85
            $this->controller = 'error_controller';
×
86

87
            return parent::duplicateRequest($exception, $request);
×
88
        }
89

90
        $legacy = $apiOperation ? ($apiOperation->getExtraProperties()['rfc_7807_compliant_errors'] ?? false) : $this->problemCompliantErrors;
56✔
91

92
        if (!$this->problemCompliantErrors || !$legacy) {
56✔
93
            // TODO: deprecate in API Platform 3.3
94
            $this->controller = 'api_platform.action.exception';
4✔
95
            $dup = parent::duplicateRequest($exception, $request);
4✔
96
            $dup->attributes->set('_api_operation', $apiOperation);
4✔
97
            $dup->attributes->set('_api_exception_action', true);
4✔
98

99
            return $dup;
4✔
100
        }
101

102
        if ($this->debug) {
52✔
103
            $this->logger?->error('An exception occured, transforming to an Error resource.', ['exception' => $exception, 'operation' => $apiOperation]);
52✔
104
        }
105

106
        $dup = parent::duplicateRequest($exception, $request);
52✔
107
        $operation = $this->initializeExceptionOperation($request, $exception, $format, $apiOperation);
52✔
108

109
        if (null === $operation->getProvider()) {
52✔
110
            $operation = $operation->withProvider('api_platform.state.error_provider');
×
111
        }
112

113
        $normalizationContext = $operation->getNormalizationContext() ?? [];
52✔
114
        if (!($normalizationContext['api_error_resource'] ?? false)) {
52✔
115
            $normalizationContext += ['api_error_resource' => true];
52✔
116
        }
117

118
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
52✔
119
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = ['trace', 'file', 'line', 'code', 'message', 'traceAsString'];
52✔
120
        }
121

122
        $operation = $operation->withNormalizationContext($normalizationContext);
52✔
123

124
        $dup->attributes->set('_api_resource_class', $operation->getClass());
52✔
125
        $dup->attributes->set('_api_previous_operation', $apiOperation);
52✔
126
        $dup->attributes->set('_api_operation', $operation);
52✔
127
        $dup->attributes->set('_api_operation_name', $operation->getName());
52✔
128
        $dup->attributes->set('exception', $exception);
52✔
129
        // These are for swagger
130
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
52✔
131
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
52✔
132
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
52✔
133
        $dup->attributes->set('_api_platform_disable_listeners', true);
52✔
134

135
        return $dup;
52✔
136
    }
137

138
    /**
139
     * @return array<int, array<class-string, int>>
140
     */
141
    private function getOperationExceptionToStatus(Request $request): array
142
    {
143
        $attributes = RequestAttributesExtractor::extractAttributes($request);
4✔
144

145
        if ([] === $attributes) {
4✔
146
            return [];
4✔
147
        }
148

149
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
150
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
151

152
        if (!$operation instanceof HttpOperation) {
×
153
            return [];
×
154
        }
155

156
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
157

158
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
159
            /* @var \ApiPlatform\Metadata\ApiResource; $resourceMetadata */
160
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
161
        }
162

163
        return array_merge(...$exceptionToStatus);
×
164
    }
165

166
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
167
    {
168
        $exceptionToStatus = array_merge(
52✔
169
            $this->exceptionToStatus,
52✔
170
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
52✔
171
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
52✔
172
        );
52✔
173

174
        foreach ($exceptionToStatus as $class => $status) {
52✔
175
            if (is_a($exception::class, $class, true)) {
52✔
176
                return $status;
×
177
            }
178
        }
179

180
        if ($exception instanceof SymfonyHttpExceptionInterface) {
52✔
181
            return $exception->getStatusCode();
52✔
182
        }
183

184
        if ($exception instanceof ProblemExceptionInterface && $status = $exception->getStatus()) {
×
185
            return $status;
×
186
        }
187

188
        if ($exception instanceof HttpExceptionInterface) {
×
189
            return $exception->getStatusCode();
×
190
        }
191

192
        if ($exception instanceof RequestExceptionInterface) {
×
193
            return 400;
×
194
        }
195

196
        if ($exception instanceof ConstraintViolationListAwareExceptionInterface || $exception instanceof LegacyConstraintViolationListAwareExceptionInterface) {
×
197
            return 422;
×
198
        }
199

200
        if ($status = $errorOperation?->getStatus()) {
×
201
            return $status;
×
202
        }
203

204
        return 500;
×
205
    }
206

207
    private function getFormatOperation(?string $format): string
208
    {
209
        return match ($format) {
8✔
210
            'json' => '_api_errors_problem',
8✔
211
            'jsonproblem' => '_api_errors_problem',
8✔
212
            'jsonld' => '_api_errors_hydra',
8✔
213
            'jsonapi' => '_api_errors_jsonapi',
8✔
214
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
8✔
215
            default => '_api_errors_problem'
8✔
216
        };
8✔
217
    }
218

219
    private function initializeExceptionOperation(?Request $request, \Throwable $exception, string $format, ?HttpOperation $apiOperation): Operation
220
    {
221
        if (!$this->resourceMetadataCollectionFactory) {
52✔
222
            $operation = new ErrorOperation(
×
223
                name: '_api_errors_problem',
×
224
                class: Error::class,
×
225
                outputFormats: ['jsonld' => ['application/problem+json']],
×
226
                normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]
×
227
            );
×
228

229
            return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
230
        }
231

232
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
52✔
233
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
44✔
234

235
            $operation = null;
44✔
236
            // TODO: move this to ResourceMetadataCollection?
237
            foreach ($resourceCollection as $resource) {
44✔
238
                foreach ($resource->getOperations() as $op) {
44✔
239
                    foreach ($op->getOutputFormats() as $key => $value) {
44✔
240
                        if ($key === $format) {
44✔
241
                            $operation = $op;
44✔
242
                            break 3;
44✔
243
                        }
244
                    }
245
                }
246
            }
247

248
            // No operation found for the requested format, we take the first available
249
            $operation ??= $resourceCollection->getOperation();
44✔
250

251
            if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
44✔
252
                return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
44✔
253
            }
254

255
            return $operation;
×
256
        }
257

258
        // Create a generic, rfc7807 compatible error according to the wanted format
259
        $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
8✔
260
        // status code may be overriden by the exceptionToStatus option
261
        $statusCode = 500;
8✔
262
        if ($operation instanceof HttpOperation) {
8✔
263
            $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
8✔
264
            $operation = $operation->withStatus($statusCode);
8✔
265
        }
266

267
        return $operation;
8✔
268
    }
269
}
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