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

api-platform / core / 10487907814

21 Aug 2024 10:12AM UTC coverage: 7.035% (-0.7%) from 7.697%
10487907814

push

github

web-flow
feat(laravel): policy, auth and gate (#6523)

23 of 162 new or added lines in 33 files covered. (14.2%)

212 existing lines in 3 files now uncovered.

11392 of 161924 relevant lines covered (7.04%)

23.0 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

35
class ErrorHandler extends ExceptionsHandler
36
{
37
    use ContentNegotiationTrait;
38
    use OperationRequestInitiatorTrait;
39
    public static mixed $error;
40

41
    public function __construct(
42
        Container $container,
43
        ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
44
        private readonly ApiPlatformController $apiPlatformController,
45
        private readonly ?IdentifiersExtractorInterface $identifiersExtractor = null,
46
        private readonly ?ResourceClassResolverInterface $resourceClassResolver = null,
47
        ?Negotiator $negotiator = null
48
    ) {
49
        $this->resourceMetadataCollectionFactory = $resourceMetadataCollectionFactory;
×
50
        $this->negotiator = $negotiator;
×
51
        // calls register
52
        parent::__construct($container);
×
53
        $this->register();
×
54
    }
55

56
    public function register(): void
57
    {
58
        $this->renderable(function (\Throwable $exception, Request $request) {
×
59
            $apiOperation = $this->initializeOperation($request);
×
60
            if (!$apiOperation) {
×
61
                return null;
×
62
            }
63

64
            $formats = config('api-platform.error_formats') ?? ['jsonproblem' => ['application/problem+json']];
×
65
            $format = $request->getRequestFormat() ?? $this->getRequestFormat($request, $formats, false);
×
66

67
            if ($this->resourceClassResolver->isResourceClass($exception::class)) {
×
68
                $resourceCollection = $this->resourceMetadataCollectionFactory->create($exception::class);
×
69

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

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

104
                $errorResource = Error::createFromException($exception, $statusCode);
×
105
            }
106

107
            /** @var HttpOperation $operation */
108
            if (!$operation->getProvider()) {
×
109
                // TODO: validation
110
                // static::$error = 'jsonapi' === $format && $errorResource instanceof ConstraintViolationListAwareExceptionInterface ? $errorResource->getConstraintViolationList() : $errorResource;
111
                static::$error = $errorResource;
×
112
                $operation = $operation->withProvider([self::class, 'provide']);
×
113
            }
114

115
            // For our swagger Ui errors
116
            if ('html' === $format) {
×
117
                $operation = $operation->withOutputFormats(['html' => ['text/html']]);
×
118
            }
119

120
            $identifiers = [];
×
121
            try {
122
                $identifiers = $this->identifiersExtractor?->getIdentifiersFromItem($errorResource, $operation) ?? [];
×
123
            } catch (\Exception $e) {
×
124
            }
125

126
            $dup = $request->duplicate(null, null, []);
×
127
            $dup->setMethod('GET');
×
128
            $dup->attributes->set('_api_resource_class', $operation->getClass());
×
129
            $dup->attributes->set('_api_previous_operation', $apiOperation);
×
130
            $dup->attributes->set('_api_operation', $operation);
×
131
            $dup->attributes->set('_api_operation_name', $operation->getName());
×
132
            $dup->attributes->remove('exception');
×
133
            // These are for swagger
134
            $dup->attributes->set('_api_original_route', $request->attributes->get('_route'));
×
135
            $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
×
136
            $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
×
137

138
            foreach ($identifiers as $name => $value) {
×
139
                $dup->attributes->set($name, $value);
×
140
            }
141

142
            return $this->apiPlatformController->__invoke($dup);
×
143
        });
×
144
    }
145

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

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

NEW
159
        if ($exception instanceof AuthenticationException) {
×
NEW
160
            return 401;
×
161
        }
162

NEW
163
        if ($exception instanceof AuthorizationException) {
×
NEW
164
            return 403;
×
165
        }
166

NEW
167
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
NEW
168
            return $exception->getStatusCode();
×
169
        }
170

171
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
172
            return $exception->getStatusCode();
×
173
        }
174

175
        if ($exception instanceof RequestExceptionInterface) {
×
176
            return 400;
×
177
        }
178

179
        // if ($exception instanceof ValidationException) {
180
        //     return 422;
181
        // }
182

183
        if ($status = $errorOperation?->getStatus()) {
×
184
            return $status;
×
185
        }
186

187
        return 500;
×
188
    }
189

190
    private function getFormatOperation(?string $format): string
191
    {
192
        return match ($format) {
×
193
            'json' => '_api_errors_problem',
×
194
            'jsonproblem' => '_api_errors_problem',
×
195
            'jsonld' => '_api_errors_hydra',
×
196
            'jsonapi' => '_api_errors_jsonapi',
×
197
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
198
            default => '_api_errors_problem'
×
199
        };
×
200
    }
201

202
    public static function provide(): mixed
203
    {
204
        if ($data = static::$error) {
×
205
            return $data;
×
206
        }
207

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

© 2026 Coveralls, Inc