ApiExceptionListener   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 33
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 4
eloc 14
dl 0
loc 33
c 0
b 0
f 0
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A onKernelException() 0 21 3
1
<?php
2
3
namespace App\Project\App\EventListener;
4
5
use Symfony\Component\HttpFoundation\JsonResponse;
6
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
7
use Symfony\Component\Validator\Exception\ValidatorException;
8
9
class ApiExceptionListener
10
{
11
    /**
12
     * @var bool
13
     */
14
    public $isKernelDebug;
15
16
    public function __construct(bool $isKernelDebug)
17
    {
18
        $this->isKernelDebug = $isKernelDebug;
19
    }
20
21
    public function onKernelException(GetResponseForExceptionEvent $event)
22
    {
23
        $throwedException = $event->getException();
24
25
        $errorBody = [
26
            'code'    => $throwedException->getCode(),
27
            'message' => $throwedException->getMessage(),
28
        ];
29
30
        if ($throwedException instanceof ValidatorException) {
31
            $errorBody['message'] = 'Invalid data has been sent';
32
        }
33
34
        if ($this->isKernelDebug) {
35
            $errorBody['exception'] = [
36
                'class'   => get_class($throwedException)
37
            ];
38
            $errorBody['trace'] = $throwedException->getTrace();
39
        }
40
41
        $event->setResponse(new JsonResponse(['success' => false, 'error' => $errorBody]));
42
    }
43
}
44