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

ApiExceptionSubscriber::onExceptionEvent()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 2
Metric Value
eloc 10
c 3
b 0
f 2
dl 0
loc 14
rs 9.9332
cc 3
nc 3
nop 1
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