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

api-platform / core / 13203378522

07 Feb 2025 03:56PM UTC coverage: 8.501% (+0.7%) from 7.837%
13203378522

push

github

soyuka
Merge 4.1

111 of 490 new or added lines in 51 files covered. (22.65%)

5590 existing lines in 163 files now uncovered.

13345 of 156987 relevant lines covered (8.5%)

22.88 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\ProblemExceptionInterface;
19
use ApiPlatform\Metadata\Exception\StatusAwareExceptionInterface;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\IdentifiersExtractorInterface;
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 Illuminate\Auth\Access\AuthorizationException;
27
use Illuminate\Auth\AuthenticationException;
28
use Illuminate\Contracts\Container\Container;
29
use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler;
30
use Illuminate\Http\Request;
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
     */
46
    public function __construct(
47
        Container $container,
48
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
49
        private readonly ApiPlatformController $apiPlatformController,
50
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
51
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
52
        ?Negotiator $negotiator = null,
53
        private readonly ?array $exceptionToStatus = null,
54
        private readonly ?bool $debug = false,
55
    ) {
56
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
57
        $this->negotiator = $negotiator;
×
58
        // calls register
59
        parent::__construct($container);
×
60
        $this->register();
×
61
    }
62

63
    public function register(): void
64
    {
65
        $this->renderable(function (\Throwable $exception, Request $request) {
×
66
            $apiOperation = $this->initializeOperation($request);
×
67
            if (!$apiOperation) {
×
68
                return null;
×
69
            }
70

71
            $formats = config('api-platform.error_formats') ?? ['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()) {
×
UNCOV
116
                static::$error = $errorResource;
×
UNCOV
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());
×
NEW
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
            return $this->apiPlatformController->__invoke($dup);
×
160
        });
×
161
    }
162

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

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

177
        if ($exception instanceof AuthenticationException) {
×
178
            return 401;
×
179
        }
180

181
        if ($exception instanceof AuthorizationException) {
×
182
            return 403;
×
183
        }
184

185
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
186
            return $exception->getStatusCode();
×
187
        }
188

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

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

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

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

205
        return 500;
×
206
    }
207

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

220
    public static function provide(): mixed
221
    {
222
        if ($data = static::$error) {
×
223
            return $data;
×
224
        }
225

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