vendor/sylius/sylius/src/Sylius/Bundle/ApiBundle/Serializer/CommandDenormalizer.php line 63

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Sylius package.
  4.  *
  5.  * (c) Paweł Jędrzejewski
  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 Sylius\Bundle\ApiBundle\Serializer;
  12. use Symfony\Component\Serializer\Exception\MissingConstructorArgumentsException;
  13. use Symfony\Component\Serializer\Normalizer\ContextAwareDenormalizerInterface;
  14. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  15. /**
  16.  * @experimental
  17.  */
  18. final class CommandDenormalizer implements ContextAwareDenormalizerInterface
  19. {
  20.     private const OBJECT_TO_POPULATE 'object_to_populate';
  21.     public function __construct(private DenormalizerInterface $itemNormalizer)
  22.     {
  23.     }
  24.     public function supportsDenormalization($data$type$format null, array $context = []): bool
  25.     {
  26.         return isset($context['input']['class']);
  27.     }
  28.     public function denormalize($data$type$format null, array $context = [])
  29.     {
  30.         if (isset($context[self::OBJECT_TO_POPULATE])) {
  31.             return $this->itemNormalizer->denormalize($data$type$format$context);
  32.         }
  33.         $constructor = (new \ReflectionClass($context['input']['class']))->getConstructor();
  34.         if (null !== $constructor) {
  35.             $this->assertConstructorArgumentsPresence($constructor$data);
  36.         }
  37.         return $this->itemNormalizer->denormalize($data$type$format$context);
  38.     }
  39.     private function assertConstructorArgumentsPresence(\ReflectionMethod $constructor$data): void
  40.     {
  41.         $parameters $constructor->getParameters();
  42.         $missingFields = [];
  43.         foreach ($parameters as $parameter) {
  44.             if (!isset($data[$parameter->getName()]) && !($parameter->allowsNull() || $parameter->isDefaultValueAvailable())) {
  45.                 $missingFields[] = $parameter->getName();
  46.             }
  47.         }
  48.         if (count($missingFields) > 0) {
  49.             throw new MissingConstructorArgumentsException(
  50.                 sprintf('Request does not have the following required fields specified: %s.'implode(', '$missingFields)),
  51.             );
  52.         }
  53.     }
  54. }