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

AutoJsonResponseListener   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 1
Metric Value
wmc 10
c 3
b 0
f 1
lcom 1
cbo 4
dl 0
loc 55
ccs 29
cts 29
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C onKernelView() 0 36 7
A getSerializer() 0 8 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