Passed
Push — master ( a85640...f71496 )
by Jin
02:34
created

onKernelException()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace jin2chen\ApiBundle\EventSubscriber;
6
7
use jin2chen\ApiBundle\Response\ExceptionConverter;
8
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
9
use Symfony\Component\HttpFoundation\JsonResponse;
10
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
11
use Symfony\Component\HttpKernel\KernelEvents;
12
13
use const JSON_UNESCAPED_UNICODE;
14
15
class ConvertExceptionToJSONResponseSubscriber implements EventSubscriberInterface
16
{
17
    private ExceptionConverter $converter;
18
19 2
    public static function getSubscribedEvents(): array
20
    {
21
        return [
22 2
            KernelEvents::EXCEPTION => ['onKernelException', -32],
23
        ];
24
    }
25
26 2
    public function __construct(ExceptionConverter $converter)
27
    {
28 2
        $this->converter = $converter;
29 2
    }
30
31
    /**
32
     * @Callback
33
     *
34
     * @param ExceptionEvent $event
35
     */
36 2
    public function onKernelException(ExceptionEvent $event): void
37
    {
38 2
        $e = $event->getThrowable();
39 2
        $result = $this->converter->convert($e);
40 2
        $response = new JsonResponse($result, $result['status']);
41 2
        $event->setResponse($response->setEncodingOptions(JSON_UNESCAPED_UNICODE));
42 2
    }
43
}
44