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

api-platform / core / 5690318870

pending completion
5690318870

push

github

dunglas
fix: previous merge

6 of 6 new or added lines in 3 files covered. (100.0%)

11110 of 18881 relevant lines covered (58.84%)

22.32 hits per line

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

77.63
/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\ApiResource;
19
use ApiPlatform\Metadata\Get;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
22
use ApiPlatform\Metadata\ResourceClassResolverInterface;
23
use ApiPlatform\Util\ErrorFormatGuesser;
24
use ApiPlatform\Util\OperationRequestInitiatorTrait;
25
use ApiPlatform\Util\RequestAttributesExtractor;
26
use ApiPlatform\Validator\Exception\ValidationException;
27
use Psr\Log\LoggerInterface;
28
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
29
use Symfony\Component\HttpFoundation\Request;
30
use Symfony\Component\HttpKernel\EventListener\ErrorListener as SymfonyErrorListener;
31
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
32

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

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

57
    protected function duplicateRequest(\Throwable $exception, Request $request): Request
58
    {
59
        $dup = parent::duplicateRequest($exception, $request);
6✔
60

61
        $apiOperation = $this->initializeOperation($request);
6✔
62

63
        $resourceClass = $exception::class;
6✔
64
        $format = ErrorFormatGuesser::guessErrorFormat($request, $this->errorFormats);
6✔
65

66
        if ($this->resourceClassResolver?->isResourceClass($exception::class)) {
6✔
67
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
2✔
68

69
            $operation = null;
2✔
70
            foreach ($resourceCollection as $resource) {
2✔
71
                foreach ($resource->getOperations() as $op) {
2✔
72
                    foreach ($op->getOutputFormats() as $key => $value) {
2✔
73
                        if ($key === $format['key']) {
2✔
74
                            $operation = $op;
2✔
75
                            break 3;
2✔
76
                        }
77
                    }
78
                }
79
            }
80

81
            // No operation found for the requested format, we take the first available
82
            if (!$operation) {
2✔
83
                $operation = $resourceCollection->getOperation();
×
84
            }
85
            $errorResource = $exception;
2✔
86
        } elseif ($this->resourceMetadataCollectionFactory) {
4✔
87
            // Create a generic, rfc7807 compatible error according to the wanted format
88
            /** @var HttpOperation $operation */
89
            $operation = $this->resourceMetadataCollectionFactory->create(Error::class)->getOperation($this->getFormatOperation($format['key'] ?? null));
4✔
90
            $operation = $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
4✔
91
            $errorResource = Error::createFromException($exception, $operation->getStatus());
4✔
92
            $resourceClass = Error::class;
4✔
93
        } else {
94
            $operation = new Get(name: '_api_errors_problem', class: Error::class, outputFormats: ['jsonld' => ['application/ld+json']], normalizationContext: ['groups' => ['jsonld'], 'skip_null_values' => true]);
×
95
            $operation = $operation->withStatus($this->getStatusCode($apiOperation, $request, $operation, $exception));
×
96
            $errorResource = Error::createFromException($exception, $operation->getStatus());
×
97
            $resourceClass = Error::class;
×
98
        }
99

100
        $identifiers = $this->identifiersExtractor?->getIdentifiersFromItem($errorResource, $operation) ?? [];
6✔
101

102
        $dup->attributes->set('_api_error', true);
6✔
103
        $dup->attributes->set('_api_resource_class', $resourceClass);
6✔
104
        $dup->attributes->set('_api_previous_operation', $apiOperation);
6✔
105
        $dup->attributes->set('_api_operation', $operation);
6✔
106
        $dup->attributes->set('_api_operation_name', $operation->getName());
6✔
107
        $dup->attributes->remove('exception');
6✔
108
        $dup->attributes->set('data', $errorResource);
6✔
109
        // Once we get rid of the SwaggerUiAction we'll be able to do this properly
110
        $dup->attributes->set('_api_exception_swagger_data', [
6✔
111
            '_route' => $request->attributes->get('_route'),
6✔
112
            '_route_params' => $request->attributes->get('_route_params'),
6✔
113
            '_api_resource_class' => $request->attributes->get('_api_resource_class'),
6✔
114
            '_api_operation_name' => $request->attributes->get('_api_operation_name'),
6✔
115
        ]);
6✔
116

117
        foreach ($identifiers as $name => $value) {
6✔
118
            $dup->attributes->set($name, $value);
2✔
119
        }
120

121
        return $dup;
6✔
122
    }
123

124
    private function getOperationExceptionToStatus(Request $request): array
125
    {
126
        $attributes = RequestAttributesExtractor::extractAttributes($request);
4✔
127

128
        if ([] === $attributes) {
4✔
129
            return [];
4✔
130
        }
131

132
        $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($attributes['resource_class']);
×
133
        /** @var HttpOperation $operation */
134
        $operation = $resourceMetadataCollection->getOperation($attributes['operation_name'] ?? null);
×
135
        $exceptionToStatus = [$operation->getExceptionToStatus() ?: []];
×
136

137
        foreach ($resourceMetadataCollection as $resourceMetadata) {
×
138
            /* @var ApiResource $resourceMetadata */
139
            $exceptionToStatus[] = $resourceMetadata->getExceptionToStatus() ?: [];
×
140
        }
141

142
        return array_merge(...$exceptionToStatus);
×
143
    }
144

145
    private function getStatusCode(?HttpOperation $apiOperation, Request $request, ?HttpOperation $errorOperation, \Throwable $exception): int
146
    {
147
        $exceptionToStatus = array_merge(
4✔
148
            $this->exceptionToStatus,
4✔
149
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : $this->getOperationExceptionToStatus($request),
4✔
150
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : []
4✔
151
        );
4✔
152

153
        foreach ($exceptionToStatus as $class => $status) {
4✔
154
            if (is_a($exception::class, $class, true)) {
×
155
                return $status;
×
156
            }
157
        }
158

159
        if ($exception instanceof SymfonyHttpExceptionInterface) {
4✔
160
            return $exception->getStatusCode();
×
161
        }
162

163
        if ($exception instanceof RequestExceptionInterface) {
4✔
164
            return 400;
×
165
        }
166

167
        if ($exception instanceof ValidationException) {
4✔
168
            return 422;
×
169
        }
170

171
        if ($status = $errorOperation?->getStatus()) {
4✔
172
            return $status;
4✔
173
        }
174

175
        return 500;
×
176
    }
177

178
    private function getFormatOperation(string $format): ?string
179
    {
180
        return match ($format) {
4✔
181
            'jsonproblem' => '_api_errors_problem',
4✔
182
            'jsonld' => '_api_errors_hydra',
4✔
183
            'jsonapi' => '_api_errors_jsonapi',
4✔
184
            default => null
4✔
185
        };
4✔
186
    }
187
}
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