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

api-platform / core / 6236589284

19 Sep 2023 01:58PM UTC coverage: 37.063% (+0.2%) from 36.816%
6236589284

push

github

web-flow
fix(symfony): use static variable to store Error (#5837)

3 of 3 new or added lines in 1 file covered. (100.0%)

10133 of 27340 relevant lines covered (37.06%)

19.99 hits per line

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

72.34
/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\Operation;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use ApiPlatform\Metadata\ResourceClassResolverInterface;
24
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
25
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
26
use ApiPlatform\Symfony\Util\RequestAttributesExtractor;
27
use ApiPlatform\Symfony\Validator\Exception\ConstraintViolationListAwareExceptionInterface;
28
use ApiPlatform\Validator\Exception\ValidationException;
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

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

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

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

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

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

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

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

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

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

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

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

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

150
        foreach ($identifiers as $name => $value) {
9✔
151
            $dup->attributes->set($name, $value);
3✔
152
        }
153

154
        return $dup;
9✔
155
    }
156

157
    private function getOperationExceptionToStatus(Request $request): array
158
    {
159
        $attributes = RequestAttributesExtractor::extractAttributes($request);
9✔
160

161
        if ([] === $attributes) {
9✔
162
            return [];
9✔
163
        }
164

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

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

175
        return array_merge(...$exceptionToStatus);
×
176
    }
177

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

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

192
        if ($exception instanceof SymfonyHttpExceptionInterface) {
9✔
193
            return $exception->getStatusCode();
×
194
        }
195

196
        if ($exception instanceof RequestExceptionInterface) {
9✔
197
            return 400;
×
198
        }
199

200
        if ($exception instanceof ValidationException) {
9✔
201
            return 422;
×
202
        }
203

204
        if ($status = $errorOperation?->getStatus()) {
9✔
205
            return $status;
9✔
206
        }
207

208
        return 500;
×
209
    }
210

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

223
    public static function provide(): mixed
224
    {
225
        if ($data = static::$error) {
×
226
            return $data;
×
227
        }
228

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