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

api-platform / core / 10315659289

09 Aug 2024 07:49AM UTC coverage: 7.841% (-0.006%) from 7.847%
10315659289

push

github

soyuka
style: cs fixes

70 of 529 new or added lines in 176 files covered. (13.23%)

160 existing lines in 58 files now uncovered.

12688 of 161818 relevant lines covered (7.84%)

26.86 hits per line

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

0.0
/src/Laravel/Exception/Handler.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\Contracts\Container\Container;
27
use Illuminate\Foundation\Exceptions\Handler as ExceptionsHandler;
28
use Illuminate\Http\Request;
29
use Negotiation\Negotiator;
30
use Symfony\Component\HttpFoundation\Exception\RequestExceptionInterface;
31
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface as SymfonyHttpExceptionInterface;
32

33
class Handler extends ExceptionsHandler
34
{
35
    use ContentNegotiationTrait;
36
    use OperationRequestInitiatorTrait;
37
    public static mixed $error;
38

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

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

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

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

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

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

102
                $errorResource = Error::createFromException($exception, $statusCode);
×
103
            }
104

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

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

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

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

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

140
            return $this->apiPlatformController->__invoke($dup);
×
141
        });
×
142
    }
143

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

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

157
        if ($exception instanceof SymfonyHttpExceptionInterface) {
×
158
            return $exception->getStatusCode();
×
159
        }
160

161
        if ($exception instanceof RequestExceptionInterface) {
×
162
            return 400;
×
163
        }
164

165
        // if ($exception instanceof ValidationException) {
166
        //     return 422;
167
        // }
168

169
        if ($status = $errorOperation?->getStatus()) {
×
170
            return $status;
×
171
        }
172

173
        return 500;
×
174
    }
175

176
    private function getFormatOperation(?string $format): string
177
    {
178
        return match ($format) {
×
179
            'json' => '_api_errors_problem',
×
180
            'jsonproblem' => '_api_errors_problem',
×
181
            'jsonld' => '_api_errors_hydra',
×
182
            'jsonapi' => '_api_errors_jsonapi',
×
183
            'html' => '_api_errors_problem', // This will be intercepted by the SwaggerUiProvider
×
184
            default => '_api_errors_problem'
×
185
        };
×
186
    }
187

188
    public static function provide(): mixed
189
    {
190
        if ($data = static::$error) {
×
191
            return $data;
×
192
        }
193

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