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

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