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

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