Completed
Push — master ( 9dfe4a...9f73a9 )
by Alexey
03:27
created

RequestDtoExceptionListener::onKernelException()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 10
c 1
b 0
f 1
nc 2
nop 1
dl 0
loc 13
ccs 11
cts 11
cp 1
crap 2
rs 9.9332
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Nelexa\RequestDtoBundle\EventListener;
6
7
use Nelexa\RequestDtoBundle\Exception\RequestDtoValidationException;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
10
use Symfony\Component\Serializer\SerializerInterface;
11
12
final class RequestDtoExceptionListener
13
{
14
    private SerializerInterface $serializer;
15
16
    /**
17
     * ExceptionListener constructor.
18
     */
19 5
    public function __construct(SerializerInterface $serializer)
20
    {
21 5
        $this->serializer = $serializer;
22 5
    }
23
24 5
    public function onKernelException(ExceptionEvent $event): void
25
    {
26 5
        $exception = $event->getThrowable();
27
28 5
        if ($exception instanceof RequestDtoValidationException) {
29 3
            $contentType = 'json';
30 3
            $responseObject = $this->serializer->serialize($exception, $contentType);
31 3
            $event->setResponse(
32 3
                new JsonResponse(
33 3
                    $responseObject,
34 3
                    $exception->getStatusCode(),
35 3
                    [...$exception->getHeaders(), 'Content-Type' => 'application/problem+json'],
36 3
                    true
37
                )
38
            );
39
        }
40 5
    }
41
}
42