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

AutoJsonResponseListener::getSerializer()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
ccs 4
cts 4
cp 1
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
crap 2
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