vendor/api-platform/core/src/Symfony/EventListener/DeserializeListener.php line 64

  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\Symfony\EventListener;
  12. use ApiPlatform\Api\FormatMatcher;
  13. use ApiPlatform\Metadata\HttpOperation;
  14. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  15. use ApiPlatform\Serializer\SerializerContextBuilderInterface;
  16. use ApiPlatform\Symfony\Validator\Exception\ValidationException;
  17. use ApiPlatform\Util\OperationRequestInitiatorTrait;
  18. use ApiPlatform\Util\RequestAttributesExtractor;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpKernel\Event\RequestEvent;
  21. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  22. use Symfony\Component\Serializer\Exception\NotNormalizableValueException;
  23. use Symfony\Component\Serializer\Exception\PartialDenormalizationException;
  24. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  25. use Symfony\Component\Serializer\SerializerInterface;
  26. use Symfony\Component\Validator\Constraints\Type;
  27. use Symfony\Component\Validator\ConstraintViolation;
  28. use Symfony\Component\Validator\ConstraintViolationList;
  29. use Symfony\Contracts\Translation\LocaleAwareInterface;
  30. use Symfony\Contracts\Translation\TranslatorInterface;
  31. use Symfony\Contracts\Translation\TranslatorTrait;
  32. /**
  33.  * Updates the entity retrieved by the data provider with data contained in the request body.
  34.  *
  35.  * @author Kévin Dunglas <dunglas@gmail.com>
  36.  */
  37. final class DeserializeListener
  38. {
  39.     use OperationRequestInitiatorTrait;
  40.     public const OPERATION_ATTRIBUTE_KEY 'deserialize';
  41.     public function __construct(private readonly SerializerInterface $serializer, private readonly SerializerContextBuilderInterface $serializerContextBuilder, ?ResourceMetadataCollectionFactoryInterface $resourceMetadataFactory null, private ?TranslatorInterface $translator null)
  42.     {
  43.         $this->resourceMetadataCollectionFactory $resourceMetadataFactory;
  44.         if (null === $this->translator) {
  45.             $this->translator = new class() implements TranslatorInterfaceLocaleAwareInterface {
  46.                 use TranslatorTrait;
  47.             };
  48.             $this->translator->setLocale('en');
  49.         }
  50.     }
  51.     /**
  52.      * Deserializes the data sent in the requested format.
  53.      *
  54.      * @throws UnsupportedMediaTypeHttpException
  55.      */
  56.     public function onKernelRequest(RequestEvent $event): void
  57.     {
  58.         $request $event->getRequest();
  59.         $method $request->getMethod();
  60.         if (
  61.             'DELETE' === $method
  62.             || $request->isMethodSafe()
  63.             || !($attributes RequestAttributesExtractor::extractAttributes($request))
  64.             || !$attributes['receive']
  65.         ) {
  66.             return;
  67.         }
  68.         $operation $this->initializeOperation($request);
  69.         if (!($operation?->canDeserialize() ?? true)) {
  70.             return;
  71.         }
  72.         $context $this->serializerContextBuilder->createFromRequest($requestfalse$attributes);
  73.         $format $this->getFormat($request$operation?->getInputFormats() ?? []);
  74.         $data $request->attributes->get('data');
  75.         if (
  76.             null !== $data &&
  77.             (
  78.                 HttpOperation::METHOD_POST === $method ||
  79.                 HttpOperation::METHOD_PATCH === $method ||
  80.                 (HttpOperation::METHOD_PUT === $method && !($operation->getExtraProperties()['standard_put'] ?? false))
  81.             )
  82.         ) {
  83.             $context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
  84.         }
  85.         try {
  86.             $request->attributes->set(
  87.                 'data',
  88.                 $this->serializer->deserialize($request->getContent(), $context['resource_class'], $format$context)
  89.             );
  90.         } catch (PartialDenormalizationException $e) {
  91.             $violations = new ConstraintViolationList();
  92.             foreach ($e->getErrors() as $exception) {
  93.                 if (!$exception instanceof NotNormalizableValueException) {
  94.                     continue;
  95.                 }
  96.                 $message = (new Type($exception->getExpectedTypes() ?? []))->message;
  97.                 $parameters = [];
  98.                 if ($exception->canUseMessageForUser()) {
  99.                     $parameters['hint'] = $exception->getMessage();
  100.                 }
  101.                 $violations->add(new ConstraintViolation($this->translator->trans($message, ['{{ type }}' => implode('|'$exception->getExpectedTypes() ?? [])], 'validators'), $message$parametersnull$exception->getPath(), nullnull, (string) $exception->getCode()));
  102.             }
  103.             if (!== \count($violations)) {
  104.                 throw new ValidationException($violations);
  105.             }
  106.         }
  107.     }
  108.     /**
  109.      * Extracts the format from the Content-Type header and check that it is supported.
  110.      *
  111.      * @throws UnsupportedMediaTypeHttpException
  112.      */
  113.     private function getFormat(Request $request, array $formats): string
  114.     {
  115.         /** @var ?string $contentType */
  116.         $contentType $request->headers->get('CONTENT_TYPE');
  117.         if (null === $contentType) {
  118.             throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.');
  119.         }
  120.         $formatMatcher = new FormatMatcher($formats);
  121.         $format $formatMatcher->getFormat($contentType);
  122.         if (null === $format) {
  123.             $supportedMimeTypes = [];
  124.             foreach ($formats as $mimeTypes) {
  125.                 foreach ($mimeTypes as $mimeType) {
  126.                     $supportedMimeTypes[] = $mimeType;
  127.                 }
  128.             }
  129.             throw new UnsupportedMediaTypeHttpException(sprintf('The content-type "%s" is not supported. Supported MIME types are "%s".'$contentTypeimplode('", "'$supportedMimeTypes)));
  130.         }
  131.         return $format;
  132.     }
  133. }