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

api-platform / core / 9937329719

15 Jul 2024 09:54AM UTC coverage: 64.188% (-0.05%) from 64.239%
9937329719

push

github

soyuka
Merge 3.4

8 of 18 new or added lines in 5 files covered. (44.44%)

7 existing lines in 3 files now uncovered.

11326 of 17645 relevant lines covered (64.19%)

68.35 hits per line

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

67.62
/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\Symfony\Validator\Exception\ConstraintViolationListAwareExceptionInterface as LegacyConstraintViolationListAwareExceptionInterface;
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
        private readonly bool $problemCompliantErrors = true,
63
    ) {
64
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
459✔
65
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
459✔
66
        $this->negotiator = $negotiator ?? new Negotiator();
459✔
67
    }
68

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

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

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

85
            return parent::duplicateRequest($exception, $request);
4✔
86
        }
87

88
        $legacy = $apiOperation ? ($apiOperation->getExtraProperties()['rfc_7807_compliant_errors'] ?? false) : $this->problemCompliantErrors;
64✔
89

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

UNCOV
97
            return $dup;
×
98
        }
99

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

104
        $dup = parent::duplicateRequest($exception, $request);
64✔
105
        $operation = $this->initializeExceptionOperation($request, $exception, $format, $apiOperation);
64✔
106

107
        if (null === $operation->getProvider()) {
64✔
108
            $operation = $operation->withProvider('api_platform.state.error_provider');
×
109
        }
110

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

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

120
        $operation = $operation->withNormalizationContext($normalizationContext);
64✔
121

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

133
        return $dup;
64✔
134
    }
135

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

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

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

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

154
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
155

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

161
        return array_merge(...$exceptionToStatus);
×
162
    }
163

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

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

178
        if ($exception instanceof SymfonyHttpExceptionInterface) {
64✔
179
            return $exception->getStatusCode();
64✔
180
        }
181

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

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

190
        if ($exception instanceof RequestExceptionInterface) {
×
191
            return 400;
×
192
        }
193

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

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

202
        return 500;
×
203
    }
204

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

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

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

230
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
64✔
231
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
44✔
232

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

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

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

253
            return $operation;
×
254
        }
255

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

265
        return $operation;
20✔
266
    }
267
}
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