vendor/api-platform/core/src/Serializer/ItemNormalizer.php line 45

  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\DataProvider\ItemDataProviderInterface;
  16. use ApiPlatform\Core\Metadata\Property\Factory\PropertyNameCollectionFactoryInterface;
  17. use ApiPlatform\Exception\InvalidArgumentException;
  18. use ApiPlatform\Symfony\Security\ResourceAccessCheckerInterface;
  19. use Psr\Log\LoggerInterface;
  20. use Psr\Log\NullLogger;
  21. use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
  22. use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
  23. use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactoryInterface;
  24. use Symfony\Component\Serializer\NameConverter\NameConverterInterface;
  25. /**
  26.  * Generic item normalizer.
  27.  *
  28.  * @author Kévin Dunglas <dunglas@gmail.com>
  29.  */
  30. class ItemNormalizer extends AbstractItemNormalizer
  31. {
  32.     private $logger;
  33.     /**
  34.      * @param mixed                                             $propertyMetadataFactory
  35.      * @param LegacyIriConverterInterface|IriConverterInterface $iriConverter
  36.      * @param mixed                                             $resourceClassResolver
  37.      * @param mixed|null                                        $resourceMetadataFactory
  38.      */
  39.     public function __construct(PropertyNameCollectionFactoryInterface $propertyNameCollectionFactory$propertyMetadataFactory$iriConverter$resourceClassResolverPropertyAccessorInterface $propertyAccessor nullNameConverterInterface $nameConverter nullClassMetadataFactoryInterface $classMetadataFactory nullItemDataProviderInterface $itemDataProvider nullbool $allowPlainIdentifiers falseLoggerInterface $logger nulliterable $dataTransformers = [], $resourceMetadataFactory nullResourceAccessCheckerInterface $resourceAccessChecker null, array $defaultContext = [])
  40.     {
  41.         parent::__construct($propertyNameCollectionFactory$propertyMetadataFactory$iriConverter$resourceClassResolver$propertyAccessor$nameConverter$classMetadataFactory$itemDataProvider$allowPlainIdentifiers$defaultContext$dataTransformers$resourceMetadataFactory$resourceAccessChecker);
  42.         $this->logger $logger ?: new NullLogger();
  43.     }
  44.     /**
  45.      * {@inheritdoc}
  46.      *
  47.      * @throws NotNormalizableValueException
  48.      *
  49.      * @return mixed
  50.      */
  51.     public function denormalize($data$class$format null, array $context = [])
  52.     {
  53.         // Avoid issues with proxies if we populated the object
  54.         if (isset($data['id']) && !isset($context[self::OBJECT_TO_POPULATE])) {
  55.             if (isset($context['api_allow_update']) && true !== $context['api_allow_update']) {
  56.                 throw new NotNormalizableValueException('Update is not allowed for this operation.');
  57.             }
  58.             if (isset($context['resource_class'])) {
  59.                 $this->updateObjectToPopulate($data$context);
  60.             } else {
  61.                 // See https://github.com/api-platform/core/pull/2326 to understand this message.
  62.                 $this->logger->warning('The "resource_class" key is missing from the context.', [
  63.                     'context' => $context,
  64.                 ]);
  65.             }
  66.         }
  67.         return parent::denormalize($data$class$format$context);
  68.     }
  69.     private function updateObjectToPopulate(array $data, array &$context): void
  70.     {
  71.         try {
  72.             $context[self::OBJECT_TO_POPULATE] = $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getItemFromIri((string) $data['id'], $context + ['fetch_data' => true]) : $this->iriConverter->getResourceFromIri((string) $data['id'], $context + ['fetch_data' => true]);
  73.         } catch (InvalidArgumentException $e) {
  74.             if ($this->iriConverter instanceof LegacyIriConverterInterface) {
  75.                 // remove in 3.0
  76.                 $identifier null;
  77.                 $options $this->getFactoryOptions($context);
  78.                 foreach ($this->propertyNameCollectionFactory->create($context['resource_class'], $options) as $propertyName) {
  79.                     if (true === $this->propertyMetadataFactory->create($context['resource_class'], $propertyName)->isIdentifier()) {
  80.                         $identifier $propertyName;
  81.                         break;
  82.                     }
  83.                 }
  84.                 if (null === $identifier) {
  85.                     throw $e;
  86.                 }
  87.                 $iri sprintf('%s/%s'$this->iriConverter->getIriFromResourceClass($context['resource_class']), $data[$identifier]);
  88.             } else {
  89.                 $operation $this->resourceMetadataFactory->create($context['resource_class'])->getOperation();
  90.                 // todo: we could guess uri variables with the operation and the data instead of hardcoding id
  91.                 $iri $this->iriConverter->getIriFromResource($context['resource_class'], UrlGeneratorInterface::ABS_PATH$operation, ['uri_variables' => ['id' => $data['id']]]);
  92.             }
  93.             $context[self::OBJECT_TO_POPULATE] = $this->iriConverter instanceof LegacyIriConverterInterface $this->iriConverter->getItemFromIri($iri, ['fetch_data' => true]) : $this->iriConverter->getResourceFromIri($iri, ['fetch_data' => true]);
  94.         }
  95.     }
  96. }
  97. class_alias(ItemNormalizer::class, \ApiPlatform\Core\Serializer\ItemNormalizer::class);