ExceptionListener::onKernelException()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 10
ccs 7
cts 7
cp 1
crap 3
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace FRZB\Component\RequestMapper\EventListener;
6
7
use FRZB\Component\RequestMapper\Event\ListenerExceptionEvent;
8
use FRZB\Component\RequestMapper\ExceptionFormatter\ExceptionFormatterInterface as ExceptionFormatter;
9
use FRZB\Component\RequestMapper\Helper\Header;
10
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
11
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
12
use Symfony\Component\HttpKernel\KernelEvents;
13
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface as EventDispatcher;
14
15
#[AsEventListener(event: KernelEvents::EXCEPTION, method: 'onKernelException', priority: 20)]
16
class ExceptionListener
17
{
18
    private const ALLOWED_CONTENT_TYPE = 'application/json';
19
20 6
    public function __construct(
21
        private readonly ExceptionFormatter $exceptionFormatter,
22
        private readonly EventDispatcher $eventDispatcher,
23
    ) {
24
    }
25
26 6
    public function onKernelException(ExceptionEvent $event): void
27
    {
28 6
        $request = $event->getRequest();
29 6
        $isContentTypeAllowed = $request->headers->contains(Header::CONTENT_TYPE, self::ALLOWED_CONTENT_TYPE);
30 6
        $isAcceptTypeAllowed = $request->headers->contains(Header::ACCEPT, self::ALLOWED_CONTENT_TYPE);
31
32 6
        if ($isContentTypeAllowed || $isAcceptTypeAllowed) {
33 3
            $errorContract = $this->exceptionFormatter->format($event->getThrowable());
34
35 3
            $this->eventDispatcher->dispatch(new ListenerExceptionEvent($event, $event->getThrowable(), self::class, $errorContract));
36
        }
37
    }
38
}
39