-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSimpleNormalizer.php
More file actions
228 lines (196 loc) · 5.99 KB
/
SimpleNormalizer.php
File metadata and controls
228 lines (196 loc) · 5.99 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
<?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\InvalidMaxDepthException;
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.
*
* @final
*/
class SimpleNormalizer
{
private readonly ?ClassMetadataFactory $doctrineMetadata;
private const int DEFAULT_MAX_DEPTH = 128;
/** @var array<class-string, class-string> */
private array $normalizedClassNames = [];
/**
* @param ServiceLocator<SimpleObjectNormalizerInterface> $objectNormalizers
*/
public function __construct (
private readonly ServiceLocator $objectNormalizers,
private readonly bool $isDebug = false,
private readonly ?ValidJsonVerifier $validJsonVerifier = null,
?EntityManagerInterface $entityManager = null,
private readonly int $maxDepth = self::DEFAULT_MAX_DEPTH,
)
{
if ($this->maxDepth < 1)
{
throw new InvalidMaxDepthException("The max depth must be at least 1.");
}
$this->doctrineMetadata = $entityManager?->getMetadataFactory();
}
/**
*/
public function normalize (mixed $value, array $context = []) : mixed
{
$stack = [];
$normalizedValue = $this->recursiveNormalize($value, $context, $stack);
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue, $this->maxDepth);
}
return $normalizedValue;
}
/**
*/
public function normalizeArray (array $array, array $context = []) : array
{
$stack = [];
$normalizedValue = $this->recursiveNormalizeArray($array, $context, $stack);
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue, $this->maxDepth);
}
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.
$stack = [];
$normalizedValue = $this->recursiveNormalizeArray($array, $context, $stack) ?: new \stdClass();
if ($this->isDebug)
{
$this->validJsonVerifier?->ensureValidOnlyJsonTypes($normalizedValue, $this->maxDepth);
}
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, array &$stack) : mixed
{
if (null === $value || \is_scalar($value))
{
return $value;
}
if (\count($stack) >= $this->maxDepth)
{
$extendedStack = [...$stack, get_debug_type($value)];
throw new UnsupportedTypeException(\sprintf(
"Maximum normalization depth of %d exceeded when normalizing type %s in stack %s",
$this->maxDepth,
get_debug_type($value),
implode(" > ", array_reverse($extendedStack)),
));
}
$stack[] = get_debug_type($value);
try
{
if (\is_array($value))
{
return $this->recursiveNormalizeArray($value, $context, $stack);
}
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 && [] === (array) $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' in stack %s",
get_debug_type($value),
implode(" > ", array_reverse($stack)),
), 0, $exception);
}
}
throw new UnsupportedTypeException(\sprintf(
"Can't normalize type %s in stack %s",
get_debug_type($value),
implode(" > ", array_reverse($stack)),
));
}
finally
{
array_pop($stack);
}
}
/**
* 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;
}
if (isset($this->normalizedClassNames[$className]))
{
return $this->normalizedClassNames[$className];
}
return $this->normalizedClassNames[$className] = $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 &$stack) : array
{
$result = [];
$isList = array_is_list($array);
foreach ($array as $key => $value)
{
$normalized = $this->recursiveNormalize($value, $context, $stack);
// 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;
}
}