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

api-platform / core / 6250499992

20 Sep 2023 03:04PM UTC coverage: 36.863% (-0.2%) from 37.089%
6250499992

push

github

web-flow
fix: errors without compatibility flag (#5841)

24 of 24 new or added lines in 8 files covered. (100.0%)

10081 of 27347 relevant lines covered (36.86%)

13.36 hits per line

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

74.23
/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
    private static mixed $error;
45

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

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

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

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

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

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

114
        if (!$operation->getProvider()) {
9✔
115
            static::$error = 'jsonapi' === $format && $errorResource instanceof ConstraintViolationListAwareExceptionInterface ? $errorResource->getConstraintViolationList() : $errorResource;
9✔
116
            $operation = $operation->withProvider([self::class, 'provide']);
9✔
117
        }
118

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

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

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

137
        if ('jsonld' === $format && !($apiOperation?->getExtraProperties()['rfc_7807_compliant_errors'] ?? false)) {
9✔
138
            $operation = $operation->withOutputFormats(['jsonld' => ['application/ld+json']])
6✔
139
                                   ->withLinks([])
6✔
140
                                   ->withExtraProperties(['rfc_7807_compliant_errors' => false] + $operation->getExtraProperties());
6✔
141
        }
142

143
        $dup->attributes->set('_api_resource_class', $operation->getClass());
9✔
144
        $dup->attributes->set('_api_previous_operation', $apiOperation);
9✔
145
        $dup->attributes->set('_api_operation', $operation);
9✔
146
        $dup->attributes->set('_api_operation_name', $operation->getName());
9✔
147
        $dup->attributes->remove('exception');
9✔
148
        // These are for swagger
149
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
9✔
150
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
9✔
151
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
9✔
152

153
        foreach ($identifiers as $name => $value) {
9✔
154
            $dup->attributes->set($name, $value);
3✔
155
        }
156

157
        return $dup;
9✔
158
    }
159

160
    private function getOperationExceptionToStatus(Request $request): array
161
    {
162
        $attributes = RequestAttributesExtractor::extractAttributes($request);
9✔
163

164
        if ([] === $attributes) {
9✔
165
            return [];
9✔
166
        }
167

168
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
169
        /** @var HttpOperation $operation */
170
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
171
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
172

173
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
174
            /* @var ApiResource $resourceMetadata */
175
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
176
        }
177

178
        return array_merge(...$exceptionToStatus);
×
179
    }
180

181
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
182
    {
183
        $exceptionToStatus = array_merge(
9✔
184
            $this->exceptionToStatus,
9✔
185
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
9✔
186
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
9✔
187
        );
9✔
188

189
        foreach ($exceptionToStatus as $class => $status) {
9✔
190
            if (is_a($exception::class, $class, true)) {
×
191
                return $status;
×
192
            }
193
        }
194

195
        if ($exception instanceof SymfonyHttpExceptionInterface) {
9✔
196
            return $exception->getStatusCode();
×
197
        }
198

199
        if ($exception instanceof RequestExceptionInterface) {
9✔
200
            return 400;
×
201
        }
202

203
        if ($exception instanceof ValidationException) {
9✔
204
            return 422;
×
205
        }
206

207
        if ($status = $errorOperation?->getStatus()) {
9✔
208
            return $status;
9✔
209
        }
210

211
        return 500;
×
212
    }
213

214
    private function getFormatOperation(?string $format): string
215
    {
216
        return match ($format) {
6✔
217
            'json' => '_api_errors_problem',
6✔
218
            'jsonproblem' => '_api_errors_problem',
6✔
219
            'jsonld' => '_api_errors_hydra',
6✔
220
            'jsonapi' => '_api_errors_jsonapi',
6✔
221
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
6✔
222
            default => '_api_errors_problem'
6✔
223
        };
6✔
224
    }
225

226
    public static function provide(): mixed
227
    {
228
        if ($data = static::$error) {
×
229
            return $data;
×
230
        }
231

232
        throw new \LogicException(sprintf('We could not find the thrown exception in the %s.', self::class));
×
233
    }
234
}
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