Completed
Push — master ( 583849...e66a3e )
by Paweł
20s
created

ApiExceptionSubscriber::getSubscribedEvents()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 2
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
nc 1
nop 0
1
<?php
2
3
namespace App\EventSubscriber;
4
5
use SWP\Component\Common\Exception\HttpException;
6
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
7
use Symfony\Component\HttpFoundation\JsonResponse;
8
use Symfony\Component\HttpFoundation\Response;
9
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
10
11
class ApiExceptionSubscriber implements EventSubscriberInterface
12
{
13
    public function onExceptionEvent(ExceptionEvent $event)
14
    {
15
        $request = $event->getRequest();
16
        $exception = $event->getException();
17
        if ('application/json' === $request->headers->get('Content-Type')) {
18
            $code = Response::HTTP_INTERNAL_SERVER_ERROR;
19
            if ($exception instanceof HttpException) {
20
                $code = $exception->getStatusCode();
21
            }
22
23
            $event->setResponse(new JsonResponse([
24
                'success' => false,
25
                'message' => $exception->getMessage(),
26
            ], $code));
27
        }
28
    }
29
30
    public static function getSubscribedEvents()
31
    {
32
        return [
33
            ExceptionEvent::class => 'onExceptionEvent',
34
        ];
35
    }
36
}
37