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

api-platform / core / 10618078048

29 Aug 2024 03:28PM UTC coverage: 7.687% (-0.003%) from 7.69%
10618078048

push

github

web-flow
fix(laravel): cache metadata, add trace on debug mode (#6555)

0 of 143 new or added lines in 8 files covered. (0.0%)

3 existing lines in 1 file now uncovered.

12488 of 162451 relevant lines covered (7.69%)

22.92 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()) {
×
116
                // TODO: validation
117
                // static::$error = 'jsonapi' === $format && $errorResource instanceof ConstraintViolationListAwareExceptionInterface ? $errorResource->getConstraintViolationList() : $errorResource;
118
                static::$error = $errorResource;
×
119
                $operation = $operation->withProvider([self::class, 'provide']);
×
120
            }
121

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

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

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

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

142
            $operation = $operation->withNormalizationContext($normalizationContext);
×
143

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

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

160
            return $this->apiPlatformController->__invoke($dup);
×
161
        });
×
162
    }
163

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

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

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

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

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

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

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

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

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

206
        return 500;
×
207
    }
208

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

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

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