-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonResponder.php
57 lines (47 loc) · 1.81 KB
/
JsonResponder.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<?php
namespace AdrBundle\Response\Responder;
use AdrBundle\Attribute\SerializerContext;
use AdrBundle\Response\Contract\ResponderInterface;
use Psr\Container\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Contracts\Service\Attribute\Required;
use Symfony\Contracts\Service\ServiceSubscriberInterface;
class JsonResponder implements ResponderInterface, ServiceSubscriberInterface
{
private ContainerInterface $container;
#[Required]
public function setContainer(ContainerInterface $container): ?ContainerInterface
{
$previous = $this->container ?? null;
$this->container = $container;
return $previous;
}
public function __invoke(mixed $data, array $attributes, array $responseArguments): JsonResponse
{
if ($this->container->has('serializer')) {
$responseArguments['json'] = true;
$context = [];
if (\array_key_exists(SerializerContext::class, $attributes)) {
/** @var SerializerContext $contextAttribute */
$contextAttribute = $attributes[SerializerContext::class];
$context = $contextAttribute->context;
}
$json = $this->container->get('serializer')
->serialize($data, 'json', array_merge([
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS,
],
$context
));
return new JsonResponse($json, ...$responseArguments);
}
return new JsonResponse($data, ...$responseArguments);
}
#[\Override]
public static function getSubscribedServices(): array
{
return [
'serializer' => '?'.SerializerInterface::class,
];
}
}