vendor/api-platform/core/src/Serializer/AbstractItemNormalizer.php line 104

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the API Platform project.
  4.  *
  5.  * (c) Kévin Dunglas <dunglas@gmail.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. declare(strict_types=1);
  11. namespace ApiPlatform\Serializer;
  12. use ApiPlatform\Api\IriConverterInterface;
  13. use ApiPlatform\Api\UrlGeneratorInterface;
  14. use ApiPlatform\Core\Api\IriConverterInterface as LegacyIriConverterInterface;
  15. use ApiPlatform\Core\Bridge\Symfony\Messenger\DataTransformer as MessengerDataTransformer;
  16. use ApiPlatform\Core\DataProvider\ItemDataProviderInterface;
  17. use ApiPlatform\Core\DataTransformer\DataTransformerInitializerInterface;
  18. use ApiPlatform\Core\DataTransformer\DataTransformerInterface;
  19. use ApiPlatform\Core\Metadata\Property\Factory\PropertyMetadataFactoryInterface as LegacyPropertyMetadataFactoryInterface;
  20. use ApiPlatform\Core\Metadata\Property\PropertyMetadata;
  21. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  22. use ApiPlatform\Exception\InvalidArgumentException;
  23. use ApiPlatform\Exception\InvalidValueException;
  24. use ApiPlatform\Exception\ItemNotFoundException;
  25. use ApiPlatform\Metadata\ApiProperty;
  26. use ApiPlatform\Metadata\Property\Factory\PropertyMetadataFactoryInterface;
  27. use ApiPlatform\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
  28. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  29. use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
  30. use ApiPlatform\Util\ClassInfoTrait;
  31. use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
  32. use Symfony\Component\PropertyAccess\PropertyAccess;
  33. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  34. use Symfony\Component\PropertyInfo\Type;
  35. use Symfony\Component\Serializer\Encoder\CsvEncoder;
  36. use Symfony\Component\Serializer\Encoder\XmlEncoder;
  37. use Symfony\Component\Serializer\Exception\LogicException;
  38. use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
  39. use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
  40. use Symfony\Component\Serializer\Exception\RuntimeException;
  41. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  42. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
  43. use Symfony\Component\Serializer\NameConverter\AdvancedNameConverterInterface;
  44. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  45. use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
  46. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  47. use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
  48. /**
  49.  * Base item normalizer.
  50.  *
  51.  * @author Kévin Dunglas <dunglas@gmail.com>
  52.  */
  53. abstract class AbstractItemNormalizer extends AbstractObjectNormalizer
  54. {
  55.     use ClassInfoTrait;
  56.     use ContextTrait;
  57.     use InputOutputMetadataTrait;
  58.     public const IS_TRANSFORMED_TO_SAME_CLASS 'is_transformed_to_same_class';
  59.     /**
  60.      * @var PropertyNameCollectionFactoryInterface
  61.      */
  62.     protected $propertyNameCollectionFactory;
  63.     /**
  64.      * @var LegacyPropertyMetadataFactoryInterface|PropertyMetadataFactoryInterface
  65.      */
  66.     protected $propertyMetadataFactory;
  67.     protected $resourceMetadataFactory;
  68.     /**
  69.      * @var LegacyIriConverterInterface|IriConverterInterface
  70.      */
  71.     protected $iriConverter;
  72.     protected $resourceClassResolver;
  73.     protected $resourceAccessChecker;
  74.     protected $propertyAccessor;
  75.     protected $itemDataProvider;
  76.     protected $allowPlainIdentifiers;
  77.     protected $dataTransformers = [];
  78.     protected $localCache = [];
  79.     public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory$propertyMetadataFactory$iriConverter$resourceClassResolverPropertyAccessorInterface $propertyAccessor nullNameConverterInterface $nameConverter nullClassMetadataFactoryInterface $classMetadataFactory nullItemDataProviderInterface $itemDataProvider nullbool $allowPlainIdentifiers false, array $defaultContext = [], iterable $dataTransformers = [], $resourceMetadataFactory nullResourceAccessCheckerInterface $resourceAccessChecker null)
  80.     {
  81.         if (!isset($defaultContext['circular_reference_handler'])) {
  82.             $defaultContext['circular_reference_handler'] = function ($object) {
  83.                 return $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getIriFromItem($object) : $this->iriConverter->getIriFromResource($object);
  84.             };
  85.         }
  86.         if (!interface_exists(AdvancedNameConverterInterface::class) && method_exists($this'setCircularReferenceHandler')) {
  87.             $this->setCircularReferenceHandler($defaultContext['circular_reference_handler']);
  88.         }
  89.         parent::__construct($classMetadataFactory$nameConverternullnull, \Closure::fromCallable([$this'getObjectClass']), $defaultContext);
  90.         $this->propertyNameCollectionFactory $propertyNameCollectionFactory;
  91.         $this->propertyMetadataFactory $propertyMetadataFactory;
  92.         if ($iriConverter instanceof LegacyIriConverterInterface) {
  93.             trigger_deprecation('api-platform/core''2.7'sprintf('Use an implementation of "%s" instead of "%s".'IriConverterInterface::class, LegacyIriConverterInterface::class));
  94.         }
  95.         $this->iriConverter $iriConverter;
  96.         $this->resourceClassResolver $resourceClassResolver;
  97.         $this->propertyAccessor $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
  98.         $this->itemDataProvider $itemDataProvider;
  99.         if (true === $allowPlainIdentifiers) {
  100.             @trigger_error(sprintf('Allowing plain identifiers as argument of "%s" is deprecated since API Platform 2.7 and will not be possible anymore in API Platform 3.'self::class), \E_USER_DEPRECATED);
  101.         }
  102.         $this->allowPlainIdentifiers $allowPlainIdentifiers;
  103.         $this->dataTransformers $dataTransformers;
  104.         // Just skip our data transformer to trigger a proper deprecation
  105.         $customDataTransformers array_filter(\is_array($dataTransformers) ? $dataTransformers iterator_to_array($dataTransformers), function ($dataTransformer) {
  106.             return !$dataTransformer instanceof MessengerDataTransformer;
  107.         });
  108.         if (\count($customDataTransformers)) {
  109.             trigger_deprecation('api-platform/core''2.7''The DataTransformer pattern is deprecated, use a Provider or a Processor and either use your input or return a new output there.');
  110.         }
  111.         if ($resourceMetadataFactory && !$resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  112.             trigger_deprecation('api-platform/core''2.7'sprintf('Use "%s" instead of "%s".'ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  113.         }
  114.         $this->resourceMetadataFactory $resourceMetadataFactory;
  115.         $this->resourceAccessChecker $resourceAccessChecker;
  116.     }
  117.     /**
  118.      * {@inheritdoc}
  119.      */
  120.     public function supportsNormalization($data$format null, array $context = []): bool
  121.     {
  122.         if (!\is_object($data) || is_iterable($data)) {
  123.             return false;
  124.         }
  125.         $class $this->getObjectClass($data);
  126.         if (($context['output']['class'] ?? null) === $class) {
  127.             return true;
  128.         }
  129.         return $this->resourceClassResolver->isResourceClass($class);
  130.     }
  131.     /**
  132.      * {@inheritdoc}
  133.      */
  134.     public function hasCacheableSupportsMethod(): bool
  135.     {
  136.         return true;
  137.     }
  138.     /**
  139.      * {@inheritdoc}
  140.      *
  141.      * @throws LogicException
  142.      *
  143.      * @return array|string|int|float|bool|\ArrayObject|null
  144.      */
  145.     public function normalize($object$format null, array $context = [])
  146.     {
  147.         $resourceClass $this->getObjectClass($object);
  148.         if (!($isTransformed = isset($context[self::IS_TRANSFORMED_TO_SAME_CLASS])) && $outputClass $this->getOutputClass($resourceClass$context)) {
  149.             if (!$this->serializer instanceof NormalizerInterface) {
  150.                 throw new LogicException('Cannot normalize the output because the injected serializer is not a normalizer');
  151.             }
  152.             // Data transformers are deprecated, this is removed from 3.0
  153.             if ($dataTransformer $this->getDataTransformer($object$outputClass$context)) {
  154.                 $transformed $dataTransformer->transform($object$outputClass$context);
  155.                 if ($object === $transformed) {
  156.                     $context[self::IS_TRANSFORMED_TO_SAME_CLASS] = true;
  157.                 } else {
  158.                     $context['api_normalize'] = true;
  159.                     $context['api_resource'] = $object;
  160.                     unset($context['output'], $context['resource_class']);
  161.                 }
  162.                 return $this->serializer->normalize($transformed$format$context);
  163.             }
  164.             unset($context['output'], $context['operation_name']);
  165.             if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface && !isset($context['operation'])) {
  166.                 $context['operation'] = $this->resourceMetadataFactory->create($context['resource_class'])->getOperation();
  167.             }
  168.             $context['resource_class'] = $outputClass;
  169.             $context['api_sub_level'] = true;
  170.             $context[self::ALLOW_EXTRA_ATTRIBUTES] = false;
  171.             return $this->serializer->normalize($object$format$context);
  172.         }
  173.         if ($isTransformed) {
  174.             unset($context[self::IS_TRANSFORMED_TO_SAME_CLASS]);
  175.         }
  176.         $iri null;
  177.         if ($this->resourceClassResolver->isResourceClass($resourceClass)) {
  178.             $context $this->initContext($resourceClass$context);
  179.             if ($this->iriConverter instanceof LegacyIriConverterInterface) {
  180.                 $iri $this->iriConverter->getIriFromItem($object);
  181.             }
  182.         }
  183.         if (isset($context['iri'])) {
  184.             $iri $context['iri'];
  185.         } elseif ($this->iriConverter instanceof IriConverterInterface) {
  186.             $iri $this->iriConverter->getIriFromResource($objectUrlGeneratorInterface::ABS_URL$context['operation'] ?? null$context);
  187.         }
  188.         $context['iri'] = $iri;
  189.         $context['api_normalize'] = true;
  190.         /*
  191.          * When true, converts the normalized data array of a resource into an
  192.          * IRI, if the normalized data array is empty.
  193.          *
  194.          * This is useful when traversing from a non-resource towards an attribute
  195.          * which is a resource, as we do not have the benefit of {@see PropertyMetadata::isReadableLink}.
  196.          *
  197.          * It must not be propagated to subresources, as {@see PropertyMetadata::isReadableLink}
  198.          * should take effect.
  199.          */
  200.         $emptyResourceAsIri $context['api_empty_resource_as_iri'] ?? false;
  201.         unset($context['api_empty_resource_as_iri']);
  202.         if (isset($context['resources'])) {
  203.             $context['resources'][$iri] = $iri;
  204.         }
  205.         $data parent::normalize($object$format$context);
  206.         if ($emptyResourceAsIri && \is_array($data) && === \count($data)) {
  207.             return $iri;
  208.         }
  209.         return $data;
  210.     }
  211.     /**
  212.      * {@inheritdoc}
  213.      *
  214.      * @return bool
  215.      */
  216.     public function supportsDenormalization($data$type$format null, array $context = [])
  217.     {
  218.         if (($context['input']['class'] ?? null) === $type) {
  219.             return true;
  220.         }
  221.         return $this->localCache[$type] ?? $this->localCache[$type] = $this->resourceClassResolver->isResourceClass($type);
  222.     }
  223.     /**
  224.      * {@inheritdoc}
  225.      *
  226.      * @return mixed
  227.      */
  228.     public function denormalize($data$class$format null, array $context = [])
  229.     {
  230.         $resourceClass $class;
  231.         if (null !== $inputClass $this->getInputClass($resourceClass$context)) {
  232.             if (null !== $dataTransformer $this->getDataTransformer($data$resourceClass$context)) {
  233.                 $dataTransformerContext $context;
  234.                 unset($context['input']);
  235.                 unset($context['resource_class']);
  236.                 if (!$this->serializer instanceof DenormalizerInterface) {
  237.                     throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
  238.                 }
  239.                 if ($dataTransformer instanceof DataTransformerInitializerInterface) {
  240.                     $context[AbstractObjectNormalizer::OBJECT_TO_POPULATE] = $dataTransformer->initialize($inputClass$context);
  241.                     $context[AbstractObjectNormalizer::DEEP_OBJECT_TO_POPULATE] = true;
  242.                 }
  243.                 try {
  244.                     $denormalizedInput $this->serializer->denormalize($data$inputClass$format$context);
  245.                 } catch (NotNormalizableValueException $e) {
  246.                     throw new UnexpectedValueException('The input data is misformatted.'$e->getCode(), $e);
  247.                 }
  248.                 if (!\is_object($denormalizedInput)) {
  249.                     throw new UnexpectedValueException('Expected denormalized input to be an object.');
  250.                 }
  251.                 return $dataTransformer->transform($denormalizedInput$resourceClass$dataTransformerContext);
  252.             }
  253.             unset($context['input']);
  254.             unset($context['operation']);
  255.             unset($context['operation_name']);
  256.             $context['resource_class'] = $inputClass;
  257.             if (!$this->serializer instanceof DenormalizerInterface) {
  258.                 throw new LogicException('Cannot denormalize the input because the injected serializer is not a denormalizer');
  259.             }
  260.             try {
  261.                 return $this->serializer->denormalize($data$inputClass$format$context);
  262.             } catch (NotNormalizableValueException $e) {
  263.                 throw new UnexpectedValueException('The input data is misformatted.'$e->getCode(), $e);
  264.             }
  265.         }
  266.         if (null === $objectToPopulate $this->extractObjectToPopulate($class$context, static::OBJECT_TO_POPULATE)) {
  267.             $normalizedData = \is_scalar($data) ? [$data] : $this->prepareForDenormalization($data);
  268.             $class $this->getClassDiscriminatorResolvedClass($normalizedData$class);
  269.         }
  270.         $context['api_denormalize'] = true;
  271.         if ($this->resourceClassResolver->isResourceClass($class)) {
  272.             $resourceClass $this->resourceClassResolver->getResourceClass($objectToPopulate$class);
  273.             $context['resource_class'] = $resourceClass;
  274.         }
  275.         $supportsPlainIdentifiers $this->supportsPlainIdentifiers();
  276.         if (\is_string($data)) {
  277.             try {
  278.                 return $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getItemFromIri($data$context + ['fetch_data' => true]) : $this->iriConverter->getResourceFromIri($data$context + ['fetch_data' => true]);
  279.             } catch (ItemNotFoundException $e) {
  280.                 if (!$supportsPlainIdentifiers) {
  281.                     throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
  282.                 }
  283.             } catch (InvalidArgumentException $e) {
  284.                 if (!$supportsPlainIdentifiers) {
  285.                     throw new UnexpectedValueException(sprintf('Invalid IRI "%s".'$data), $e->getCode(), $e);
  286.                 }
  287.             }
  288.         }
  289.         if (!\is_array($data)) {
  290.             if (!$supportsPlainIdentifiers) {
  291.                 throw new UnexpectedValueException(sprintf('Expected IRI or document for resource "%s", "%s" given.'$resourceClass, \gettype($data)));
  292.             }
  293.             $item $this->itemDataProvider->getItem($resourceClass$datanull$context + ['fetch_data' => true]);
  294.             if (null === $item) {
  295.                 throw new ItemNotFoundException(sprintf('Item not found for resource "%s" with id "%s".'$resourceClass$data));
  296.             }
  297.             return $item;
  298.         }
  299.         $previousObject null !== $objectToPopulate ? clone $objectToPopulate null;
  300.         $object parent::denormalize($data$resourceClass$format$context);
  301.         if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
  302.             return $object;
  303.         }
  304.         // Revert attributes that aren't allowed to be changed after a post-denormalize check
  305.         foreach (array_keys($data) as $attribute) {
  306.             if (!$this->canAccessAttributePostDenormalize($object$previousObject$attribute$context)) {
  307.                 if (null !== $previousObject) {
  308.                     $this->setValue($object$attribute$this->propertyAccessor->getValue($previousObject$attribute));
  309.                 } else {
  310.                     $propertyMetadata $this->propertyMetadataFactory->create($resourceClass$attribute$this->getFactoryOptions($context));
  311.                     $this->setValue($object$attribute$propertyMetadata->getDefault());
  312.                 }
  313.             }
  314.         }
  315.         return $object;
  316.     }
  317.     /**
  318.      * Method copy-pasted from symfony/serializer.
  319.      * Remove it after symfony/serializer version update @see https://github.com/symfony/symfony/pull/28263.
  320.      *
  321.      * {@inheritdoc}
  322.      *
  323.      * @internal
  324.      *
  325.      * @return object
  326.      */
  327.     protected function instantiateObject(array &$data$class, array &$context, \ReflectionClass $reflectionClass$allowedAttributesstring $format null)
  328.     {
  329.         if (null !== $object $this->extractObjectToPopulate($class$context, static::OBJECT_TO_POPULATE)) {
  330.             unset($context[static::OBJECT_TO_POPULATE]);
  331.             return $object;
  332.         }
  333.         $class $this->getClassDiscriminatorResolvedClass($data$class);
  334.         $reflectionClass = new \ReflectionClass($class);
  335.         $constructor $this->getConstructor($data$class$context$reflectionClass$allowedAttributes);
  336.         if ($constructor) {
  337.             $constructorParameters $constructor->getParameters();
  338.             $params = [];
  339.             foreach ($constructorParameters as $constructorParameter) {
  340.                 $paramName $constructorParameter->name;
  341.                 $key $this->nameConverter $this->nameConverter->normalize($paramName$class$format$context) : $paramName;
  342.                 $allowed false === $allowedAttributes || (\is_array($allowedAttributes) && \in_array($paramName$allowedAttributestrue));
  343.                 $ignored = !$this->isAllowedAttribute($class$paramName$format$context);
  344.                 if ($constructorParameter->isVariadic()) {
  345.                     if ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key$data))) {
  346.                         if (!\is_array($data[$paramName])) {
  347.                             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));
  348.                         }
  349.                         $params array_merge($params$data[$paramName]);
  350.                     }
  351.                 } elseif ($allowed && !$ignored && (isset($data[$key]) || \array_key_exists($key$data))) {
  352.                     $params[] = $this->createConstructorArgument($data[$key], $key$constructorParameter$context$format);
  353.                     // Don't run set for a parameter passed to the constructor
  354.                     unset($data[$key]);
  355.                 } elseif (isset($context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key])) {
  356.                     $params[] = $context[static::DEFAULT_CONSTRUCTOR_ARGUMENTS][$class][$key];
  357.                 } elseif ($constructorParameter->isDefaultValueAvailable()) {
  358.                     $params[] = $constructorParameter->getDefaultValue();
  359.                 } else {
  360.                     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));
  361.                 }
  362.             }
  363.             if ($constructor->isConstructor()) {
  364.                 return $reflectionClass->newInstanceArgs($params);
  365.             }
  366.             return $constructor->invokeArgs(null$params);
  367.         }
  368.         return new $class();
  369.     }
  370.     protected function getClassDiscriminatorResolvedClass(array &$datastring $class): string
  371.     {
  372.         if (null === $this->classDiscriminatorResolver || (null === $mapping $this->classDiscriminatorResolver->getMappingForClass($class))) {
  373.             return $class;
  374.         }
  375.         if (!isset($data[$mapping->getTypeProperty()])) {
  376.             throw new RuntimeException(sprintf('Type property "%s" not found for the abstract object "%s"'$mapping->getTypeProperty(), $class));
  377.         }
  378.         $type $data[$mapping->getTypeProperty()];
  379.         if (null === ($mappedClass $mapping->getClassForType($type))) {
  380.             throw new RuntimeException(sprintf('The type "%s" has no mapped class for the abstract object "%s"'$type$class));
  381.         }
  382.         return $mappedClass;
  383.     }
  384.     /**
  385.      * {@inheritdoc}
  386.      */
  387.     protected function createConstructorArgument($parameterDatastring $key, \ReflectionParameter $constructorParameter, array &$contextstring $format null)
  388.     {
  389.         return $this->createAttributeValue($constructorParameter->name$parameterData$format$context);
  390.     }
  391.     /**
  392.      * {@inheritdoc}
  393.      *
  394.      * Unused in this context.
  395.      *
  396.      * @return string[]
  397.      */
  398.     protected function extractAttributes($object$format null, array $context = [])
  399.     {
  400.         return [];
  401.     }
  402.     /**
  403.      * {@inheritdoc}
  404.      *
  405.      * @return array|bool
  406.      */
  407.     protected function getAllowedAttributes($classOrObject, array $context$attributesAsString false)
  408.     {
  409.         if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
  410.             return parent::getAllowedAttributes($classOrObject$context$attributesAsString);
  411.         }
  412.         $resourceClass $this->resourceClassResolver->getResourceClass(null$context['resource_class']); // fix for abstract classes and interfaces
  413.         $options $this->getFactoryOptions($context);
  414.         $propertyNames $this->propertyNameCollectionFactory->create($resourceClass$options);
  415.         $allowedAttributes = [];
  416.         foreach ($propertyNames as $propertyName) {
  417.             $propertyMetadata $this->propertyMetadataFactory->create($resourceClass$propertyName$options);
  418.             if (
  419.                 $this->isAllowedAttribute($classOrObject$propertyNamenull$context) &&
  420.                 (
  421.                     isset($context['api_normalize']) && $propertyMetadata->isReadable() ||
  422.                     isset($context['api_denormalize']) && ($propertyMetadata->isWritable() || !\is_object($classOrObject) && $propertyMetadata->isInitializable())
  423.                 )
  424.             ) {
  425.                 $allowedAttributes[] = $propertyName;
  426.             }
  427.         }
  428.         return $allowedAttributes;
  429.     }
  430.     /**
  431.      * {@inheritdoc}
  432.      *
  433.      * @return bool
  434.      */
  435.     protected function isAllowedAttribute($classOrObject$attribute$format null, array $context = [])
  436.     {
  437.         if (!parent::isAllowedAttribute($classOrObject$attribute$format$context)) {
  438.             return false;
  439.         }
  440.         return $this->canAccessAttribute(\is_object($classOrObject) ? $classOrObject null$attribute$context);
  441.     }
  442.     /**
  443.      * Check if access to the attribute is granted.
  444.      *
  445.      * @param object $object
  446.      */
  447.     protected function canAccessAttribute($objectstring $attribute, array $context = []): bool
  448.     {
  449.         if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
  450.             return true;
  451.         }
  452.         $options $this->getFactoryOptions($context);
  453.         /** @var PropertyMetadata|ApiProperty */
  454.         $propertyMetadata $this->propertyMetadataFactory->create($context['resource_class'], $attribute$options);
  455.         $security $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getAttribute('security') : $propertyMetadata->getSecurity();
  456.         if ($this->resourceAccessChecker && $security) {
  457.             return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
  458.                 'object' => $object,
  459.             ]);
  460.         }
  461.         return true;
  462.     }
  463.     /**
  464.      * Check if access to the attribute is granted.
  465.      *
  466.      * @param object      $object
  467.      * @param object|null $previousObject
  468.      */
  469.     protected function canAccessAttributePostDenormalize($object$previousObjectstring $attribute, array $context = []): bool
  470.     {
  471.         $options $this->getFactoryOptions($context);
  472.         /** @var PropertyMetadata|ApiProperty */
  473.         $propertyMetadata $this->propertyMetadataFactory->create($context['resource_class'], $attribute$options);
  474.         $security $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getAttribute('security_post_denormalize') : $propertyMetadata->getSecurityPostDenormalize();
  475.         if ($this->resourceAccessChecker && $security) {
  476.             return $this->resourceAccessChecker->isGranted($context['resource_class'], $security, [
  477.                 'object' => $object,
  478.                 'previous_object' => $previousObject,
  479.             ]);
  480.         }
  481.         return true;
  482.     }
  483.     /**
  484.      * {@inheritdoc}
  485.      */
  486.     protected function setAttributeValue($object$attribute$value$format null, array $context = [])
  487.     {
  488.         $this->setValue($object$attribute$this->createAttributeValue($attribute$value$format$context));
  489.     }
  490.     /**
  491.      * Validates the type of the value. Allows using integers as floats for JSON formats.
  492.      *
  493.      * @param mixed $value
  494.      *
  495.      * @throws InvalidArgumentException
  496.      */
  497.     protected function validateType(string $attributeType $type$valuestring $format null)
  498.     {
  499.         $builtinType $type->getBuiltinType();
  500.         if (Type::BUILTIN_TYPE_FLOAT === $builtinType && null !== $format && false !== strpos($format'json')) {
  501.             $isValid = \is_float($value) || \is_int($value);
  502.         } else {
  503.             $isValid = \call_user_func('is_'.$builtinType$value);
  504.         }
  505.         if (!$isValid) {
  506.             throw new UnexpectedValueException(sprintf('The type of the "%s" attribute must be "%s", "%s" given.'$attribute$builtinType, \gettype($value)));
  507.         }
  508.     }
  509.     /**
  510.      * Denormalizes a collection of objects.
  511.      *
  512.      * @param ApiProperty|PropertyMetadata $propertyMetadata
  513.      * @param mixed                        $value
  514.      *
  515.      * @throws InvalidArgumentException
  516.      */
  517.     protected function denormalizeCollection(string $attribute$propertyMetadataType $typestring $className$value, ?string $format, array $context): array
  518.     {
  519.         if (!\is_array($value)) {
  520.             throw new InvalidArgumentException(sprintf('The type of the "%s" attribute must be "array", "%s" given.'$attribute, \gettype($value)));
  521.         }
  522.         $collectionKeyType method_exists(Type::class, 'getCollectionKeyTypes') ? ($type->getCollectionKeyTypes()[0] ?? null) : $type->getCollectionKeyType();
  523.         $collectionKeyBuiltinType null === $collectionKeyType null $collectionKeyType->getBuiltinType();
  524.         $values = [];
  525.         foreach ($value as $index => $obj) {
  526.             if (null !== $collectionKeyBuiltinType && !\call_user_func('is_'.$collectionKeyBuiltinType$index)) {
  527.                 throw new InvalidArgumentException(sprintf('The type of the key "%s" must be "%s", "%s" given.'$index$collectionKeyBuiltinType, \gettype($index)));
  528.             }
  529.             $values[$index] = $this->denormalizeRelation($attribute$propertyMetadata$className$obj$format$this->createChildContext($context$attribute$format));
  530.         }
  531.         return $values;
  532.     }
  533.     /**
  534.      * Denormalizes a relation.
  535.      *
  536.      * @param ApiProperty|PropertyMetadata $propertyMetadata
  537.      * @param mixed                        $value
  538.      *
  539.      * @throws LogicException
  540.      * @throws UnexpectedValueException
  541.      * @throws ItemNotFoundException
  542.      *
  543.      * @return object|null
  544.      */
  545.     protected function denormalizeRelation(string $attributeName$propertyMetadatastring $className$value, ?string $format, array $context)
  546.     {
  547.         $supportsPlainIdentifiers $this->supportsPlainIdentifiers();
  548.         if (\is_string($value)) {
  549.             try {
  550.                 return $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getItemFromIri($value$context + ['fetch_data' => true]) : $this->iriConverter->getResourceFromIri($value$context + ['fetch_data' => true]);
  551.             } catch (ItemNotFoundException $e) {
  552.                 if (!$supportsPlainIdentifiers) {
  553.                     throw new UnexpectedValueException($e->getMessage(), $e->getCode(), $e);
  554.                 }
  555.             } catch (InvalidArgumentException $e) {
  556.                 if (!$supportsPlainIdentifiers) {
  557.                     throw new UnexpectedValueException(sprintf('Invalid IRI "%s".'$value), $e->getCode(), $e);
  558.                 }
  559.             }
  560.         }
  561.         if ($propertyMetadata->isWritableLink()) {
  562.             $context['api_allow_update'] = true;
  563.             if (!$this->serializer instanceof DenormalizerInterface) {
  564.                 throw new LogicException(sprintf('The injected serializer must be an instance of "%s".'DenormalizerInterface::class));
  565.             }
  566.             try {
  567.                 $item $this->serializer->denormalize($value$className$format$context);
  568.                 if (!\is_object($item) && null !== $item) {
  569.                     throw new \UnexpectedValueException('Expected item to be an object or null.');
  570.                 }
  571.                 return $item;
  572.             } catch (InvalidValueException $e) {
  573.                 if (!$supportsPlainIdentifiers) {
  574.                     throw $e;
  575.                 }
  576.             }
  577.         }
  578.         if (!\is_array($value)) {
  579.             if (!$supportsPlainIdentifiers) {
  580.                 throw new UnexpectedValueException(sprintf('Expected IRI or nested document for attribute "%s", "%s" given.'$attributeName, \gettype($value)));
  581.             }
  582.             $item $this->itemDataProvider->getItem($className$valuenull$context + ['fetch_data' => true]);
  583.             if (null === $item) {
  584.                 throw new ItemNotFoundException(sprintf('Item not found for resource "%s" with id "%s".'$className$value));
  585.             }
  586.             return $item;
  587.         }
  588.         throw new UnexpectedValueException(sprintf('Nested documents for attribute "%s" are not allowed. Use IRIs instead.'$attributeName));
  589.     }
  590.     /**
  591.      * Gets the options for the property name collection / property metadata factories.
  592.      */
  593.     protected function getFactoryOptions(array $context): array
  594.     {
  595.         $options = [];
  596.         if (isset($context[self::GROUPS])) {
  597.             /* @see https://github.com/symfony/symfony/blob/v4.2.6/src/Symfony/Component/PropertyInfo/Extractor/SerializerExtractor.php */
  598.             $options['serializer_groups'] = (array) $context[self::GROUPS];
  599.         }
  600.         if (isset($context['resource_class']) && $this->resourceClassResolver->isResourceClass($context['resource_class']) && $this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  601.             $resourceClass $this->resourceClassResolver->getResourceClass(null$context['resource_class']); // fix for abstract classes and interfaces
  602.             // This is a hot spot, we should avoid calling this here but in many cases we can't
  603.             $operation $context['operation'] ?? $this->resourceMetadataFactory->create($resourceClass)->getOperation($context['operation_name'] ?? null);
  604.             $options['normalization_groups'] = $operation->getNormalizationContext()['groups'] ?? null;
  605.             $options['denormalization_groups'] = $operation->getDenormalizationContext()['groups'] ?? null;
  606.         }
  607.         if (isset($context['operation_name'])) {
  608.             $options['operation_name'] = $context['operation_name'];
  609.         }
  610.         if (isset($context['collection_operation_name'])) {
  611.             $options['collection_operation_name'] = $context['collection_operation_name'];
  612.         }
  613.         if (isset($context['item_operation_name'])) {
  614.             $options['item_operation_name'] = $context['item_operation_name'];
  615.         }
  616.         return $options;
  617.     }
  618.     /**
  619.      * Creates the context to use when serializing a relation.
  620.      *
  621.      * @deprecated since version 2.1, to be removed in 3.0.
  622.      */
  623.     protected function createRelationSerializationContext(string $resourceClass, array $context): array
  624.     {
  625.         @trigger_error(sprintf('The method %s() is deprecated since 2.1 and will be removed in 3.0.'__METHOD__), \E_USER_DEPRECATED);
  626.         return $context;
  627.     }
  628.     /**
  629.      * {@inheritdoc}
  630.      *
  631.      * @throws UnexpectedValueException
  632.      * @throws LogicException
  633.      *
  634.      * @return mixed
  635.      */
  636.     protected function getAttributeValue($object$attribute$format null, array $context = [])
  637.     {
  638.         $context['api_attribute'] = $attribute;
  639.         /** @var ApiProperty|PropertyMetadata */
  640.         $propertyMetadata $this->propertyMetadataFactory->create($context['resource_class'], $attribute$this->getFactoryOptions($context));
  641.         try {
  642.             $attributeValue $this->propertyAccessor->getValue($object$attribute);
  643.         } catch (NoSuchPropertyException $e) {
  644.             // BC to be removed in 3.0
  645.             if ($propertyMetadata instanceof PropertyMetadata && !$propertyMetadata->hasChildInherited()) {
  646.                 throw $e;
  647.             }
  648.             if ($propertyMetadata instanceof ApiProperty) {
  649.                 throw $e;
  650.             }
  651.             $attributeValue null;
  652.         }
  653.         if ($context['api_denormalize'] ?? false) {
  654.             return $attributeValue;
  655.         }
  656.         $type $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getType() : ($propertyMetadata->getBuiltinTypes()[0] ?? null);
  657.         if (
  658.             $type &&
  659.             $type->isCollection() &&
  660.             ($collectionValueType method_exists(Type::class, 'getCollectionValueTypes') ? ($type->getCollectionValueTypes()[0] ?? null) : $type->getCollectionValueType()) &&
  661.             ($className $collectionValueType->getClassName()) &&
  662.             $this->resourceClassResolver->isResourceClass($className)
  663.         ) {
  664.             if (!is_iterable($attributeValue)) {
  665.                 throw new UnexpectedValueException('Unexpected non-iterable value for to-many relation.');
  666.             }
  667.             $resourceClass $this->resourceClassResolver->getResourceClass($attributeValue$className);
  668.             $childContext $this->createChildContext($context$attribute$format);
  669.             $childContext['resource_class'] = $resourceClass;
  670.             if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  671.                 $childContext['operation'] = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
  672.             }
  673.             unset($childContext['iri'], $childContext['uri_variables']);
  674.             return $this->normalizeCollectionOfRelations($propertyMetadata$attributeValue$resourceClass$format$childContext);
  675.         }
  676.         if (
  677.             $type &&
  678.             ($className $type->getClassName()) &&
  679.             $this->resourceClassResolver->isResourceClass($className)
  680.         ) {
  681.             if (!\is_object($attributeValue) && null !== $attributeValue) {
  682.                 throw new UnexpectedValueException('Unexpected non-object value for to-one relation.');
  683.             }
  684.             $resourceClass $this->resourceClassResolver->getResourceClass($attributeValue$className);
  685.             $childContext $this->createChildContext($context$attribute$format);
  686.             $childContext['resource_class'] = $resourceClass;
  687.             if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  688.                 $childContext['operation'] = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
  689.             }
  690.             unset($childContext['iri'], $childContext['uri_variables']);
  691.             return $this->normalizeRelation($propertyMetadata$attributeValue$resourceClass$format$childContext);
  692.         }
  693.         if (!$this->serializer instanceof NormalizerInterface) {
  694.             throw new LogicException(sprintf('The injected serializer must be an instance of "%s".'NormalizerInterface::class));
  695.         }
  696.         unset($context['resource_class']);
  697.         if ($type && $type->getClassName()) {
  698.             $childContext $this->createChildContext($context$attribute$format);
  699.             unset($childContext['iri'], $childContext['uri_variables']);
  700.             if ($propertyMetadata instanceof PropertyMetadata) {
  701.                 $childContext['output']['iri'] = $propertyMetadata->getIri();
  702.             } else {
  703.                 if (null !== ($propertyIris $propertyMetadata->getIris())) {
  704.                     $childContext['output']['iri'] = === \count($propertyIris) ? $propertyIris[0] : $propertyIris;
  705.                 }
  706.             }
  707.             return $this->serializer->normalize($attributeValue$format$childContext);
  708.         }
  709.         return $this->serializer->normalize($attributeValue$format$context);
  710.     }
  711.     /**
  712.      * Normalizes a collection of relations (to-many).
  713.      *
  714.      * @param ApiProperty|PropertyMetadata $propertyMetadata
  715.      * @param iterable                     $attributeValue
  716.      *
  717.      * @throws UnexpectedValueException
  718.      */
  719.     protected function normalizeCollectionOfRelations($propertyMetadata$attributeValuestring $resourceClass, ?string $format, array $context): array
  720.     {
  721.         $value = [];
  722.         foreach ($attributeValue as $index => $obj) {
  723.             if (!\is_object($obj) && null !== $obj) {
  724.                 throw new UnexpectedValueException('Unexpected non-object element in to-many relation.');
  725.             }
  726.             $value[$index] = $this->normalizeRelation($propertyMetadata$obj$resourceClass$format$context);
  727.         }
  728.         return $value;
  729.     }
  730.     /**
  731.      * Normalizes a relation.
  732.      *
  733.      * @param ApiProperty|PropertyMetadata $propertyMetadata
  734.      * @param object|null                  $relatedObject
  735.      *
  736.      * @throws LogicException
  737.      * @throws UnexpectedValueException
  738.      *
  739.      * @return string|array|\ArrayObject|null IRI or normalized object data
  740.      */
  741.     protected function normalizeRelation($propertyMetadata$relatedObjectstring $resourceClass, ?string $format, array $context)
  742.     {
  743.         if (null === $relatedObject || !empty($context['attributes']) || $propertyMetadata->isReadableLink()) {
  744.             if (!$this->serializer instanceof NormalizerInterface) {
  745.                 throw new LogicException(sprintf('The injected serializer must be an instance of "%s".'NormalizerInterface::class));
  746.             }
  747.             $normalizedRelatedObject $this->serializer->normalize($relatedObject$format$context);
  748.             // @phpstan-ignore-next-line throwing an explicit exception helps debugging
  749.             if (!\is_string($normalizedRelatedObject) && !\is_array($normalizedRelatedObject) && !$normalizedRelatedObject instanceof \ArrayObject && null !== $normalizedRelatedObject) {
  750.                 throw new UnexpectedValueException('Expected normalized relation to be an IRI, array, \ArrayObject or null');
  751.             }
  752.             return $normalizedRelatedObject;
  753.         }
  754.         $iri $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getIriFromItem($relatedObject) : $this->iriConverter->getIriFromResource($relatedObject);
  755.         if (isset($context['resources'])) {
  756.             $context['resources'][$iri] = $iri;
  757.         }
  758.         $push $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getAttribute('push'false) : ($propertyMetadata->getPush() ?? false);
  759.         if (isset($context['resources_to_push']) && $push) {
  760.             $context['resources_to_push'][$iri] = $iri;
  761.         }
  762.         return $iri;
  763.     }
  764.     /**
  765.      * Finds the first supported data transformer if any.
  766.      *
  767.      * @param object|array $data object on normalize / array on denormalize
  768.      */
  769.     protected function getDataTransformer($datastring $to, array $context = []): ?DataTransformerInterface
  770.     {
  771.         foreach ($this->dataTransformers as $dataTransformer) {
  772.             if ($dataTransformer->supportsTransformation($data$to$context)) {
  773.                 return $dataTransformer;
  774.             }
  775.         }
  776.         return null;
  777.     }
  778.     /**
  779.      * For a given resource, it returns an output representation if any
  780.      * If not, the resource is returned.
  781.      *
  782.      * @param mixed $object
  783.      */
  784.     protected function transformOutput($object, array $context = [], string $outputClass null)
  785.     {
  786.     }
  787.     private function createAttributeValue($attribute$value$format null, array $context = [])
  788.     {
  789.         if (!$this->resourceClassResolver->isResourceClass($context['resource_class'])) {
  790.             return $value;
  791.         }
  792.         /** @var ApiProperty|PropertyMetadata */
  793.         $propertyMetadata $this->propertyMetadataFactory->create($context['resource_class'], $attribute$this->getFactoryOptions($context));
  794.         $type $propertyMetadata instanceof PropertyMetadata $propertyMetadata->getType() : ($propertyMetadata->getBuiltinTypes()[0] ?? null);
  795.         if (null === $type) {
  796.             // No type provided, blindly return the value
  797.             return $value;
  798.         }
  799.         if (null === $value && $type->isNullable()) {
  800.             return $value;
  801.         }
  802.         $collectionValueType method_exists(Type::class, 'getCollectionValueTypes') ? ($type->getCollectionValueTypes()[0] ?? null) : $type->getCollectionValueType();
  803.         /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
  804.         // Fix a collection that contains the only one element
  805.         // This is special to xml format only
  806.         if ('xml' === $format && null !== $collectionValueType && (!\is_array($value) || !\is_int(key($value)))) {
  807.             $value = [$value];
  808.         }
  809.         if (
  810.             $type->isCollection() &&
  811.             null !== $collectionValueType &&
  812.             null !== ($className $collectionValueType->getClassName()) &&
  813.             $this->resourceClassResolver->isResourceClass($className)
  814.         ) {
  815.             $resourceClass $this->resourceClassResolver->getResourceClass(null$className);
  816.             $context['resource_class'] = $resourceClass;
  817.             return $this->denormalizeCollection($attribute$propertyMetadata$type$resourceClass$value$format$context);
  818.         }
  819.         if (
  820.             null !== ($className $type->getClassName()) &&
  821.             $this->resourceClassResolver->isResourceClass($className)
  822.         ) {
  823.             $resourceClass $this->resourceClassResolver->getResourceClass(null$className);
  824.             $childContext $this->createChildContext($context$attribute$format);
  825.             $childContext['resource_class'] = $resourceClass;
  826.             if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  827.                 $childContext['operation'] = $this->resourceMetadataFactory->create($resourceClass)->getOperation();
  828.             }
  829.             return $this->denormalizeRelation($attribute$propertyMetadata$resourceClass$value$format$childContext);
  830.         }
  831.         if (
  832.             $type->isCollection() &&
  833.             null !== $collectionValueType &&
  834.             null !== ($className $collectionValueType->getClassName())
  835.         ) {
  836.             if (!$this->serializer instanceof DenormalizerInterface) {
  837.                 throw new LogicException(sprintf('The injected serializer must be an instance of "%s".'DenormalizerInterface::class));
  838.             }
  839.             unset($context['resource_class']);
  840.             return $this->serializer->denormalize($value$className.'[]'$format$context);
  841.         }
  842.         if (null !== $className $type->getClassName()) {
  843.             if (!$this->serializer instanceof DenormalizerInterface) {
  844.                 throw new LogicException(sprintf('The injected serializer must be an instance of "%s".'DenormalizerInterface::class));
  845.             }
  846.             unset($context['resource_class']);
  847.             return $this->serializer->denormalize($value$className$format$context);
  848.         }
  849.         /* From @see AbstractObjectNormalizer::validateAndDenormalize() */
  850.         // In XML and CSV all basic datatypes are represented as strings, it is e.g. not possible to determine,
  851.         // if a value is meant to be a string, float, int or a boolean value from the serialized representation.
  852.         // That's why we have to transform the values, if one of these non-string basic datatypes is expected.
  853.         if (\is_string($value) && (XmlEncoder::FORMAT === $format || CsvEncoder::FORMAT === $format)) {
  854.             if ('' === $value && $type->isNullable() && \in_array($type->getBuiltinType(), [Type::BUILTIN_TYPE_BOOLType::BUILTIN_TYPE_INTType::BUILTIN_TYPE_FLOAT], true)) {
  855.                 return null;
  856.             }
  857.             switch ($type->getBuiltinType()) {
  858.                 case Type::BUILTIN_TYPE_BOOL:
  859.                     // according to https://www.w3.org/TR/xmlschema-2/#boolean, valid representations are "false", "true", "0" and "1"
  860.                     if ('false' === $value || '0' === $value) {
  861.                         $value false;
  862.                     } elseif ('true' === $value || '1' === $value) {
  863.                         $value true;
  864.                     } else {
  865.                         throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be bool ("%s" given).'$attribute$className$value));
  866.                     }
  867.                     break;
  868.                 case Type::BUILTIN_TYPE_INT:
  869.                     if (ctype_digit($value) || ('-' === $value[0] && ctype_digit(substr($value1)))) {
  870.                         $value = (int) $value;
  871.                     } else {
  872.                         throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be int ("%s" given).'$attribute$className$value));
  873.                     }
  874.                     break;
  875.                 case Type::BUILTIN_TYPE_FLOAT:
  876.                     if (is_numeric($value)) {
  877.                         return (float) $value;
  878.                     }
  879.                     switch ($value) {
  880.                         case 'NaN':
  881.                             return \NAN;
  882.                         case 'INF':
  883.                             return \INF;
  884.                         case '-INF':
  885.                             return -\INF;
  886.                         default:
  887.                             throw new NotNormalizableValueException(sprintf('The type of the "%s" attribute for class "%s" must be float ("%s" given).'$attribute$className$value));
  888.                     }
  889.             }
  890.         }
  891.         if ($context[static::DISABLE_TYPE_ENFORCEMENT] ?? false) {
  892.             return $value;
  893.         }
  894.         $this->validateType($attribute$type$value$format);
  895.         return $value;
  896.     }
  897.     /**
  898.      * Sets a value of the object using the PropertyAccess component.
  899.      *
  900.      * @param object $object
  901.      * @param mixed  $value
  902.      */
  903.     private function setValue($objectstring $attributeName$value)
  904.     {
  905.         try {
  906.             $this->propertyAccessor->setValue($object$attributeName$value);
  907.         } catch (NoSuchPropertyException $exception) {
  908.             // Properties not found are ignored
  909.         }
  910.     }
  911.     /**
  912.      * TODO: to remove in 3.0.
  913.      *
  914.      * @deprecated since 2.7
  915.      */
  916.     private function supportsPlainIdentifiers(): bool
  917.     {
  918.         return $this->allowPlainIdentifiers && null !== $this->itemDataProvider;
  919.     }
  920. }
  921. class_alias(AbstractItemNormalizer::class, \ApiPlatform\Core\Serializer\AbstractItemNormalizer::class);