ExceptionListener::log()   A
last analyzed

Complexity

Conditions 5
Paths 78

Size

Total Lines 28
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 20
c 1
b 0
f 0
nc 78
nop 1
dl 0
loc 28
rs 9.2888
1
<?php
2
3
namespace GeodisBundle\Event;
4
5
use Doctrine\ORM\EntityManagerInterface;
6
use GeodisBundle\Entity\GeodisLogger;
7
use GeodisBundle\Service\DAO\Exception\ApiExceptionInterface;
8
use GuzzleHttp\Exception\GuzzleException;
9
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
10
use Symfony\Component\HttpFoundation\JsonResponse;
11
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
12
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
13
use Symfony\Component\HttpKernel\KernelEvents;
14
use Psr\Log\LoggerInterface;
15
16
class ExceptionListener
17
{
18
    public function __construct(
19
        private readonly EntityManagerInterface $em,
20
        private readonly LoggerInterface $logger
21
    ) {}
22
23
    #[AsEventListener(event: KernelEvents::EXCEPTION)]
24
    public function onKernelException(ExceptionEvent $event): void
25
    {
26
        $e = $event->getThrowable();
27
28
        if (!($e instanceof ApiExceptionInterface || $e instanceof GuzzleException)) {
29
            return;
30
        }
31
32
        $status = $e instanceof HttpExceptionInterface ? $e->getStatusCode() : 500;
33
34
        $event->setResponse(new JsonResponse(
35
            ['error' => $e->getMessage()],
36
            $status
37
        ));
38
39
        $this->log($e);
40
    }
41
42
    private function log(\Throwable $exception): void
43
    {
44
        try {
45
            $log = new GeodisLogger();
46
47
            $statusOrCode = $exception instanceof HttpExceptionInterface
48
                ? $exception->getStatusCode()
49
                : ($exception->getCode() !== 0 ? $exception->getCode() : 500);
50
51
            $trace  = $exception->getTrace();
52
            $first  = $trace[0] ?? null;
53
54
            $called  = $first
55
                ? sprintf('file: %s line: %s', $first['file'] ?? 'n/a', $first['line'] ?? 'n/a')
56
                : 'n/a';
57
58
            $occured = sprintf('file: %s line: %s', $exception->getFile(), $exception->getLine());
59
60
            $log->setCode((int) $statusOrCode);
61
            $log->setMessage($exception->getMessage());
62
            $log->setCalled($called);
63
            $log->setOccured($occured);
64
65
            $this->em->persist($log);
66
            $this->em->flush();
67
        } catch (\Throwable $e) {
68
            $this->logger->error('Erreur lors de la persistance du log Geodis : ' . $e->getMessage(), [
69
                'exception' => $e
70
            ]);
71
        }
72
    }
73
}
74