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

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\Core\Api\FormatsProviderInterface;
  14. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  15. use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
  16. use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
  17. use ApiPlatform\Serializer\SerializerContextBuilderInterface;
  18. use ApiPlatform\Util\OperationRequestInitiatorTrait;
  19. use ApiPlatform\Util\RequestAttributesExtractor;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpKernel\Event\RequestEvent;
  22. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  23. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  24. use Symfony\Component\Serializer\SerializerInterface;
  25. /**
  26.  * Updates the entity retrieved by the data provider with data contained in the request body.
  27.  *
  28.  * @author Kévin Dunglas <dunglas@gmail.com>
  29.  */
  30. final class DeserializeListener
  31. {
  32.     use OperationRequestInitiatorTrait;
  33.     use ToggleableOperationAttributeTrait;
  34.     public const OPERATION_ATTRIBUTE_KEY 'deserialize';
  35.     private $serializer;
  36.     private $serializerContextBuilder;
  37.     private $formats;
  38.     private $formatsProvider;
  39.     /**
  40.      * @param ResourceMetadataCollectionFactoryInterface|ResourceMetadataFactoryInterface|FormatsProviderInterface|array $resourceMetadataFactory
  41.      */
  42.     public function __construct(SerializerInterface $serializerSerializerContextBuilderInterface $serializerContextBuilder$resourceMetadataFactory)
  43.     {
  44.         $this->serializer $serializer;
  45.         $this->serializerContextBuilder $serializerContextBuilder;
  46.         $this->resourceMetadataFactory $resourceMetadataFactory;
  47.         if ($resourceMetadataFactory) {
  48.             if (!$resourceMetadataFactory instanceof ResourceMetadataFactoryInterface && !$resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  49.                 @trigger_error(sprintf('Passing an array or an instance of "%s" as 3rd parameter of the constructor of "%s" is deprecated since API Platform 2.5, pass an instance of "%s" instead'FormatsProviderInterface::class, __CLASS__ResourceMetadataFactoryInterface::class), \E_USER_DEPRECATED);
  50.             }
  51.             if ($resourceMetadataFactory instanceof ResourceMetadataFactoryInterface && !$resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  52.                 trigger_deprecation('api-platform/core''2.7'sprintf('Use "%s" instead of "%s".'ResourceMetadataCollectionFactoryInterface::class, ResourceMetadataFactoryInterface::class));
  53.             }
  54.             if ($resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface) {
  55.                 $this->resourceMetadataCollectionFactory $resourceMetadataFactory;
  56.             }
  57.         }
  58.         if (\is_array($resourceMetadataFactory)) {
  59.             $this->formats $resourceMetadataFactory;
  60.         } elseif ($resourceMetadataFactory instanceof FormatsProviderInterface) {
  61.             $this->formatsProvider $resourceMetadataFactory;
  62.         }
  63.     }
  64.     /**
  65.      * Deserializes the data sent in the requested format.
  66.      *
  67.      * @throws UnsupportedMediaTypeHttpException
  68.      */
  69.     public function onKernelRequest(RequestEvent $event): void
  70.     {
  71.         $request $event->getRequest();
  72.         $method $request->getMethod();
  73.         $operation $this->initializeOperation($request);
  74.         if (
  75.             'DELETE' === $method
  76.             || $request->isMethodSafe()
  77.             || !($attributes RequestAttributesExtractor::extractAttributes($request))
  78.         ) {
  79.             return;
  80.         }
  81.         if ($this->resourceMetadataFactory instanceof ResourceMetadataCollectionFactoryInterface &&
  82.             (!$operation || !($operation->canDeserialize() ?? true) || !$attributes['receive'])
  83.         ) {
  84.             return;
  85.         }
  86.         if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface && (
  87.             !$attributes['receive']
  88.             || $this->isOperationAttributeDisabled($attributesself::OPERATION_ATTRIBUTE_KEY)
  89.         )) {
  90.             return;
  91.         }
  92.         $context $this->serializerContextBuilder->createFromRequest($requestfalse$attributes);
  93.         $formats $operation $operation->getInputFormats() ?? null null;
  94.         if (!$formats) {
  95.             // BC check to be removed in 3.0
  96.             if ($this->resourceMetadataFactory instanceof ResourceMetadataFactoryInterface) {
  97.                 @trigger_error('When using a "route_name", be sure to define the "_api_operation" route defaults as we will not rely on metadata in API Platform 3.0.'\E_USER_DEPRECATED);
  98.                 $formats $this->resourceMetadataFactory
  99.                     ->create($attributes['resource_class'])
  100.                     ->getOperationAttribute($attributes'input_formats', [], true);
  101.             } elseif ($this->formatsProvider instanceof FormatsProviderInterface) {
  102.                 $formats $this->formatsProvider->getFormatsFromAttributes($attributes);
  103.             } else {
  104.                 $formats $this->formats;
  105.             }
  106.         }
  107.         $format $this->getFormat($request$formats);
  108.         $data $request->attributes->get('data');
  109.         if (null !== $data) {
  110.             $context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
  111.         }
  112.         $request->attributes->set(
  113.             'data',
  114.             $this->serializer->deserialize($request->getContent(), $context['resource_class'], $format$context)
  115.         );
  116.     }
  117.     /**
  118.      * Extracts the format from the Content-Type header and check that it is supported.
  119.      *
  120.      * @throws UnsupportedMediaTypeHttpException
  121.      */
  122.     private function getFormat(Request $request, array $formats): string
  123.     {
  124.         /**
  125.          * @var string|null
  126.          */
  127.         $contentType $request->headers->get('CONTENT_TYPE');
  128.         if (null === $contentType) {
  129.             throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.');
  130.         }
  131.         $formatMatcher = new FormatMatcher($formats);
  132.         $format $formatMatcher->getFormat($contentType);
  133.         if (null === $format) {
  134.             $supportedMimeTypes = [];
  135.             foreach ($formats as $mimeTypes) {
  136.                 foreach ($mimeTypes as $mimeType) {
  137.                     $supportedMimeTypes[] = $mimeType;
  138.                 }
  139.             }
  140.             throw new UnsupportedMediaTypeHttpException(sprintf('The content-type "%s" is not supported. Supported MIME types are "%s".'$contentTypeimplode('", "'$supportedMimeTypes)));
  141.         }
  142.         return $format;
  143.     }
  144. }
  145. class_alias(DeserializeListener::class, \ApiPlatform\Core\EventListener\DeserializeListener::class);