RequestDtoExceptionListener::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 1
eloc 1
c 1
b 0
f 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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