Completed
Push — main ( bdd72f...bbe282 )
by Niels
15s queued 12s
created

ThrowableToProblemExceptionSubscriber   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 40
rs 10
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A onKernelExceptionTransformToProblemException() 0 10 2
A __construct() 0 3 1
A isManagedRoute() 0 5 1
A getSubscribedEvents() 0 5 1
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