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

api-platform / core / 14967095168

12 May 2025 08:08AM UTC coverage: 22.155% (+13.7%) from 8.457%
14967095168

Pull #7135

github

web-flow
Merge 574a2b863 into 4dd0cdfc4
Pull Request #7135: fix(symfony,laravel): InvalidUriVariableException status code (e400)

1 of 2 new or added lines in 2 files covered. (50.0%)

120 existing lines in 12 files now uncovered.

10846 of 48956 relevant lines covered (22.15%)

10.12 hits per line

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

0.0
/src/Laravel/Exception/ErrorHandler.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\Laravel\Exception;
15

16
use ApiPlatform\Laravel\ApiResource\Error;
17
use ApiPlatform\Laravel\Controller\ApiPlatformController;
18
use ApiPlatform\Metadata\Exception\InvalidUriVariableException;
19
use ApiPlatform\Metadata\Exception\ProblemExceptionInterface;
20
use ApiPlatform\Metadata\Exception\StatusAwareExceptionInterface;
21
use ApiPlatform\Metadata\HttpOperation;
22
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
23
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
24
use ApiPlatform\Metadata\ResourceClassResolverInterface;
25
use ApiPlatform\Metadata\Util\ContentNegotiationTrait;
26
use ApiPlatform\State\Util\OperationRequestInitiatorTrait;
27
use Illuminate\Auth\Access\AuthorizationException;
28
use Illuminate\Auth\AuthenticationException;
29
use Illuminate\Contracts\Container\Container;
30
use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler;
31
use Negotiation\Negotiator;
32
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
33
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
34
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
35

36
class ErrorHandler extends ExceptionsHandler
37
{
38
    use ContentNegotiationTrait;
39
    use OperationRequestInitiatorTrait;
40

41
    public static mixed $error;
42

43
    /**
44
     * @param array<class-string, int> $exceptionToStatus
45
     * @param array<string, string[]>  $errorFormats
46
     */
47
    public function __construct(
48
        Container $container,
49
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
50
        private readonly ApiPlatformController $apiPlatformController,
51
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
52
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
53
        ?Negotiator $negotiator = null,
54
        private readonly ?array $exceptionToStatus = null,
55
        private readonly ?bool $debug = false,
56
        private readonly ?array $errorFormats = null,
57
    ) {
58
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
59
        $this->negotiator = $negotiator;
×
60
        parent::__construct($container);
×
61
    }
62

63
    public function render($request, \Throwable $exception)
64
    {
65
        $apiOperation = $this->initializeOperation($request);
×
66

67
        if (!$apiOperation) {
×
68
            return parent::render($request, $exception);
×
69
        }
70

71
        $formats = $this->errorFormats ?? ['jsonproblem' => ['application/problem+json']];
×
72
        $format = $request->getRequestFormat() ?? $this->getRequestFormat($request, $formats, false);
×
73

74
        if ($this->resourceClassResolver->isResourceClass($exception::class)) {
×
75
            $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
×
76

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

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

111
            $errorResource = Error::createFromException($exception, $statusCode);
×
112
        }
113

114
        /** @var HttpOperation $operation */
115
        if (!$operation->getProvider()) {
×
116
            static::$error = $errorResource;
×
117
            $operation = $operation->withProvider([self::class, 'provide']);
×
118
        }
119

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

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

131
        $normalizationContext = $operation->getNormalizationContext() ?? [];
×
132
        if (!($normalizationContext['api_error_resource'] ?? false)) {
×
133
            $normalizationContext += ['api_error_resource' => true];
×
134
        }
135

136
        if (!isset($normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES])) {
×
137
            $normalizationContext[AbstractObjectNormalizer::IGNORED_ATTRIBUTES] = true === $this->debug ? [] : ['originalTrace'];
×
138
        }
139

140
        $operation = $operation->withNormalizationContext($normalizationContext);
×
141

142
        $dup = $request->duplicate(null, null, []);
×
143
        $dup->setMethod('GET');
×
144
        $dup->attributes->set('_api_resource_class', $operation->getClass());
×
145
        $dup->attributes->set('_api_previous_operation', $apiOperation);
×
146
        $dup->attributes->set('_api_operation', $operation);
×
147
        $dup->attributes->set('_api_operation_name', $operation->getName());
×
148
        $dup->attributes->set('exception', $exception);
×
149
        // These are for swagger
150
        $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
×
151
        $dup->attributes->set('_api_original_uri_variables', $request->attributes->get('_api_uri_variables'));
×
152
        $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
×
153
        $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
×
154

155
        foreach ($identifiers as $name => $value) {
×
156
            $dup->attributes->set($name, $value);
×
157
        }
158

159
        try {
160
            return $this->apiPlatformController->__invoke($dup);
×
161
        } catch (\Throwable $e) {
×
162
            return parent::render($dup, $e);
×
163
        }
164
    }
165

166
    private function getStatusCode(?HttpOperation $apiOperation, ?HttpOperation $errorOperation, \Throwable $exception): int
167
    {
168
        $exceptionToStatus = array_merge(
×
169
            $apiOperation ? $apiOperation->getExceptionToStatus() ?? [] : [],
×
170
            $errorOperation ? $errorOperation->getExceptionToStatus() ?? [] : [],
×
171
            $this->exceptionToStatus ?? []
×
172
        );
×
173

174
        foreach ($exceptionToStatus as $class => $status) {
×
175
            if (is_a($exception::class, $class, true)) {
×
176
                return $status;
×
177
            }
178
        }
179

180
        if ($exception instanceof AuthenticationException) {
×
181
            return 401;
×
182
        }
183

184
        if ($exception instanceof AuthorizationException) {
×
185
            return 403;
×
186
        }
187

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

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

NEW
196
        if ($exception instanceof RequestExceptionInterface || $exception instanceof InvalidUriVariableException) {
×
197
            return 400;
×
198
        }
199

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

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

208
        return 500;
×
209
    }
210

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