-
-
Notifications
You must be signed in to change notification settings - Fork 892
/
Copy pathAbstractItemNormalizer.php
896 lines (758 loc) · 37.2 KB
/
AbstractItemNormalizer.php
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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Serializer;
use ApiPlatform\Core\Api\IriConverterInterface;
use ApiPlatform\Core\Api\ResourceClassResolverInterface;
use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
use ApiPlatform\Core\DataTransformer\DataTransformerInitializerInterface;
use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
use ApiPlatform\Core\Exception\InvalidArgumentException;
use ApiPlatform\Core\Exception\InvalidValueException;
use ApiPlatform\Core\Exception\ItemNotFoundException;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
use ApiPlatform\Core\Security\ResourceAccessCheckerInterface;
use ApiPlatform\Core\Util\ClassInfoTrait;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Exception\LogicException;
use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
use Symfony\Component\Serializer\Exception\RuntimeException;
use Symfony\Component\Serializer\Exception\UnexpectedValueException;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
/**
* Base item normalizer.
*
* @author Kévin Dunglas <[email protected]>
*/
abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
{
use ClassInfoTrait;
use ContextTrait;
use InputOutputMetadataTrait;
public const IS_TRANSFORMED_TO_SAME_CLASS = 'is_transformed_to_same_class';
protected $propertyNameCollectionFactory;
protected $propertyMetadataFactory;
protected $iriConverter;
protected $resourceClassResolver;
protected $resourceAccessChecker;
protected $propertyAccessor;
protected $itemDataProvider;
protected $allowPlainIdentifiers;
protected $dataTransformers = [];
protected $localCache = [];
public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory, PropertyMetadataFactoryInterface $propertyMetadataFactory, IriConverterInterface $iriConverter, ResourceClassResolverInterface $resourceClassResolver, PropertyAccessorInterface $propertyAccessor = null, NameConverterInterface $nameConverter = null, ClassMetadataFactoryInterface $classMetadataFactory = null, ItemDataProviderInterface $itemDataProvider = null, bool $allowPlainIdentifiers = false, array $defaultContext = [], iterable $dataTransformers = [], ResourceMetadataFactoryInterface $resourceMetadataFactory = null, ResourceAccessCheckerInterface $resourceAccessChecker = null)
{
if (!isset($defaultContext['circular_reference_handler'])) {
$defaultContext['circular_reference_handler'] = function ($object) {
return $this->iriConverter->getIriFromItem($object);
};
}
if (!interface_exists(AdvancedNameConverterInterface::class) && method_exists($this, 'setCircularReferenceHandler')) {
$this->setCircularReferenceHandler($defaultContext['circular_reference_handler']);
}
parent::__construct($classMetadataFactory, $nameConverter, null, null, \Closure::fromCallable([$this, 'getObjectClass']), $defaultContext);
$this->propertyNameCollectionFactory = $propertyNameCollectionFactory;
$this->propertyMetadataFactory = $propertyMetadataFactory;
$this->iriConverter = $iriConverter;
$this->resourceClassResolver = $resourceClassResolver;
$this->propertyAccessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
$this->itemDataProvider = $itemDataProvider;
$this->allowPlainIdentifiers = $allowPlainIdentifiers;
$this->dataTransformers = $dataTransformers;
$this->resourceMetadataFactory = $resourceMetadataFactory;
$this->resourceAccessChecker = $resourceAccessChecker;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function supportsNormalization($data, $format = null)
{
if (!\is_object($data)) {
return false;
}
return $this->resourceClassResolver->isResourceClass($this->getObjectClass($data));
}
/**
* {@inheritdoc}
*/
public function hasCacheableSupportsMethod(): bool
{
return true;
}
/**
* {@inheritdoc}
*
* @throws LogicException
*
* @return array|string|int|float|bool|\ArrayObject|null
*/
public function normalize($object, $format = null, array $context = [])
{
if (!($isTransformed = isset($context[self::IS_TRANSFORMED_TO_SAME_CLASS])) && $outputClass = $this->getOutputClass($this->getObjectClass($object), $context)) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
}
if ($object !== $transformed = $this->transformOutput($object, $context, $outputClass)) {
$context['api_normalize'] = true;
$context['api_resource'] = $object;
unset($context['output'], $context['resource_class']);
} else {
$context[self::IS_TRANSFORMED_TO_SAME_CLASS] = true;
}
return $this->serializer->normalize($transformed, $format, $context);
}
if ($isTransformed) {
unset($context[self::IS_TRANSFORMED_TO_SAME_CLASS]);
}
$resourceClass = $this->resourceClassResolver->getResourceClass($object, $context['resource_class'] ?? null);
$context = $this->initContext($resourceClass, $context);
$iri = $context['iri'] ?? $this->iriConverter->getIriFromItem($object);
$context['iri'] = $iri;
$context['api_normalize'] = true;
/*
* When true, converts the normalized data array of a resource into an
* IRI, if the normalized data array is empty.
*
* This is useful when traversing from a non-resource towards an attribute
* which is a resource, as we do not have the benefit of {@see PropertyMetadata::isReadableLink}.
*
* It must not be propagated to subresources, as {@see PropertyMetadata::isReadableLink}
* should take effect.
*/
$emptyResourceAsIri = $context['api_empty_resource_as_iri'] ?? false;
unset($context['api_empty_resource_as_iri']);
if (isset($context['resources'])) {
$context['resources'][$iri] = $iri;
}
$data = parent::normalize($object, $format, $context);
if ($emptyResourceAsIri && \is_array($data) && 0 === \count($data)) {
return $iri;
}
return $data;
}
/**
* {@inheritdoc}
*
* @return bool
*/
public function supportsDenormalization($data, $type, $format = null)
{
return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
}
/**
* {@inheritdoc}
*
* @return mixed
*/
public function denormalize($data, $class, $format = null, array $context = [])
{
if (null === $objectToPopulate = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
$normalizedData = is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
$class = $this->getClassDiscriminatorResolvedClass($normalizedData, $class);
}
$resourceClass = $this->resourceClassResolver->getResourceClass($objectToPopulate, $class);
$context['api_denormalize'] = true;
$context['resource_class'] = $resourceClass;
if (null !== ($inputClass = $this->getInputClass($resourceClass, $context)) && null !== ($dataTransformer = $this->getDataTransformer($data, $resourceClass, $context))) {
$dataTransformerContext = $context;
unset($context['input']);
unset($context['resource_class']);
if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
}
if ($dataTransformer instanceof DataTransformerInitializerInterface) {
$context[AbstractObjectNormalizer::OBJECT_TO_POPULATE] = $dataTransformer->initialize($inputClass, $context);
$context[AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE] = true;
}
try {
$denormalizedInput = $this->serializer->denormalize($data, $inputClass, $format, $context);
} catch (NotNormalizableValueException $e) {
throw new UnexpectedValueException('The input data is misformatted.', $e->getCode(), $e);
}
if (!\is_object($denormalizedInput)) {
throw new UnexpectedValueException('Expected denormalized input to be an object.');
}
return $dataTransformer->transform($denormalizedInput, $resourceClass, $dataTransformerContext);
}
$supportsPlainIdentifiers = $this->supportsPlainIdentifiers();
if (\is_string($data)) {
try {
return $this->iriConverter->getItemFromIri($data, $context + ['fetch_data' => true]);
} catch (ItemNotFoundException $e) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
}
} catch (InvalidArgumentException $e) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $data), $e->getCode(), $e);
}
}
}
if (!\is_array($data)) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException(sprintf('Expected IRI or document for resource "%s", "%s" given.', $resourceClass, \gettype($data)));
}
$item = $this->itemDataProvider->getItem($resourceClass, $data, null, $context + ['fetch_data' => true]);
if (null === $item) {
throw new ItemNotFoundException(sprintf('Item not found for resource "%s" with id "%s".', $resourceClass, $data));
}
return $item;
}
return parent::denormalize($data, $resourceClass, $format, $context);
}
/**
* Method copy-pasted from symfony/serializer.
* Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
*
* {@inheritdoc}
*
* @internal
*
* @return object
*/
protected function instantiateObject(array &$data, $class, array &$context, \ReflectionClass $reflectionClass, $allowedAttributes, string $format = null)
{
if (null !== $object = $this->extractObjectToPopulate($class, $context, static::OBJECT_TO_POPULATE)) {
unset($context[static::OBJECT_TO_POPULATE]);
return $object;
}
$class = $this->getClassDiscriminatorResolvedClass($data, $class);
$reflectionClass = new \ReflectionClass($class);
$constructor = $this->getConstructor($data, $class, $context, $reflectionClass, $allowedAttributes);
if ($constructor) {
$constructorParameters = $constructor->getParameters();
$params = [];
foreach ($constructorParameters as $constructorParameter) {
$paramName = $constructorParameter->name;
$key = $this->nameConverter ? $this->nameConverter->normalize($paramName, $class, $format, $context) : $paramName;
$allowed = false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName, $allowedAttributes, true));
$ignored = !$this->isAllowedAttribute($class, $paramName, $format, $context);
if ($constructorParameter->isVariadic()) {
if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
if (!\is_array($data[$paramName])) {
throw new RuntimeException(sprintf('Cannot create an instance of %s from serialized data because the variadic parameter %s can only accept an array.', $class, $constructorParameter->name));
}
$params = array_merge($params, $data[$paramName]);
}
} elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key, $data))) {
$params[] = $this->createConstructorArgument($data[$key], $key, $constructorParameter, $context, $format);
// Don't run set for a parameter passed to the constructor
unset($data[$key]);
} elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
$params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
} elseif ($constructorParameter->isDefaultValueAvailable()) {
$params[] = $constructorParameter->getDefaultValue();
} else {
throw new MissingConstructorArgumentsException(sprintf('Cannot create an instance of %s from serialized data because its constructor requires parameter "%s" to be present.', $class, $constructorParameter->name));
}
}
if ($constructor->isConstructor()) {
return $reflectionClass->newInstanceArgs($params);
}
return $constructor->invokeArgs(null, $params);
}
return new $class();
}
protected function getClassDiscriminatorResolvedClass(array &$data, string $class): string
{
if (null === $this->classDiscriminatorResolver || (null === $mapping = $this->classDiscriminatorResolver->getMappingForClass($class))) {
return $class;
}
if (!isset($data[$mapping->getTypeProperty()])) {
throw new RuntimeException(sprintf('Type property "%s" not found for the abstract object "%s"', $mapping->getTypeProperty(), $class));
}
$type = $data[$mapping->getTypeProperty()];
if (null === ($mappedClass = $mapping->getClassForType($type))) {
throw new RuntimeException(sprintf('The type "%s" has no mapped class for the abstract object "%s"', $type, $class));
}
return $mappedClass;
}
/**
* {@inheritdoc}
*/
protected function createConstructorArgument($parameterData, string $key, \ReflectionParameter $constructorParameter, array &$context, string $format = null)
{
return $this->createAttributeValue($constructorParameter->name, $parameterData, $format, $context);
}
/**
* {@inheritdoc}
*
* Unused in this context.
*
* @return string[]
*/
protected function extractAttributes($object, $format = null, array $context = [])
{
return [];
}
/**
* {@inheritdoc}
*
* @return array|bool
*/
protected function getAllowedAttributes($classOrObject, array $context, $attributesAsString = false)
{
$options = $this->getFactoryOptions($context);
$propertyNames = $this->propertyNameCollectionFactory->create($context['resource_class'], $options);
$allowedAttributes = [];
foreach ($propertyNames as $propertyName) {
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $propertyName, $options);
if (
$this->isAllowedAttribute($classOrObject, $propertyName, null, $context) &&
(
isset($context['api_normalize']) && $propertyMetadata->isReadable() ||
isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
)
) {
$allowedAttributes[] = $propertyName;
}
}
return $allowedAttributes;
}
/**
* {@inheritdoc}
*
* @return bool
*/
protected function isAllowedAttribute($classOrObject, $attribute, $format = null, array $context = [])
{
if (!parent::isAllowedAttribute($classOrObject, $attribute, $format, $context)) {
return false;
}
$options = $this->getFactoryOptions($context);
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $options);
$security = $propertyMetadata->getAttribute('security');
if ($this->resourceAccessChecker && $security) {
return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
'object' => $classOrObject,
]);
}
return true;
}
/**
* {@inheritdoc}
*/
protected function setAttributeValue($object, $attribute, $value, $format = null, array $context = [])
{
$this->setValue($object, $attribute, $this->createAttributeValue($attribute, $value, $format, $context));
}
/**
* Validates the type of the value. Allows using integers as floats for JSON formats.
*
* @param mixed $value
*
* @throws InvalidArgumentException
*/
protected function validateType(string $attribute, Type $type, $value, string $format = null)
{
$builtinType = $type->getBuiltinType();
if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && false !== strpos($format, 'json')) {
$isValid = \is_float($value) || \is_int($value);
} else {
$isValid = \call_user_func('is_'.$builtinType, $value);
}
if (!$isValid) {
throw new InvalidArgumentException(sprintf('The type of the "%s" attribute must be "%s", "%s" given.', $attribute, $builtinType, \gettype($value)));
}
}
/**
* Denormalizes a collection of objects.
*
* @param mixed $value
*
* @throws InvalidArgumentException
*/
protected function denormalizeCollection(string $attribute, PropertyMetadata $propertyMetadata, Type $type, string $className, $value, ?string $format, array $context): array
{
if (!\is_array($value)) {
throw new InvalidArgumentException(sprintf('The type of the "%s" attribute must be "array", "%s" given.', $attribute, \gettype($value)));
}
$collectionKeyType = method_exists(Type::class, 'getCollectionKeyTypes') ? ($type->getCollectionKeyTypes()[0] ?? null) : $type->getCollectionKeyType();
$collectionKeyBuiltinType = null === $collectionKeyType ? null : $collectionKeyType->getBuiltinType();
$values = [];
foreach ($value as $index => $obj) {
if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType, $index)) {
throw new InvalidArgumentException(sprintf('The type of the key "%s" must be "%s", "%s" given.', $index, $collectionKeyBuiltinType, \gettype($index)));
}
$values[$index] = $this->denormalizeRelation($attribute, $propertyMetadata, $className, $obj, $format, $this->createChildContext($context, $attribute, $format));
}
return $values;
}
/**
* Denormalizes a relation.
*
* @param mixed $value
*
* @throws LogicException
* @throws UnexpectedValueException
* @throws ItemNotFoundException
*
* @return object|null
*/
protected function denormalizeRelation(string $attributeName, PropertyMetadata $propertyMetadata, string $className, $value, ?string $format, array $context)
{
$supportsPlainIdentifiers = $this->supportsPlainIdentifiers();
if (\is_string($value)) {
try {
return $this->iriConverter->getItemFromIri($value, $context + ['fetch_data' => true]);
} catch (ItemNotFoundException $e) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
}
} catch (InvalidArgumentException $e) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException(sprintf('Invalid IRI "%s".', $value), $e->getCode(), $e);
}
}
}
if ($propertyMetadata->isWritableLink()) {
$context['api_allow_update'] = true;
if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
}
try {
$item = $this->serializer->denormalize($value, $className, $format, $context);
if (!\is_object($item) && null !== $item) {
throw new \UnexpectedValueException('Expected item to be an object or null.');
}
return $item;
} catch (InvalidValueException $e) {
if (!$supportsPlainIdentifiers) {
throw $e;
}
}
}
if (!\is_array($value)) {
if (!$supportsPlainIdentifiers) {
throw new UnexpectedValueException(sprintf('Expected IRI or nested document for attribute "%s", "%s" given.', $attributeName, \gettype($value)));
}
$item = $this->itemDataProvider->getItem($className, $value, null, $context + ['fetch_data' => true]);
if (null === $item) {
throw new ItemNotFoundException(sprintf('Item not found for resource "%s" with id "%s".', $className, $value));
}
return $item;
}
throw new UnexpectedValueException(sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.', $attributeName));
}
/**
* Gets the options for the property name collection / property metadata factories.
*/
protected function getFactoryOptions(array $context): array
{
$options = [];
if (isset($context[self::GROUPS])) {
/* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
$options['serializer_groups'] = (array) $context[self::GROUPS];
}
if (isset($context['collection_operation_name'])) {
$options['collection_operation_name'] = $context['collection_operation_name'];
}
if (isset($context['item_operation_name'])) {
$options['item_operation_name'] = $context['item_operation_name'];
}
return $options;
}
/**
* Creates the context to use when serializing a relation.
*
* @deprecated since version 2.1, to be removed in 3.0.
*/
protected function createRelationSerializationContext(string $resourceClass, array $context): array
{
@trigger_error(sprintf('The method %s() is deprecated since 2.1 and will be removed in 3.0.', __METHOD__), \E_USER_DEPRECATED);
return $context;
}
/**
* {@inheritdoc}
*
* @throws UnexpectedValueException
* @throws LogicException
*
* @return mixed
*/
protected function getAttributeValue($object, $attribute, $format = null, array $context = [])
{
$context['api_attribute'] = $attribute;
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
// BC to be removed in 3.0
try {
$attributeValue = $this->propertyAccessor->getValue($object, $attribute);
} catch (NoSuchPropertyException $e) {
if (!$propertyMetadata->hasChildInherited()) {
throw $e;
}
$attributeValue = null;
}
if ($context['api_denormalize'] ?? false) {
return $attributeValue;
}
$type = $propertyMetadata->getType();
if (
$type &&
$type->isCollection() &&
($collectionValueType = method_exists(Type::class, 'getCollectionValueTypes') ? ($type->getCollectionValueTypes()[0] ?? null) : $type->getCollectionValueType()) &&
($className = $collectionValueType->getClassName()) &&
$this->resourceClassResolver->isResourceClass($className)
) {
if (!is_iterable($attributeValue)) {
throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
}
$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
$childContext['resource_class'] = $resourceClass;
unset($childContext['iri']);
return $this->normalizeCollectionOfRelations($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
}
if (
$type &&
($className = $type->getClassName()) &&
$this->resourceClassResolver->isResourceClass($className)
) {
if (!\is_object($attributeValue) && null !== $attributeValue) {
throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
}
$resourceClass = $this->resourceClassResolver->getResourceClass($attributeValue, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
$childContext['resource_class'] = $resourceClass;
unset($childContext['iri']);
return $this->normalizeRelation($propertyMetadata, $attributeValue, $resourceClass, $format, $childContext);
}
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
}
unset($context['resource_class']);
if ($type && $type->getClassName()) {
if (!\is_object($attributeValue) && null !== $attributeValue) {
throw new UnexpectedValueException('Unexpected non-object value for object property.');
}
$childContext = $this->createChildContext($context, $attribute, $format);
unset($childContext['iri']);
return $this->serializer->normalize($attributeValue, $format, $childContext);
}
return $this->serializer->normalize($attributeValue, $format, $context);
}
/**
* Normalizes a collection of relations (to-many).
*
* @param iterable $attributeValue
*
* @throws UnexpectedValueException
*/
protected function normalizeCollectionOfRelations(PropertyMetadata $propertyMetadata, $attributeValue, string $resourceClass, ?string $format, array $context): array
{
$value = [];
foreach ($attributeValue as $index => $obj) {
if (!\is_object($obj) && null !== $obj) {
throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
}
$value[$index] = $this->normalizeRelation($propertyMetadata, $obj, $resourceClass, $format, $context);
}
return $value;
}
/**
* Normalizes a relation.
*
* @param object|null $relatedObject
*
* @throws LogicException
* @throws UnexpectedValueException
*
* @return string|array|\ArrayObject|null IRI or normalized object data
*/
protected function normalizeRelation(PropertyMetadata $propertyMetadata, $relatedObject, string $resourceClass, ?string $format, array $context)
{
if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
if (!$this->serializer instanceof NormalizerInterface) {
throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', NormalizerInterface::class));
}
$normalizedRelatedObject = $this->serializer->normalize($relatedObject, $format, $context);
// @phpstan-ignore-next-line throwing an explicit exception helps debugging
if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
}
return $normalizedRelatedObject;
}
$iri = $this->iriConverter->getIriFromItem($relatedObject);
if (isset($context['resources'])) {
$context['resources'][$iri] = $iri;
}
if (isset($context['resources_to_push']) && $propertyMetadata->getAttribute('push', false)) {
$context['resources_to_push'][$iri] = $iri;
}
return $iri;
}
/**
* Finds the first supported data transformer if any.
*
* @param object|array $data object on normalize / array on denormalize
*/
protected function getDataTransformer($data, string $to, array $context = []): ?DataTransformerInterface
{
foreach ($this->dataTransformers as $dataTransformer) {
if ($dataTransformer->supportsTransformation($data, $to, $context)) {
return $dataTransformer;
}
}
return null;
}
/**
* For a given resource, it returns an output representation if any
* If not, the resource is returned.
*
* @param mixed $object
*/
protected function transformOutput($object, array $context = [], string $outputClass = null)
{
if (null === $outputClass) {
$outputClass = $this->getOutputClass($this->getObjectClass($object), $context);
}
if (null !== $outputClass && null !== $dataTransformer = $this->getDataTransformer($object, $outputClass, $context)) {
return $dataTransformer->transform($object, $outputClass, $context);
}
return $object;
}
private function createAttributeValue($attribute, $value, $format = null, array $context = [])
{
$propertyMetadata = $this->propertyMetadataFactory->create($context['resource_class'], $attribute, $this->getFactoryOptions($context));
$type = $propertyMetadata->getType();
if (null === $type) {
// No type provided, blindly return the value
return $value;
}
if (null === $value && $type->isNullable()) {
return $value;
}
$collectionValueType = method_exists(Type::class, 'getCollectionValueTypes') ? ($type->getCollectionValueTypes()[0] ?? null) : $type->getCollectionValueType();
/* From @see AbstractObjectNormalizer::validateAndDenormalize() */
// Fix a collection that contains the only one element
// This is special to xml format only
if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
$value = [$value];
}
if (
$type->isCollection() &&
null !== $collectionValueType &&
null !== ($className = $collectionValueType->getClassName()) &&
$this->resourceClassResolver->isResourceClass($className)
) {
$resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
$context['resource_class'] = $resourceClass;
return $this->denormalizeCollection($attribute, $propertyMetadata, $type, $resourceClass, $value, $format, $context);
}
if (
null !== ($className = $type->getClassName()) &&
$this->resourceClassResolver->isResourceClass($className)
) {
$resourceClass = $this->resourceClassResolver->getResourceClass(null, $className);
$childContext = $this->createChildContext($context, $attribute, $format);
$childContext['resource_class'] = $resourceClass;
return $this->denormalizeRelation($attribute, $propertyMetadata, $resourceClass, $value, $format, $childContext);
}
if (
$type->isCollection() &&
null !== $collectionValueType &&
null !== ($className = $collectionValueType->getClassName())
) {
if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
}
unset($context['resource_class']);
return $this->serializer->denormalize($value, $className.'[]', $format, $context);
}
if (null !== $className = $type->getClassName()) {
if (!$this->serializer instanceof DenormalizerInterface) {
throw new LogicException(sprintf('The injected serializer must be an instance of "%s".', DenormalizerInterface::class));
}
unset($context['resource_class']);
return $this->serializer->denormalize($value, $className, $format, $context);
}
/* From @see AbstractObjectNormalizer::validateAndDenormalize() */
// In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
// if a value is meant to be a string, float, int or a boolean value from the serialized representation.
// That's why we have to transform the values, if one of these non-string basic datatypes is expected.
if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
if ('' === $value && $type->isNullable() && \in_array($type->getBuiltinType(), [Type::BUILTIN_TYPE_BOOL, Type::BUILTIN_TYPE_INT, Type::BUILTIN_TYPE_FLOAT], true)) {
return null;
}
switch ($type->getBuiltinType()) {
case Type::BUILTIN_TYPE_BOOL:
// according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
if ('false' === $value || '0' === $value) {
$value = false;
} elseif ('true' === $value || '1' === $value) {
$value = true;
} else {
throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).', $attribute, $className, $value));
}
break;
case Type::BUILTIN_TYPE_INT:
if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value, 1)))) {
$value = (int) $value;
} else {
throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).', $attribute, $className, $value));
}
break;
case Type::BUILTIN_TYPE_FLOAT:
if (is_numeric($value)) {
return (float) $value;
}
switch ($value) {
case 'NaN':
return \NAN;
case 'INF':
return \INF;
case '-INF':
return -\INF;
default:
throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).', $attribute, $className, $value));
}
}
}
if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
return $value;
}
$this->validateType($attribute, $type, $value, $format);
return $value;
}
/**
* Sets a value of the object using the PropertyAccess component.
*
* @param object $object
* @param mixed $value
*/
private function setValue($object, string $attributeName, $value)
{
try {
$this->propertyAccessor->setValue($object, $attributeName, $value);
} catch (NoSuchPropertyException $exception) {
// Properties not found are ignored
}
}
private function supportsPlainIdentifiers(): bool
{
return $this->allowPlainIdentifiers && null !== $this->itemDataProvider;
}
}