EncodeJsonResponseListener::onKernelView()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 18
ccs 11
cts 11
cp 1
rs 9.2
cc 4
eloc 9
nc 4
nop 1
crap 4
1
<?php
2
3
namespace Alchemy\RestBundle\EventListener;
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\GetResponseForControllerResultEvent;
9
use Symfony\Component\HttpKernel\KernelEvents;
10
11
class EncodeJsonResponseListener implements EventSubscriberInterface
12
{
13
14 6
    public function onKernelView(GetResponseForControllerResultEvent $event)
15
    {
16 6
        if (! $event->getRequest()->attributes->get('_rest[encode_response]', false, true)) {
17 2
            return;
18
        }
19
20 4
        $result = $event->getControllerResult();
21
22 4
        if (! $result instanceof Response) {
23 4
            if (!is_array($result)) {
24 2
                throw new \LogicException('Invalid controller result: array was expected.');
25
            }
26
27 2
            $result = new JsonResponse($result);
28 2
        }
29
30 2
        $event->setResponse($result);
31 2
    }
32
33 2
    public static function getSubscribedEvents()
34
    {
35 2
        return array(KernelEvents::VIEW => 'onKernelView');
36
    }
37
}
38