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

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