ExceptionListener   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 9
c 1
b 0
f 0
dl 0
loc 21
ccs 8
cts 8
cp 1
rs 10
wmc 4

2 Methods

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