|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
/* |
|
6
|
|
|
* This file is part of the OpenapiBundle package. |
|
7
|
|
|
* |
|
8
|
|
|
* (c) Niels Nijens <[email protected]> |
|
9
|
|
|
* |
|
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
11
|
|
|
* file that was distributed with this source code. |
|
12
|
|
|
*/ |
|
13
|
|
|
|
|
14
|
|
|
namespace Nijens\OpenapiBundle\ExceptionHandling\EventSubscriber; |
|
15
|
|
|
|
|
16
|
|
|
use Nijens\OpenapiBundle\ExceptionHandling\Exception\ProblemExceptionInterface; |
|
17
|
|
|
use Nijens\OpenapiBundle\ExceptionHandling\ThrowableToProblemExceptionTransformerInterface; |
|
18
|
|
|
use Nijens\OpenapiBundle\Routing\RouteContext; |
|
19
|
|
|
use Symfony\Component\EventDispatcher\EventSubscriberInterface; |
|
20
|
|
|
use Symfony\Component\HttpFoundation\Request; |
|
21
|
|
|
use Symfony\Component\HttpKernel\Event\ExceptionEvent; |
|
22
|
|
|
use Symfony\Component\HttpKernel\KernelEvents; |
|
23
|
|
|
use Throwable; |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Transforms a {@see Throwable} to {@see ProblemExceptionInterface} for routes managed by the OpenAPI bundle. |
|
27
|
|
|
* |
|
28
|
|
|
* @author Niels Nijens <[email protected]> |
|
29
|
|
|
*/ |
|
30
|
|
|
final class ThrowableToProblemExceptionSubscriber implements EventSubscriberInterface |
|
31
|
|
|
{ |
|
32
|
|
|
/** |
|
33
|
|
|
* @var ThrowableToProblemExceptionTransformerInterface |
|
34
|
|
|
*/ |
|
35
|
|
|
private $throwableToProblemExceptionTransformer; |
|
36
|
|
|
|
|
37
|
|
|
public static function getSubscribedEvents(): array |
|
38
|
|
|
{ |
|
39
|
|
|
return [ |
|
40
|
|
|
KernelEvents::EXCEPTION => [ |
|
41
|
|
|
['onKernelExceptionTransformToProblemException', 10], |
|
42
|
|
|
], |
|
43
|
|
|
]; |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
public function __construct(ThrowableToProblemExceptionTransformerInterface $throwableToProblemExceptionTransformer) |
|
47
|
|
|
{ |
|
48
|
|
|
$this->throwableToProblemExceptionTransformer = $throwableToProblemExceptionTransformer; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function onKernelExceptionTransformToProblemException(ExceptionEvent $event): void |
|
52
|
|
|
{ |
|
53
|
|
|
if ($this->isManagedRoute($event->getRequest()) === false) { |
|
54
|
|
|
return; |
|
55
|
|
|
} |
|
56
|
|
|
|
|
57
|
|
|
$event->setThrowable( |
|
58
|
|
|
$this->throwableToProblemExceptionTransformer->transform( |
|
59
|
|
|
$event->getThrowable(), |
|
60
|
|
|
$event->getRequest()->getRequestUri() |
|
61
|
|
|
) |
|
62
|
|
|
); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
private function isManagedRoute(Request $request): bool |
|
66
|
|
|
{ |
|
67
|
|
|
$routeOptions = $request->attributes->get(RouteContext::REQUEST_ATTRIBUTE); |
|
68
|
|
|
|
|
69
|
|
|
return isset($routeOptions[RouteContext::RESOURCE]); |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|