1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace W2w\Lib\Apie\Plugins\Core\Serializers; |
4
|
|
|
|
5
|
|
|
use Psr\Http\Message\ResponseInterface; |
6
|
|
|
use Symfony\Component\Serializer\Serializer; |
7
|
|
|
use W2w\Lib\Apie\Interfaces\FormatRetrieverInterface; |
8
|
|
|
use W2w\Lib\Apie\Interfaces\ResourceSerializerInterface; |
9
|
|
|
use Zend\Diactoros\Response\TextResponse; |
10
|
|
|
|
11
|
|
|
class SymfonySerializerAdapter implements ResourceSerializerInterface |
12
|
|
|
{ |
13
|
|
|
private $serializer; |
14
|
|
|
|
15
|
|
|
private $formatRetriever; |
16
|
|
|
|
17
|
|
|
public function __construct(Serializer $serializer, FormatRetrieverInterface $formatRetriever) |
18
|
|
|
{ |
19
|
|
|
$this->serializer = $serializer; |
20
|
|
|
$this->formatRetriever = $formatRetriever; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* {@inheritDoc} |
25
|
|
|
*/ |
26
|
|
|
public function putData(object $resource, string $requestBody, string $contentType): object |
27
|
|
|
{ |
28
|
|
|
$contentFormat = $this->formatRetriever->getFormat($contentType); |
29
|
|
|
return $this->serializer->deserialize( |
|
|
|
|
30
|
|
|
$requestBody, |
31
|
|
|
get_class($resource), |
32
|
|
|
$contentFormat, |
|
|
|
|
33
|
|
|
[ |
34
|
|
|
'groups' => ['base', 'write', 'put'], |
35
|
|
|
'object_to_populate' => $resource |
36
|
|
|
] |
37
|
|
|
); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** |
41
|
|
|
* {@inheritDoc} |
42
|
|
|
*/ |
43
|
|
|
public function postData(string $resourceClass, string $requestBody, string $contentType): object |
44
|
|
|
{ |
45
|
|
|
$contentFormat = $this->formatRetriever->getFormat($contentType); |
46
|
|
|
return $this->serializer->deserialize( |
|
|
|
|
47
|
|
|
$requestBody, |
48
|
|
|
$resourceClass, |
49
|
|
|
$contentFormat, |
|
|
|
|
50
|
|
|
[ |
51
|
|
|
'groups' => ['base', 'write', 'post'], |
52
|
|
|
] |
53
|
|
|
); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* {@inheritDoc} |
58
|
|
|
*/ |
59
|
|
|
public function toResponse(?object $resource, string $acceptHeader): ResponseInterface |
60
|
|
|
{ |
61
|
|
|
$format = $this->formatRetriever->getFormat($acceptHeader ?? 'application/json'); |
62
|
|
|
$contentType = $this->formatRetriever->getContentType($format); |
|
|
|
|
63
|
|
|
$response = $this->serializer->serialize($resource, $format, ['groups' => ['base', 'read', 'get']]); |
|
|
|
|
64
|
|
|
|
65
|
|
|
return new TextResponse($response, is_null($resource) ? 204 : 200, ['content-type' => $contentType]); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* {@inheritDoc} |
70
|
|
|
*/ |
71
|
|
|
public function normalize(?object $resource, string $acceptHeader) |
72
|
|
|
{ |
73
|
|
|
$format = $this->formatRetriever->getFormat($acceptHeader ?? 'application/json'); |
74
|
|
|
return $this->serializer->normalize($resource, $format, ['groups' => ['base', 'read', 'get']]); |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|