ConvertExceptionToJSONResponseSubscriber   A
last analyzed

Complexity

Total Complexity 3

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 3
eloc 9
c 1
b 0
f 0
dl 0
loc 27
ccs 10
cts 10
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getSubscribedEvents() 0 4 1
A __construct() 0 3 1
A onKernelException() 0 6 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 3
    public function __construct(ExceptionConverter $converter)
27
    {
28 3
        $this->converter = $converter;
29 3
    }
30
31
    /**
32
     * @Callback
33
     *
34
     * @param ExceptionEvent $event
35
     */
36 3
    public function onKernelException(ExceptionEvent $event): void
37
    {
38 3
        $e = $event->getThrowable();
39 3
        $result = $this->converter->convert($e);
40 3
        $response = new JsonResponse($result, $result['status']);
41 3
        $event->setResponse($response->setEncodingOptions(JSON_UNESCAPED_UNICODE));
42 3
    }
43
}
44