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
|
|
|
public function __construct(Serializer $serializer = null) |
24
|
|
|
{ |
25
|
|
|
$this->serializer = $serializer; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function onKernelView(GetResponseForControllerResultEvent $event) |
29
|
|
|
{ |
30
|
|
|
if (!$event->isMasterRequest()) { |
31
|
|
|
return; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
$request = $event->getRequest(); |
35
|
|
|
if ('json' !== $request->getRequestFormat()) { |
36
|
|
|
return; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$result = $event->getControllerResult(); |
40
|
|
|
if (null === $result) { |
41
|
|
|
$event->setResponse(new JsonResponse(null, 204)); |
42
|
|
|
|
43
|
|
|
return; |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
if ($result instanceof Response) { |
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
$response = new JsonResponse(); |
51
|
|
|
|
52
|
|
|
if ($request->isMethod('POST')) { |
53
|
|
|
$response->setStatusCode(201); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
if (is_object($result)) { |
57
|
|
|
$result = $this->getSerializer()->normalize($result); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
$response->setData($result); |
61
|
|
|
|
62
|
|
|
$event->setResponse($response); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
private function getSerializer() |
66
|
|
|
{ |
67
|
|
|
if (null === $this->serializer) { |
68
|
|
|
throw new \BadMethodCallException('You should enable `serializer` in `config.yml` to get this work'); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return $this->serializer; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|