RequestDtoExceptionListener   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 29
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 1 Features 1
Metric Value
eloc 14
c 2
b 1
f 1
dl 0
loc 29
ccs 15
cts 15
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onKernelException() 0 17 3
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\Response;
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 8
    public function __construct(SerializerInterface $serializer)
20
    {
21 8
        $this->serializer = $serializer;
22 8
    }
23
24 8
    public function onKernelException(ExceptionEvent $event): void
25
    {
26 8
        $exception = $event->getThrowable();
27
28 8
        if ($exception instanceof RequestDtoValidationException) {
29 4
            $format = $event->getRequest()->getContentType() ?? 'json';
30
31 4
            if (!\in_array($format, ['json', 'xml'], true)) {
32 2
                $format = 'json';
33
            }
34
35 4
            $responseObject = (string) $this->serializer->serialize($exception, $format);
36 4
            $event->setResponse(
37 4
                new Response(
38 4
                    $responseObject,
39 4
                    $exception->getStatusCode(),
40 4
                    [...$exception->getHeaders(), 'Content-Type' => 'application/problem+' . $format]
41
                )
42
            );
43
        }
44 8
    }
45
}
46