1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace ScayTrase\Api\Cruds\Listener; |
4
|
|
|
|
5
|
|
|
use Doctrine\Common\Collections\Collection; |
6
|
|
|
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent; |
7
|
|
|
use Symfony\Component\Routing\RouterInterface; |
8
|
|
|
use Symfony\Component\Serializer\Normalizer\NormalizerInterface; |
9
|
|
|
|
10
|
|
|
final class ResponseNormalizerListener |
11
|
|
|
{ |
12
|
|
|
use CrudsRequestCheckerTrait; |
13
|
|
|
|
14
|
|
|
/** @var NormalizerInterface */ |
15
|
|
|
private $normalizer; |
16
|
|
|
/** @var RouterInterface */ |
17
|
|
|
private $router; |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* ResponseNormalizerListener constructor. |
21
|
|
|
* |
22
|
|
|
* @param NormalizerInterface $normalizer |
23
|
|
|
* @param RouterInterface $router |
24
|
|
|
*/ |
25
|
26 |
|
public function __construct(NormalizerInterface $normalizer, RouterInterface $router) |
26
|
|
|
{ |
27
|
26 |
|
$this->normalizer = $normalizer; |
28
|
26 |
|
$this->router = $router; |
29
|
26 |
|
} |
30
|
|
|
|
31
|
26 |
|
public function filterResponse(GetResponseForControllerResultEvent $event) |
32
|
|
|
{ |
33
|
26 |
|
if (!$this->checkRequest($event)) { |
34
|
|
|
return; |
35
|
|
|
} |
36
|
|
|
|
37
|
26 |
|
$result = $event->getControllerResult(); |
38
|
|
|
|
39
|
26 |
|
if (is_scalar($result)) { |
40
|
6 |
|
return; |
41
|
|
|
} |
42
|
|
|
|
43
|
20 |
|
$entities = $result; |
44
|
|
|
|
45
|
20 |
|
if (null === $entities) { |
46
|
4 |
|
return null; |
47
|
|
|
} |
48
|
|
|
|
49
|
16 |
|
if ($entities instanceof Collection) { |
50
|
4 |
|
$entities = $entities->toArray(); |
51
|
|
|
} |
52
|
|
|
|
53
|
16 |
|
$isArray = true; |
54
|
16 |
|
if (!is_array($entities)) { |
55
|
12 |
|
$isArray = false; |
56
|
12 |
|
$entities = [$entities]; |
57
|
|
|
} |
58
|
|
|
|
59
|
16 |
|
$options = $this->getNormalizedCrudApiOptions($event); |
60
|
16 |
|
if (!$options['enabled']) { |
61
|
|
|
return; |
62
|
|
|
} |
63
|
|
|
|
64
|
16 |
|
$context = $options['context']; |
65
|
16 |
|
foreach ($entities as &$entity) { |
66
|
16 |
|
$entity = $this->normalizer->normalize($entity, null, $context); |
67
|
|
|
} |
68
|
16 |
|
unset($entity); |
69
|
|
|
|
70
|
16 |
|
$entities = $isArray ? $entities : array_shift($entities); |
71
|
|
|
|
72
|
16 |
|
$event->setControllerResult($entities); |
73
|
16 |
|
} |
74
|
|
|
|
75
|
|
|
/** {@inheritdoc} */ |
76
|
|
|
protected function getRouter() |
77
|
|
|
{ |
78
|
|
|
return $this->router; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|