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

api-platform / core / 6198903018

15 Sep 2023 01:50PM UTC coverage: 37.037% (+0.04%) from 36.999%
6198903018

push

github

web-flow
fix: exception to status on error resource (#5823)

52 of 52 new or added lines in 12 files covered. (100.0%)

10121 of 27327 relevant lines covered (37.04%)

19.98 hits per line

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

74.44
/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;
17
use ApiPlatform\ApiResource\Error;
18
use ApiPlatform\Metadata\Error as ErrorOperation;
19
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
22
use ApiPlatform\Metadata\ResourceClassResolverInterface;
23
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
24
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
25
use ApiPlatform\Symfony\Util\RequestAttributesExtractor;
26
use ApiPlatform\Symfony\Validator\Exception\ConstraintViolationListAwareExceptionInterface;
27
use ApiPlatform\Validator\Exception\ValidationException;
28
use Negotiation\Negotiator;
29
use Psr\Log\LoggerInterface;
30
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
31
use Symfony\Component\HttpFoundation\Request;
32
use Symfony\Component\HttpKernel\EventListener\ErrorListener as SymfonyErrorListener;
33
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
34

35
/**
36
 * This error listener extends the Symfony one in order to add
37
 * the `_api_operation` attribute when the request is duplicated.
38
 * It will later be used to retrieve the exceptionToStatus from the operation ({@see ApiPlatform\Action\ExceptionAction}).
39
 */
40
final class ErrorListener extends SymfonyErrorListener
41
{
42
    use ContentNegotiationTrait;
43
    use OperationRequestInitiatorTrait;
44

45
    public function __construct(
46
        object|array|string|null $controller,
47
        LoggerInterface $logger = null,
48
        bool $debug = false,
49
        array $exceptionsMapping = [],
50
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory = null,
51
        private readonly array $errorFormats = [],
52
        private readonly array $exceptionToStatus = [],
53
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
54
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
55
        Negotiator $negotiator = null
56
    ) {
57
        parent::__construct($controller, $logger, $debug, $exceptionsMapping);
81✔
58
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
81✔
59
        $this->negotiator = $negotiator ?? new Negotiator();
81✔
60
    }
61

62
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
63
    {
64
        $dup = parent::duplicateRequest($exception, $request);
9✔
65
        $apiOperation = $this->initializeOperation($request);
9✔
66
        $format = $this->getRequestFormat($request, $this->errorFormats, false);
9✔
67

68
        if ($this->resourceMetadataCollectionFactory) {
9✔
69
            if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
9✔
70
                $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
3✔
71

72
                $operation = null;
3✔
73
                foreach ($resourceCollection as $resource) {
3✔
74
                    foreach ($resource->getOperations() as $op) {
3✔
75
                        foreach ($op->getOutputFormats() as $key => $value) {
3✔
76
                            if ($key === $format) {
3✔
77
                                $operation = $op;
3✔
78
                                break 3;
3✔
79
                            }
80
                        }
81
                    }
82
                }
83

84
                // No operation found for the requested format, we take the first available
85
                if (!$operation) {
3✔
86
                    $operation = $resourceCollection->getOperation();
×
87
                }
88
                $errorResource = $exception;
3✔
89
                if ($errorResource instanceof ProblemExceptionInterface && $operation instanceof HttpOperation) {
3✔
90
                    $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
3✔
91
                    $operation = $operation->withStatus($statusCode);
3✔
92
                    $errorResource->setStatus($statusCode);
3✔
93
                }
94
            } else {
95
                // Create a generic, rfc7807 compatible error according to the wanted format
96
                $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format));
6✔
97
                // status code may be overriden by the exceptionToStatus option
98
                $statusCode = 500;
6✔
99
                if ($operation instanceof HttpOperation) {
6✔
100
                    $statusCode = $this->getStatusCode($apiOperation, $request, $operation, $exception);
6✔
101
                    $operation = $operation->withStatus($statusCode);
6✔
102
                }
103

104
                $errorResource = Error::createFromException($exception, $statusCode);
7✔
105
            }
106
        } else {
107
            /** @var HttpOperation $operation */
108
            $operation = new ErrorOperation(name: '_api_errors_problem', class: Error::class, outputFormats: ['jsonld' => ['application/ld+json']], normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]);
×
109
            $operation = $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
110
            $errorResource = Error::createFromException($exception, $operation->getStatus());
×
111
        }
112

113
        if (!$operation->getProvider()) {
9✔
114
            $operation = $operation->withProvider(provider: fn () => 'jsonapi' === $format && $errorResource instanceof ConstraintViolationListAwareExceptionInterface ? $errorResource->getConstraintViolationList() : $errorResource);
9✔
115
        }
116

117
        // For our swagger Ui errors
118
        if ('html' === $format) {
9✔
119
            $operation = $operation->withOutputFormats(['html' => ['text/html']]);
×
120
        }
121

122
        $identifiers = [];
9✔
123
        try {
124
            $identifiers = $this->identifiersExtractor?->getIdentifiersFromItem($errorResource, $operation) ?? [];
9✔
125
        } catch (\Exception $e) {
×
126
        }
127

128
        if ($exception instanceof ValidationException) {
9✔
129
            if (!($apiOperation?->getExtraProperties()['rfc_7807_compliant_errors'] ?? false)) {
×
130
                $operation = $operation->withNormalizationContext([
×
131
                    'groups' => ['legacy_'.$format],
×
132
                    'force_iri_generation' => false,
×
133
                ]);
×
134
            }
135
        }
136

137
        $dup->attributes->set('_api_resource_class', $operation->getClass());
9✔
138
        $dup->attributes->set('_api_previous_operation', $apiOperation);
9✔
139
        $dup->attributes->set('_api_operation', $operation);
9✔
140
        $dup->attributes->set('_api_operation_name', $operation->getName());
9✔
141
        $dup->attributes->remove('exception');
9✔
142
        // These are for swagger
143
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
9✔
144
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
9✔
145
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
9✔
146

147
        foreach ($identifiers as $name => $value) {
9✔
148
            $dup->attributes->set($name, $value);
3✔
149
        }
150

151
        return $dup;
9✔
152
    }
153

154
    private function getOperationExceptionToStatus(Request $request): array
155
    {
156
        $attributes = RequestAttributesExtractor::extractAttributes($request);
9✔
157

158
        if ([] === $attributes) {
9✔
159
            return [];
9✔
160
        }
161

162
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
163
        /** @var HttpOperation $operation */
164
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
165
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
166

167
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
168
            /* @var ApiResource $resourceMetadata */
169
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
170
        }
171

172
        return array_merge(...$exceptionToStatus);
×
173
    }
174

175
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
176
    {
177
        $exceptionToStatus = array_merge(
9✔
178
            $this->exceptionToStatus,
9✔
179
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
9✔
180
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
9✔
181
        );
9✔
182

183
        foreach ($exceptionToStatus as $class => $status) {
9✔
184
            if (is_a($exception::class, $class, true)) {
×
185
                return $status;
×
186
            }
187
        }
188

189
        if ($exception instanceof SymfonyHttpExceptionInterface) {
9✔
190
            return $exception->getStatusCode();
×
191
        }
192

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

197
        if ($exception instanceof ValidationException) {
9✔
198
            return 422;
×
199
        }
200

201
        if ($status = $errorOperation?->getStatus()) {
9✔
202
            return $status;
9✔
203
        }
204

205
        return 500;
×
206
    }
207

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