-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAbstractNormalizer.php
More file actions
376 lines (310 loc) · 12.6 KB
/
AbstractNormalizer.php
File metadata and controls
376 lines (310 loc) · 12.6 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
<?php
declare(strict_types=1);
namespace BowlOfSoup\NormalizerBundle\Service\Normalize;
use BowlOfSoup\NormalizerBundle\Annotation\Normalize;
use BowlOfSoup\NormalizerBundle\Annotation\Translate;
use BowlOfSoup\NormalizerBundle\Exception\BosNormalizerException;
use BowlOfSoup\NormalizerBundle\Model\Context;
use BowlOfSoup\NormalizerBundle\Model\ObjectCache;
use BowlOfSoup\NormalizerBundle\Service\Extractor\AnnotationExtractor;
use BowlOfSoup\NormalizerBundle\Service\Extractor\ClassExtractor;
use BowlOfSoup\NormalizerBundle\Service\ObjectHelper;
use Doctrine\Common\Collections\Collection;
use Symfony\Contracts\Translation\TranslatorInterface;
abstract class AbstractNormalizer
{
protected const TYPE_DATETIME = 'datetime';
protected const TYPE_OBJECT = 'object';
protected const TYPE_COLLECTION = 'collection';
/** @var \BowlOfSoup\NormalizerBundle\Service\Normalizer */
protected $sharedNormalizer;
/** @var \BowlOfSoup\NormalizerBundle\Service\Extractor\ClassExtractor */
protected $classExtractor;
/** @var \Symfony\Contracts\Translation\TranslatorInterface */
protected $translator;
/** @var \BowlOfSoup\NormalizerBundle\Service\Extractor\AnnotationExtractor */
protected $annotationExtractor;
/** @var string */
protected $group;
/** @var \BowlOfSoup\NormalizerBundle\Model\Context */
protected $context;
/** @var array */
protected $currentPath = [];
/** @var int */
protected $maxDepth;
/** @var array */
protected $processedDepthObjects = [];
/** @var int */
protected $processedDepth = 0;
/** @var \BowlOfSoup\NormalizerBundle\Model\Store[] */
protected $nameAndClassStore;
public function __construct(
ClassExtractor $classExtractor,
TranslatorInterface $translator,
AnnotationExtractor $annotationExtractor
) {
$this->classExtractor = $classExtractor;
$this->translator = $translator;
$this->annotationExtractor = $annotationExtractor;
}
public function cleanUp(): void
{
$this->currentPath = [];
$this->maxDepth = null;
}
public function cleanUpObject(string $name): void
{
// Reset name and class store for given object.
$this->nameAndClassStore[$name] = null;
}
public function cleanUpSession(): void
{
$this->annotationExtractor->cleanUp();
}
protected function hasMaxDepth(): bool
{
return null !== $this->maxDepth && ($this->processedDepth + 1) > $this->maxDepth;
}
/**
* This function deals with processing $context, which due to compatibility can be either a group or a context model.
* Refactor this in the next major version.
*
* @param \BowlOfSoup\NormalizerBundle\Model\Context|string|null $context
*/
protected function handleContext($context): void
{
if (is_string($context)) {
// Group has been given instead of context. Set group on context.
$context = (new Context())->setGroup($context);
} elseif (!$context instanceof Context) {
// No context has been given, instantiate empty context.
$context = new Context();
}
$this->group = $context->getGroup();
$this->context = $context;
}
/**
* @throws \BowlOfSoup\NormalizerBundle\Exception\BosNormalizerException
*
* @return int|string
*/
protected function getValueForMaxDepth(object $object)
{
$value = $this->classExtractor->getId($object);
if (null === $value) {
throw new BosNormalizerException('Maximal depth reached, but no identifier found. ' . 'Prevent this by adding a getId() method to ' . get_class($object));
}
return $value;
}
/**
* Get class annotation for specified group.
*
* First group entry will be used, duplicate definitions will be gracefully ignored.
*
* @throws \ReflectionException
*/
protected function getClassAnnotation(object $object): ?Normalize
{
$classAnnotations = $this->annotationExtractor->getAnnotationsForClass(Normalize::class, $object);
if (empty($classAnnotations)) {
return null;
}
/** @var \BowlOfSoup\NormalizerBundle\Annotation\Normalize $classAnnotation */
foreach ($classAnnotations as $classAnnotation) {
if ($classAnnotation->isGroupValidForConstruct($this->group)) {
$this->maxDepth = $classAnnotation->getMaxDepth();
return $classAnnotation;
}
}
return null;
}
/**
* @param mixed $value
*/
protected function skipEmptyValue($value, Normalize $annotation, Normalize $classAnnotation = null): bool
{
$skipEmpty = (null !== $classAnnotation ? $classAnnotation->getSkipEmpty() : false);
return empty($value) && (true === $skipEmpty || true === $annotation->getSkipEmpty());
}
/**
* Normalize a referenced object, handles circular references.
*
* @throws \BowlOfSoup\NormalizerBundle\Exception\BosNormalizerException
* @throws \ReflectionException
*/
protected function normalizeReferencedObject(object $object, object $parentObject): ?array
{
$normalizedConstruct = null;
$objectName = get_class($object);
if (is_object($object) && !$this->isCircularReference($object, $objectName)) {
$normalizedConstruct = $this->sharedNormalizer->normalizeObject($object, $this->context);
if (empty($normalizedConstruct)) {
return null;
}
}
if (empty($normalizedConstruct)) {
$normalizedConstruct = $this->classExtractor->getId($object);
if (null === $normalizedConstruct) {
throw new BosNormalizerException('Circular reference on: ' . $objectName . ' called from: ' . get_class($parentObject) . '. If possible, prevent this by adding a getId() method to ' . $objectName);
}
return ['id' => $normalizedConstruct];
}
return $normalizedConstruct;
}
/**
* Normalize a property with 'collection' type.
*
* A Collection can be anything that is iteratable, such as a Doctrine ArrayCollection, or just an array.
*
* @param mixed $propertyValue
*
* @throws \BowlOfSoup\NormalizerBundle\Exception\BosNormalizerException
* @throws \ReflectionException
*/
protected function normalizeReferencedCollection($propertyValue, Normalize $propertyAnnotation): ?array
{
$normalizedCollection = [];
if (!$propertyValue instanceof Collection && !is_array($propertyValue)) {
return null;
}
$annotationCallback = $propertyAnnotation->getCallback();
foreach ($propertyValue as $collectionItem) {
if (!is_object($collectionItem)) {
// If not an object, annotation property type="collection" was useless.
continue;
}
if ($this->hasMaxDepth()) {
$normalizedCollection[] = $this->getValueForMaxDepth($collectionItem);
continue;
}
++$this->processedDepth;
if (!empty($annotationCallback) && is_callable([$collectionItem, $annotationCallback])) {
$normalizedCollection[] = $this->handleCallbackResult(
$collectionItem->$annotationCallback(),
$propertyAnnotation
);
} else {
$normalizedObject = $this->sharedNormalizer->normalizeObject($collectionItem, $this->context);
$normalizedCollection[] = (!empty($normalizedObject) ? $normalizedObject : null);
}
--$this->processedDepth;
}
return $normalizedCollection;
}
/**
* @param mixed $propertyValue
*
* @throws \BowlOfSoup\NormalizerBundle\Exception\BosNormalizerException
* @throws \ReflectionException
*
* @return array|string|null
*/
protected function handleCallbackResult($propertyValue, Normalize $propertyAnnotation)
{
if (!$propertyAnnotation->mustNormalizeCallbackResult()) {
return $propertyValue;
}
if ($propertyValue instanceof Collection || is_array($propertyValue)) {
$allObjects = true;
$normalizedCollection = [];
foreach ($propertyValue as $item) {
if (!is_object($item)) {
// Values that are not objects will be skipped/cannot be normalized.
$allObjects = false;
continue;
}
$normalizedCollection[] = $this->sharedNormalizer->normalizeObject($item, $this->context);
}
if (empty($normalizedCollection) && !$allObjects) {
return $propertyValue;
}
return $normalizedCollection;
} elseif (is_object($propertyValue)) {
return $this->sharedNormalizer->normalizeObject($propertyValue, $this->context);
}
return $propertyValue;
}
/**
* @param \BowlOfSoup\NormalizerBundle\Annotation\Translate[]|array
*/
protected function getTranslationAnnotation(array $translateAnnotations, $emptyGroup = false): ?Translate
{
if (empty($translateAnnotations)) {
return null;
}
$group = ($emptyGroup) ? null : $this->group;
$translationAnnotation = null;
/** @var \BowlOfSoup\NormalizerBundle\Annotation\Translate $translateAnnotation */
foreach ($translateAnnotations as $translateAnnotation) {
if (!$translateAnnotation->isGroupValidForConstruct($group)) {
continue;
}
// By overwriting the return variable, the last valid annotation on the property/method is taken.
$translationAnnotation = $translateAnnotation;
}
// Annotation found, but no explicit group. Try again with no group.
if (null === $translationAnnotation) {
// Don't try again if get with no group given to prevent
return (!$emptyGroup) ? $this->getTranslationAnnotation($translateAnnotations, true) : null;
}
return $translationAnnotation;
}
/**
* @param mixed $value
*
* @return mixed
*/
protected function translateValue($value, Translate $translationAnnotation)
{
if (!is_string($value)) {
return $value;
}
return $this->translator->trans($value, [], $translationAnnotation->getDomain(), $translationAnnotation->getLocale());
}
/**
* Checks a construct (property/method) against an existing entry in the store.
* If found, the construct has already been normalized.
*/
protected function isAlreadyNormalizedForObject(string $constructName, string $baseObjectName, string $actualObjectName): bool
{
if (array_key_exists($baseObjectName, $this->nameAndClassStore) && $this->nameAndClassStore[$baseObjectName]->has($constructName)) {
$object = $this->nameAndClassStore[$baseObjectName]->get($constructName);
return is_subclass_of($object, $actualObjectName);
}
return false;
}
protected function storeNormalizedConstructForObject(string $constructName, string $baseObjectName, object $object): void
{
$this->nameAndClassStore[$baseObjectName]->set($constructName, $object);
}
protected function decreaseCurrentPath(): void
{
if (is_array($this->currentPath) && count($this->currentPath) > 1) {
array_pop($this->currentPath);
} else {
$this->currentPath = [];
}
}
protected function canCurrentPathBeIncluded(?string $pathType): bool
{
if ($pathType !== static::TYPE_OBJECT && $pathType !== static::TYPE_COLLECTION) {
return true;
}
if ($this->context->getMaxDepth() === (count($this->currentPath) - 1)) {
return false;
}
if (!$this->context->hasIncludes()) {
return true;
}
$pathThatIsBeingNormalized = implode('.', $this->currentPath);
return $this->context->hasInclude($pathThatIsBeingNormalized);
}
private function isCircularReference(object $object, string $objectName): bool
{
$objectIdentifier = ObjectHelper::getObjectIdentifier($object);
if (isset($this->processedDepthObjects[$objectName]) && $this->processedDepth <= $this->processedDepthObjects[$objectName]) {
return false;
}
return ObjectCache::hasObjectByNameAndIdentifier($objectName, $objectIdentifier);
}
}