Completed
Pull Request — develop (#1)
by Chris
16:11 queued 14:06
created

AutoJsonResponseListener::onKernelView()   C

Complexity

Conditions 7
Paths 8

Size

Total Lines 36
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 7

Importance

Changes 3
Bugs 0 Features 1
Metric Value
c 3
b 0
f 1
dl 0
loc 36
ccs 22
cts 22
cp 1
rs 6.7272
cc 7
eloc 19
nc 8
nop 1
crap 7
1
<?php
2
3
/*
4
 * This file is part of the ChrisyueAutoJsonResponseBundle package.
5
 *
6
 * (c) Chrisyue <http://chrisyue.com/>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Chrisyue\Bundle\AutoJsonResponseBundle\EventListener;
13
14
use Symfony\Component\HttpFoundation\JsonResponse;
15
use Symfony\Component\HttpFoundation\Response;
16
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
17
use Symfony\Component\Serializer\Serializer;
18
19
class AutoJsonResponseListener
20
{
21
    private $serializer;
22
23 9
    public function __construct(Serializer $serializer = null)
24
    {
25 9
        $this->serializer = $serializer;
26 9
    }
27
28 9
    public function onKernelView(GetResponseForControllerResultEvent $event)
29
    {
30 9
        if (!$event->isMasterRequest()) {
31 1
            return;
32
        }
33
34 8
        $request = $event->getRequest();
35 8
        if ('json' !== $request->getRequestFormat()) {
36 1
            return;
37
        }
38
39 7
        $result = $event->getControllerResult();
40 7
        if (null === $result) {
41 1
            $event->setResponse(new JsonResponse(null, 204));
42
43 1
            return;
44
        }
45
46 6
        if ($result instanceof Response) {
47 1
            return;
48
        }
49
50 5
        $response = new JsonResponse();
51
52 5
        if ($request->isMethod('POST')) {
53 2
            $response->setStatusCode(201);
54 2
        }
55
56 5
        if (is_object($result)) {
57 3
            $result = $this->getSerializer()->normalize($result);
58 2
        }
59
60 4
        $response->setData($result);
61
62 4
        $event->setResponse($response);
63 4
    }
64
65 3
    private function getSerializer()
66
    {
67 3
        if (null === $this->serializer) {
68 1
            throw new \BadMethodCallException('You should enable `serializer` in `config.yml` to get this work');
69
        }
70
71 2
        return $this->serializer;
72
    }
73
}
74