Passed
Push — master ( d1cf08...b96742 )
by Siim
14:35
created

RequestSubscriber::handleRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

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