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

api-platform / core / 10903050455

17 Sep 2024 12:29PM UTC coverage: 7.684% (+0.7%) from 6.96%
10903050455

push

github

web-flow
fix: swagger ui with route identifier (#6616)

2 of 6 new or added lines in 6 files covered. (33.33%)

9000 existing lines in 286 files now uncovered.

12668 of 164863 relevant lines covered (7.68%)

22.93 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])) {
×
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'));
×
NEW
153
            $dup->attributes->set('_api_original_uri_variables', $request->attributes->get('_api_uri_variables'));
×
154
            $dup->attributes->set('_api_original_route_params', $request->attributes->get('_route_params'));
×
155
            $dup->attributes->set('_api_requested_operation', $request->attributes->get('_api_requested_operation'));
×
156

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

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

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

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

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

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

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

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

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

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

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

207
        return 500;
×
208
    }
209

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

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

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