1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Chubbyphp\Serialization; |
6
|
|
|
|
7
|
|
|
use Chubbyphp\Serialization\Encoder\EncoderInterface; |
8
|
|
|
use Chubbyphp\Serialization\Normalizer\NormalizerContextInterface; |
9
|
|
|
use Chubbyphp\Serialization\Normalizer\NormalizerInterface; |
10
|
|
|
|
11
|
|
|
final class Serializer implements SerializerInterface |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var NormalizerInterface |
15
|
|
|
*/ |
16
|
|
|
private $normalizer; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var EncoderInterface |
20
|
|
|
*/ |
21
|
|
|
private $encoder; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param NormalizerInterface $normalizer |
25
|
|
|
* @param EncoderInterface $encoder |
26
|
|
|
*/ |
27
|
|
|
public function __construct(NormalizerInterface $normalizer, EncoderInterface $encoder) |
28
|
|
|
{ |
29
|
2 |
|
$this->normalizer = $normalizer; |
30
|
|
|
$this->encoder = $encoder; |
31
|
2 |
|
} |
32
|
2 |
|
|
33
|
2 |
|
/** |
34
|
|
|
* @param object $object |
35
|
|
|
* @param string $contentType |
36
|
|
|
* @param NormalizerContextInterface $context |
37
|
|
|
* @param string $path |
38
|
|
|
* |
39
|
|
|
* @return string |
40
|
|
|
*/ |
41
|
|
|
public function serialize( |
42
|
|
|
$object, |
43
|
|
|
string $contentType, |
44
|
2 |
|
NormalizerContextInterface $context = null, |
45
|
|
|
$path = '' |
46
|
2 |
|
): string { |
47
|
1 |
|
return $this->encoder->encode($this->normalizer->normalize($object, $context, $path), $contentType); |
48
|
|
|
} |
49
|
1 |
|
|
50
|
|
|
/** |
51
|
|
|
* @param object $object |
52
|
1 |
|
* @param NormalizerContextInterface|null $context |
53
|
|
|
* @param string $path |
54
|
1 |
|
* |
55
|
|
|
* @return array |
56
|
1 |
|
* |
57
|
1 |
|
* @throws SerializerLogicException |
58
|
1 |
|
*/ |
59
|
|
|
public function normalize($object, NormalizerContextInterface $context = null, string $path = ''): array |
60
|
1 |
|
{ |
61
|
|
|
return $this->normalizer->normalize($object, $context, $path); |
62
|
1 |
|
} |
63
|
1 |
|
|
64
|
|
|
/** |
65
|
|
|
* @return string[] |
66
|
1 |
|
*/ |
67
|
1 |
|
public function getContentTypes(): array |
68
|
|
|
{ |
69
|
|
|
return $this->encoder->getContentTypes(); |
70
|
1 |
|
} |
71
|
|
|
|
72
|
1 |
|
/** |
73
|
|
|
* @param array $data |
74
|
|
|
* @param string $contentType |
75
|
|
|
* |
76
|
|
|
* @return string |
77
|
|
|
* |
78
|
|
|
* @throws SerializerLogicException |
79
|
|
|
*/ |
80
|
|
|
public function encode(array $data, string $contentType): string |
81
|
|
|
{ |
82
|
|
|
return $this->encoder->encode($data, $contentType); |
83
|
1 |
|
} |
84
|
|
|
} |
85
|
|
|
|