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

api-platform / core / 7196499749

13 Dec 2023 02:17PM UTC coverage: 37.359% (+1.4%) from 36.003%
7196499749

push

github

web-flow
ci: conflict sebastian/comparator (#6032)

* ci: conflict sebastian/comparator

* for lowest

10295 of 27557 relevant lines covered (37.36%)

28.14 hits per line

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

78.35
/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\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\Symfony\Util\RequestAttributesExtractor;
29
use ApiPlatform\Validator\Exception\ValidationException;
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 null|IdentifiersExtractorInterface|LegacyIdentifiersExtractorInterface $identifiersExtractor = null,
60
        private readonly null|ResourceClassResolverInterface|LegacyResourceClassResolverInterface $resourceClassResolver = null,
61
        Negotiator $negotiator = null,
62
        private readonly bool $problemCompliantErrors = true,
63
    ) {
64
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
120✔
65
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
120✔
66
        $this->negotiator = $negotiator ?? new Negotiator();
120✔
67
    }
68

69
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
70
    {
71
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
20✔
72
        // Because ErrorFormatGuesser is buggy in some cases
73
        $request->setRequestFormat($format);
20✔
74
        $apiOperation = $this->initializeOperation($request);
20✔
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 ('html' === $format) {
20✔
83
            $this->controller = 'error_controller';
×
84

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

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

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

97
            return $dup;
8✔
98
        }
99

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

104
        $dup = parent::duplicateRequest($exception, $request);
12✔
105
        if ($this->resourceMetadataCollectionFactory) {
12✔
106
            if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
12✔
107
                $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
4✔
108

109
                $operation = null;
4✔
110
                foreach ($resourceCollection as $resource) {
4✔
111
                    foreach ($resource->getOperations() as $op) {
4✔
112
                        foreach ($op->getOutputFormats() as $key => $value) {
4✔
113
                            if ($key === $format) {
4✔
114
                                $operation = $op;
4✔
115
                                break 3;
4✔
116
                            }
117
                        }
118
                    }
119
                }
120

121
                // No operation found for the requested format, we take the first available
122
                if (!$operation) {
4✔
123
                    $operation = $resourceCollection->getOperation();
×
124
                }
125
                if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
4✔
126
                    $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
4✔
127
                    $operation = $operation->withStatus($statusCode);
4✔
128
                }
129
            } else {
130
                // Create a generic, rfc7807 compatible error according to the wanted format
131
                $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
8✔
132
                // status code may be overriden by the exceptionToStatus option
133
                $statusCode = 500;
8✔
134
                if ($operation instanceof HttpOperation) {
8✔
135
                    $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
8✔
136
                    $operation = $operation->withStatus($statusCode);
9✔
137
                }
138
            }
139
        } else {
140
            /** @var HttpOperation $operation */
141
            $operation = new ErrorOperation(name: '_api_errors_problem', class: Error::class, outputFormats: ['jsonld' => ['application/problem+json']], normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]);
×
142
            $operation = $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
143
        }
144

145
        if (null === $operation->getProvider()) {
12✔
146
            $operation = $operation->withProvider('api_platform.state.error_provider');
12✔
147
        }
148

149
        $normalizationContext = $operation->getNormalizationContext() ?? [];
12✔
150
        if (!($normalizationContext['_api_error_resource'] ?? false)) {
12✔
151
            $normalizationContext += ['api_error_resource' => true];
12✔
152
        }
153

154
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
12✔
155
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = ['trace', 'file', 'line', 'code', 'message', 'traceAsString'];
12✔
156
        }
157

158
        $operation = $operation->withNormalizationContext($normalizationContext);
12✔
159

160
        $dup->attributes->set('_api_resource_class', $operation->getClass());
12✔
161
        $dup->attributes->set('_api_previous_operation', $apiOperation);
12✔
162
        $dup->attributes->set('_api_operation', $operation);
12✔
163
        $dup->attributes->set('_api_operation_name', $operation->getName());
12✔
164
        $dup->attributes->set('exception', $exception);
12✔
165
        // These are for swagger
166
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
12✔
167
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
12✔
168
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
12✔
169
        $dup->attributes->set('_api_platform_disable_listeners', true);
12✔
170

171
        return $dup;
12✔
172
    }
173

174
    private function getOperationExceptionToStatus(Request $request): array
175
    {
176
        $attributes = RequestAttributesExtractor::extractAttributes($request);
×
177

178
        if ([] === $attributes) {
×
179
            return [];
×
180
        }
181

182
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
183
        /** @var HttpOperation $operation */
184
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
185
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
186

187
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
188
            /* @var \ApiPlatform\Metadata\ApiResource; $resourceMetadata */
189
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
190
        }
191

192
        return array_merge(...$exceptionToStatus);
×
193
    }
194

195
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
196
    {
197
        $exceptionToStatus = array_merge(
12✔
198
            $this->exceptionToStatus,
12✔
199
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
12✔
200
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
12✔
201
        );
12✔
202

203
        foreach ($exceptionToStatus as $class => $status) {
12✔
204
            if (is_a($exception::class, $class, true)) {
×
205
                return $status;
×
206
            }
207
        }
208

209
        if ($exception instanceof SymfonyHttpExceptionInterface) {
12✔
210
            return $exception->getStatusCode();
×
211
        }
212

213
        if ($exception instanceof ProblemExceptionInterface && $status = $exception->getStatus()) {
12✔
214
            return $status;
4✔
215
        }
216

217
        if ($exception instanceof HttpExceptionInterface) {
8✔
218
            return $exception->getStatusCode();
×
219
        }
220

221
        if ($exception instanceof RequestExceptionInterface) {
8✔
222
            return 400;
×
223
        }
224

225
        if ($exception instanceof ValidationException) {
8✔
226
            return 422;
×
227
        }
228

229
        if ($status = $errorOperation?->getStatus()) {
8✔
230
            return $status;
8✔
231
        }
232

233
        return 500;
×
234
    }
235

236
    private function getFormatOperation(?string $format): string
237
    {
238
        return match ($format) {
8✔
239
            'json' => '_api_errors_problem',
8✔
240
            'jsonproblem' => '_api_errors_problem',
8✔
241
            'jsonld' => '_api_errors_hydra',
8✔
242
            'jsonapi' => '_api_errors_jsonapi',
8✔
243
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
8✔
244
            default => '_api_errors_problem'
8✔
245
        };
8✔
246
    }
247
}
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

© 2026 Coveralls, Inc