Test Failed
Push — master ( c1d2e0...874a5e )
by Sven
13:19
created

ApiExceptionSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
eloc 2
c 2
b 0
f 1
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace App\Subscriber;
4
5
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
6
use Symfony\Component\HttpFoundation\JsonResponse;
7
use Symfony\Component\HttpFoundation\Response;
8
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
9
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
10
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
11
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
12
use Symfony\Component\HttpKernel\KernelEvents;
13
14
class ApiExceptionSubscriber implements EventSubscriberInterface
15
{
16
    public function onKernelException(ExceptionEvent $event): void
17
    {
18
        $throwable = $event->getThrowable();
19
20
        $response = $this->createResponse($throwable);
21
22
        $event->setResponse($response);
23
    }
24
25
    public static function getSubscribedEvents(): array
26
    {
27
        return [
28
            KernelEvents::EXCEPTION => 'onKernelException',
29
        ];
30
    }
31
32
    private function createResponse(\Throwable $throwable): Response
33
    {
34
        if ($throwable instanceof NotFoundHttpException) {
35
            return new Response(
36
                null,
37
                $throwable->getStatusCode(),
38
                $throwable->getHeaders(),
39
            );
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected ')'
Loading history...
40
        }
41
42
        if ($throwable instanceof BadRequestHttpException) {
43
            return new JsonResponse(
44
                ['errors' => json_decode($throwable->getMessage(), true) ?? [$throwable->getMessage()], ],
45
                $throwable->getStatusCode(),
46
            );
47
        }
48
49
        return new JsonResponse(
50
            ['message' => $throwable->getMessage()],
51
            $throwable instanceof HttpExceptionInterface ? $throwable->getStatusCode() : Response::HTTP_INTERNAL_SERVER_ERROR,
52
        );
53
    }
54
}
55