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

RequestDtoExceptionListener   A

Complexity

Total Complexity 3

Size/Duplication

Total Lines 25
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onKernelException() 0 13 2
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