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

api-platform / core / 14992745685

13 May 2025 09:09AM UTC coverage: 27.459% (+3.8%) from 23.685%
14992745685

push

github

web-flow
fix(metadata): xml PHPize HTTP cache headers (#7140)

0 of 1 new or added line in 1 file covered. (0.0%)

2013 existing lines in 145 files now uncovered.

13449 of 48979 relevant lines covered (27.46%)

74.47 hits per line

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

79.21
/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\InvalidUriVariableException;
19
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
22
use ApiPlatform\Metadata\Operation;
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\State\Util\RequestAttributesExtractor;
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
    ) {
63
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
2,022✔
64
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
2,022✔
65
        $this->negotiator = $negotiator ?? new Negotiator();
2,022✔
66
    }
67

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

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

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

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

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

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

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

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

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

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

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

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

125
        return $dup;
216✔
126
    }
127

128
    /**
129
     * @return array<int, array<class-string, int>>
130
     */
131
    private function getOperationExceptionToStatus(Request $request): array
132
    {
133
        $attributes = RequestAttributesExtractor::extractAttributes($request);
9✔
134

135
        if ([] === $attributes) {
9✔
136
            return [];
9✔
137
        }
138

139
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
140
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
141

142
        if (!$operation instanceof HttpOperation) {
×
143
            return [];
×
144
        }
145

146
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
147

148
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
149
            /* @var \ApiPlatform\Metadata\ApiResource; $resourceMetadata */
150
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
151
        }
152

153
        return array_merge(...$exceptionToStatus);
×
154
    }
155

156
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
157
    {
158
        $exceptionToStatus = array_merge(
216✔
159
            $this->exceptionToStatus,
216✔
160
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
216✔
161
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
216✔
162
        );
216✔
163

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

170
        if ($exception instanceof SymfonyHttpExceptionInterface) {
164✔
171
            return $exception->getStatusCode();
156✔
172
        }
173

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

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

182
        if ($exception instanceof RequestExceptionInterface || $exception instanceof InvalidUriVariableException) {
4✔
183
            return 400;
2✔
184
        }
185

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

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

UNCOV
194
        return 500;
2✔
195
    }
196

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

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

219
            return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
220
        }
221

222
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
216✔
223
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
71✔
224

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

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

241
            if ($exception instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
71✔
242
                return $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
71✔
243
            }
244

245
            return $operation;
×
246
        }
247

248
        // Create a generic, rfc7807 compatible error according to the wanted format
249
        $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
145✔
250
        // status code may be overridden by the exceptionToStatus option
251
        $statusCode = 500;
145✔
252
        if ($operation instanceof HttpOperation) {
145✔
253
            $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
145✔
254
            $operation = $operation->withStatus($statusCode);
145✔
255
        }
256

257
        return $operation;
145✔
258
    }
259
}
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