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
|
|
|
private $options; |
23
|
|
|
|
24
|
9 |
|
public function __construct(Serializer $serializer = null, array $options = []) |
25
|
|
|
{ |
26
|
9 |
|
$this->serializer = $serializer; |
27
|
9 |
|
$this->options = $options; |
28
|
9 |
|
} |
29
|
|
|
|
30
|
9 |
|
public function onKernelView(GetResponseForControllerResultEvent $event) |
31
|
|
|
{ |
32
|
9 |
|
if (!$event->isMasterRequest()) { |
33
|
1 |
|
return; |
34
|
|
|
} |
35
|
|
|
|
36
|
8 |
|
$request = $event->getRequest(); |
37
|
8 |
|
if ('json' !== $request->getRequestFormat()) { |
38
|
1 |
|
return; |
39
|
|
|
} |
40
|
|
|
|
41
|
7 |
|
$result = $event->getControllerResult(); |
42
|
7 |
|
if (null === $result) { |
43
|
1 |
|
$event->setResponse(new JsonResponse(null, 204)); |
44
|
|
|
|
45
|
1 |
|
return; |
46
|
|
|
} |
47
|
|
|
|
48
|
6 |
|
if ($result instanceof Response) { |
49
|
1 |
|
return; |
50
|
|
|
} |
51
|
|
|
|
52
|
5 |
|
$response = new JsonResponse(); |
53
|
|
|
|
54
|
5 |
|
if ($request->isMethod('POST')) { |
55
|
2 |
|
$response->setStatusCode(201); |
56
|
2 |
|
} |
57
|
|
|
|
58
|
5 |
|
if (!is_scalar($result)) { |
59
|
3 |
|
$result = $this->getSerializer()->normalize($result, null, [ |
|
|
|
|
60
|
2 |
|
'groups' => $this->options['serialization_default_groups'], |
61
|
2 |
|
]); |
62
|
2 |
|
} |
63
|
|
|
|
64
|
4 |
|
$response->setData($result); |
65
|
|
|
|
66
|
4 |
|
$event->setResponse($response); |
67
|
4 |
|
} |
68
|
|
|
|
69
|
3 |
|
private function getSerializer() |
70
|
|
|
{ |
71
|
3 |
|
if (null === $this->serializer) { |
72
|
1 |
|
throw new \BadMethodCallException('You should enable `serializer` in `config.yml` to get this work'); |
73
|
|
|
} |
74
|
|
|
|
75
|
2 |
|
return $this->serializer; |
76
|
|
|
} |
77
|
|
|
} |
78
|
|
|
|
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.