-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleNormalizer.php
More file actions
189 lines (162 loc) · 4.78 KB
/
SimpleNormalizer.php
File metadata and controls
189 lines (162 loc) · 4.78 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
<?php declare(strict_types=1);
namespace Torr\SimpleNormalizer\Normalizer;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Mapping\ClassMetadataFactory;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\DependencyInjection\ServiceLocator;
use Torr\SimpleNormalizer\Exception\ObjectTypeNotSupportedException;
use Torr\SimpleNormalizer\Exception\UnsupportedTypeException;
use Torr\SimpleNormalizer\Normalizer\Validator\ValidJsonVerifier;
/**
* The normalizer to use in your app.
*
* Can't be readonly, as it needs to be mock-able.
*
* The verifier is done on the top-level of every method (instead of at the point where the invalid values could occur
* = the object normalizers), as this way we can provide a full path to the invalid element in the JSON.
*
* @readonly
*
* @final
*/
class SimpleNormalizer
{
private readonly ?ClassMetadataFactory $doctrineMetadata;
/**
* @param ServiceLocator<SimpleObjectNormalizerInterface> $objectNormalizers
*/
public function __construct (
private readonly ServiceLocator $objectNormalizers,
private readonly bool $isDebug = false,
private readonly ?ValidJsonVerifier $validJsonVerifier = null,
?EntityManagerInterface $entityManager = null,
)
{
$this->doctrineMetadata = $entityManager?->getMetadataFactory();
}
/**
*/
public function normalize (mixed $value, array $context = []) : mixed
{
$normalizedValue = $this->recursiveNormalize($value, $context);
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue);
}
return $normalizedValue;
}
/**
*/
public function normalizeArray (array $array, array $context = []) : array
{
$normalizedValue = $this->recursiveNormalizeArray($array, $context);
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue);
}
return $normalizedValue;
}
/**
* Normalizes a map of values.
* Will JSON-encode to `{}` when empty.
*/
public function normalizeMap (array $array, array $context = []) : array|\stdClass
{
// return stdClass if the array is empty here, as it will be automatically normalized to `{}` in JSON.
$normalizedValue = $this->recursiveNormalizeArray($array, $context) ?: new \stdClass();
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue);
}
return $normalizedValue;
}
/**
* The actual normalize logic, that recursively normalizes the value.
* It must never call one of the public methods above and just normalizes the value.
*/
private function recursiveNormalize (mixed $value, array $context = []) : mixed
{
if (null === $value || \is_scalar($value))
{
return $value;
}
if (\is_array($value))
{
return $this->recursiveNormalizeArray($value, $context);
}
if (\is_object($value))
{
// Allow empty stdClass as a way to force a JSON {} instead of an
// array which would encode to []
if ($value instanceof \stdClass && [] === get_object_vars($value))
{
return $value;
}
try
{
$className = $this->normalizeClassName($value::class);
$normalizer = $this->objectNormalizers->get($className);
\assert($normalizer instanceof SimpleObjectNormalizerInterface);
return $normalizer->normalize($value, $context, $this);
}
catch (ServiceNotFoundException $exception)
{
throw new ObjectTypeNotSupportedException(\sprintf(
"Can't normalize type %s",
get_debug_type($value),
), 0, $exception);
}
}
throw new UnsupportedTypeException(\sprintf(
"Can't normalize type %s",
get_debug_type($value),
));
}
/**
* Normalizes the class name
*
* @param class-string $className
*
* @return class-string
*/
private function normalizeClassName (string $className) : string
{
// if there is no doctrine, just return
if (null === $this->doctrineMetadata)
{
return $className;
}
return $this->doctrineMetadata->hasMetadataFor($className)
? $this->doctrineMetadata->getMetadataFor($className)->getName()
: $className;
}
/**
* The actual customized normalization logic for arrays, that recursively normalizes the value.
* It must never call one of the public methods above and just normalizes the value.
*/
private function recursiveNormalizeArray (array $array, array $context = []) : array
{
$result = [];
$isList = array_is_list($array);
foreach ($array as $key => $value)
{
$normalized = $this->recursiveNormalize($value, $context);
// if the array was a list and the normalized value is null, just filter it out
if ($isList && null === $normalized)
{
continue;
}
if ($isList)
{
// for list: reindex without holes
$result[] = $normalized;
}
else
{
// for map: keep key
$result[$key] = $normalized;
}
}
return $result;
}
}