|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Serializer\Normalizer; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Serializer\Exception\UnexpectedValueException; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* NormalizerLoader |
|
9
|
|
|
*/ |
|
10
|
|
|
class NormalizerLoader implements NormalizerLoaderInterface |
|
11
|
|
|
{ |
|
12
|
|
|
/** |
|
13
|
|
|
* Normalizers associated to a class name |
|
14
|
|
|
* |
|
15
|
|
|
* @var NormalizerInterface[] |
|
16
|
|
|
*/ |
|
17
|
|
|
private $cached = []; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* Available normalizers |
|
21
|
|
|
* |
|
22
|
|
|
* @var NormalizerInterface[] |
|
23
|
|
|
*/ |
|
24
|
|
|
private $normalizers = []; |
|
25
|
|
|
|
|
26
|
|
|
/** |
|
27
|
|
|
* NormalizerLoader constructor. |
|
28
|
|
|
* |
|
29
|
|
|
* @param NormalizerInterface[] $normalizers |
|
30
|
|
|
*/ |
|
31
|
206 |
|
public function __construct(array $normalizers) |
|
32
|
|
|
{ |
|
33
|
206 |
|
foreach ($normalizers as $normalizer) { |
|
34
|
200 |
|
$this->addNormalizer($normalizer); |
|
35
|
|
|
} |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
/** |
|
39
|
|
|
* {@inheritdoc} |
|
40
|
|
|
*/ |
|
41
|
202 |
|
public function addNormalizer(NormalizerInterface $normalizer) |
|
42
|
|
|
{ |
|
43
|
202 |
|
if ($normalizer instanceof AutoRegisterInterface) { |
|
44
|
18 |
|
$normalizer->registerTo($this); |
|
45
|
|
|
} else { |
|
46
|
184 |
|
$this->normalizers[] = $normalizer; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
202 |
|
return $this; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* {@inheritdoc} |
|
54
|
|
|
*/ |
|
55
|
192 |
|
public function associate($className, NormalizerInterface $normalizer) |
|
56
|
|
|
{ |
|
57
|
192 |
|
$this->cached[$className] = $normalizer; |
|
58
|
|
|
|
|
59
|
192 |
|
return $this; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* {@inheritdoc} |
|
64
|
|
|
*/ |
|
65
|
196 |
|
public function getNormalizer($className): NormalizerInterface |
|
66
|
|
|
{ |
|
67
|
196 |
|
if (is_object($className)) { |
|
68
|
118 |
|
$className = get_class($className); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
// Normalizer is already loaded |
|
72
|
196 |
|
if (isset($this->cached[$className])) { |
|
73
|
60 |
|
return $this->cached[$className]; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
// Find from resolvers |
|
77
|
176 |
|
foreach ($this->normalizers as $normalizer) { |
|
78
|
174 |
|
if ($normalizer->supports($className)) { |
|
79
|
172 |
|
$this->associate($className, $normalizer); |
|
80
|
|
|
|
|
81
|
172 |
|
return $normalizer; |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
4 |
|
throw new UnexpectedValueException('Cannot find normalizer for the class "'.$className.'"'); |
|
86
|
|
|
} |
|
87
|
|
|
} |
|
88
|
|
|
|