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

api-platform / core / 10537652610

24 Aug 2024 10:04AM UTC coverage: 7.707%. Remained the same
10537652610

push

github

dunglas
cleanup

12490 of 162060 relevant lines covered (7.71%)

22.98 hits per line

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

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

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

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

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

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

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

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

102
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
292✔
103
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = ['trace', 'file', 'line', 'code', 'message', 'traceAsString'];
292✔
104
        }
105

106
        $operation = $operation->withNormalizationContext($normalizationContext);
292✔
107

108
        $dup->attributes->set('_api_resource_class', $operation->getClass());
292✔
109
        $dup->attributes->set('_api_previous_operation', $apiOperation);
292✔
110
        $dup->attributes->set('_api_operation', $operation);
292✔
111
        $dup->attributes->set('_api_operation_name', $operation->getName());
292✔
112
        $dup->attributes->set('exception', $exception);
292✔
113
        // These are for swagger
114
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
292✔
115
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
292✔
116
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
292✔
117
        $dup->attributes->set('_api_platform_disable_listeners', true);
292✔
118

119
        return $dup;
292✔
120
    }
121

122
    /**
123
     * @return array<int, array<class-string, int>>
124
     */
125
    private function getOperationExceptionToStatus(Request $request): array
126
    {
127
        $attributes = RequestAttributesExtractor::extractAttributes($request);
12✔
128

129
        if ([] === $attributes) {
12✔
130
            return [];
12✔
131
        }
132

133
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
134
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
135

136
        if (!$operation instanceof HttpOperation) {
×
137
            return [];
×
138
        }
139

140
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
141

142
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
143
            /* @var \ApiPlatform\Metadata\ApiResource; $resourceMetadata */
144
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
145
        }
146

147
        return array_merge(...$exceptionToStatus);
×
148
    }
149

150
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
151
    {
152
        $exceptionToStatus = array_merge(
292✔
153
            $this->exceptionToStatus,
292✔
154
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
292✔
155
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
292✔
156
        );
292✔
157

158
        foreach ($exceptionToStatus as $class => $status) {
292✔
159
            if (is_a($exception::class, $class, true)) {
292✔
160
                return $status;
72✔
161
            }
162
        }
163

164
        if ($exception instanceof SymfonyHttpExceptionInterface) {
220✔
165
            return $exception->getStatusCode();
207✔
166
        }
167

168
        if ($exception instanceof ProblemExceptionInterface && $status = $exception->getStatus()) {
13✔
169
            return $status;
×
170
        }
171

172
        if ($exception instanceof HttpExceptionInterface) {
13✔
173
            return $exception->getStatusCode();
×
174
        }
175

176
        if ($exception instanceof RequestExceptionInterface) {
13✔
177
            return 400;
×
178
        }
179

180
        if ($exception instanceof ConstraintViolationListAwareExceptionInterface) {
13✔
181
            return 422;
×
182
        }
183

184
        if ($status = $errorOperation?->getStatus()) {
13✔
185
            return $status;
×
186
        }
187

188
        return 500;
13✔
189
    }
190

191
    private function getFormatOperation(?string $format): string
192
    {
193
        return match ($format) {
202✔
194
            'json' => '_api_errors_problem',
13✔
195
            'jsonproblem' => '_api_errors_problem',
26✔
196
            'jsonld' => '_api_errors_hydra',
152✔
197
            'jsonapi' => '_api_errors_jsonapi',
11✔
198
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
199
            default => '_api_errors_problem'
202✔
200
        };
202✔
201
    }
202

203
    private function initializeExceptionOperation(?Request $request, \Throwable $exception, string $format, ?HttpOperation $apiOperation): Operation
204
    {
205
        if (!$this->resourceMetadataCollectionFactory) {
292✔
206
            $operation = new ErrorOperation(
×
207
                name: '_api_errors_problem',
×
208
                class: Error::class,
×
209
                outputFormats: ['jsonld' => ['application/problem+json']],
×
210
                normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]
×
211
            );
×
212

213
            return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
214
        }
215

216
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
292✔
217
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
90✔
218

219
            $operation = null;
90✔
220
            // TODO: move this to ResourceMetadataCollection?
221
            foreach ($resourceCollection as $resource) {
90✔
222
                foreach ($resource->getOperations() as $op) {
90✔
223
                    foreach ($op->getOutputFormats() as $key => $value) {
90✔
224
                        if ($key === $format) {
90✔
225
                            $operation = $op;
90✔
226
                            break 3;
90✔
227
                        }
228
                    }
229
                }
230
            }
231

232
            // No operation found for the requested format, we take the first available
233
            $operation ??= $resourceCollection->getOperation();
90✔
234

235
            if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
90✔
236
                return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
90✔
237
            }
238

239
            return $operation;
×
240
        }
241

242
        // Create a generic, rfc7807 compatible error according to the wanted format
243
        $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
202✔
244
        // status code may be overridden by the exceptionToStatus option
245
        $statusCode = 500;
202✔
246
        if ($operation instanceof HttpOperation) {
202✔
247
            $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
202✔
248
            $operation = $operation->withStatus($statusCode);
202✔
249
        }
250

251
        return $operation;
202✔
252
    }
253
}
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