RequestSubscriber::handleException()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Sf4\Api\EventSubscriber;
4
5
use Sf4\Api\RequestHandler\RequestHandlerInterface;
6
use Sf4\Api\RequestHandler\RequestHandlerTrait;
7
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
8
use Symfony\Component\HttpFoundation\JsonResponse;
9
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
10
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
11
use Symfony\Component\HttpKernel\KernelEvents;
12
13
class RequestSubscriber implements EventSubscriberInterface
14
{
15
16
    use RequestHandlerTrait;
17
18
    /**
19
     * RequestSubscriber constructor.
20
     * @param RequestHandlerInterface $requestHandler
21
     */
22
    public function __construct(RequestHandlerInterface $requestHandler)
23
    {
24
        $this->setRequestHandler($requestHandler);
25
    }
26
27
    /**
28
     * @return array
29
     */
30
    public static function getSubscribedEvents(): array
31
    {
32
        return [
33
            KernelEvents::REQUEST => 'handleRequest',
34
            KernelEvents::EXCEPTION => 'handleException'
35
        ];
36
    }
37
38
    /**
39
     * @param GetResponseEvent $event
40
     */
41
    public function handleRequest(GetResponseEvent $event): void
42
    {
43
        $request = $event->getRequest();
44
        if ($request->attributes->has('_route')) {
45
            $requestHandler = $this->getRequestHandler();
46
            if ($requestHandler) {
47
                $requestHandler->handle($request);
48
                if ($response = $requestHandler->getResponse()) {
49
                    $event->setResponse($response);
50
                }
51
            }
52
        }
53
    }
54
55
    /**
56
     * @param GetResponseForExceptionEvent $event
57
     */
58
    public function handleException(GetResponseForExceptionEvent $event): void
59
    {
60
        $event->setResponse(new JsonResponse([
61
            $event->getException()->getMessage()
62
        ], 200));
63
    }
64
}
65