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

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\Core\EventListener;
  12. use ApiPlatform\Core\Api\FormatMatcher;
  13. use ApiPlatform\Core\Api\FormatsProviderInterface;
  14. use ApiPlatform\Core\Exception\InvalidArgumentException;
  15. use ApiPlatform\Core\Metadata\Resource\Factory\ResourceMetadataFactoryInterface;
  16. use ApiPlatform\Core\Metadata\Resource\ToggleableOperationAttributeTrait;
  17. use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
  18. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  21. use Symfony\Component\HttpKernel\Exception\UnsupportedMediaTypeHttpException;
  22. use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
  23. use Symfony\Component\Serializer\SerializerInterface;
  24. /**
  25.  * Updates the entity retrieved by the data provider with data contained in the request body.
  26.  *
  27.  * @author Kévin Dunglas <dunglas@gmail.com>
  28.  */
  29. final class DeserializeListener
  30. {
  31.     use ToggleableOperationAttributeTrait;
  32.     public const OPERATION_ATTRIBUTE_KEY 'deserialize';
  33.     private $serializer;
  34.     private $serializerContextBuilder;
  35.     private $formats = [];
  36.     private $formatsProvider;
  37.     private $formatMatcher;
  38.     /**
  39.      * @throws InvalidArgumentException
  40.      */
  41.     public function __construct(SerializerInterface $serializerSerializerContextBuilderInterface $serializerContextBuilder/* FormatsProviderInterface */$formatsProviderResourceMetadataFactoryInterface $resourceMetadataFactory null)
  42.     {
  43.         $this->serializer $serializer;
  44.         $this->serializerContextBuilder $serializerContextBuilder;
  45.         if (\is_array($formatsProvider)) {
  46.             @trigger_error('Using an array as formats provider is deprecated since API Platform 2.3 and will not be possible anymore in API Platform 3'E_USER_DEPRECATED);
  47.             $this->formats $formatsProvider;
  48.         } else {
  49.             if (!$formatsProvider instanceof FormatsProviderInterface) {
  50.                 throw new InvalidArgumentException(sprintf('The "$formatsProvider" argument is expected to be an implementation of the "%s" interface.'FormatsProviderInterface::class));
  51.             }
  52.             $this->formatsProvider $formatsProvider;
  53.         }
  54.         $this->resourceMetadataFactory $resourceMetadataFactory;
  55.     }
  56.     /**
  57.      * Deserializes the data sent in the requested format.
  58.      *
  59.      * @throws UnsupportedMediaTypeHttpException
  60.      */
  61.     public function onKernelRequest(GetResponseEvent $event): void
  62.     {
  63.         $request $event->getRequest();
  64.         $method $request->getMethod();
  65.         if (
  66.             'DELETE' === $method
  67.             || $request->isMethodSafe(false)
  68.             || !($attributes RequestAttributesExtractor::extractAttributes($request))
  69.             || !$attributes['receive']
  70.             || $this->isOperationAttributeDisabled($attributesself::OPERATION_ATTRIBUTE_KEY)
  71.         ) {
  72.             return;
  73.         }
  74.         $context $this->serializerContextBuilder->createFromRequest($requestfalse$attributes);
  75.         // BC check to be removed in 3.0
  76.         if (null !== $this->formatsProvider) {
  77.             $this->formats $this->formatsProvider->getFormatsFromAttributes($attributes);
  78.         }
  79.         $this->formatMatcher = new FormatMatcher($this->formats);
  80.         $format $this->getFormat($request);
  81.         $data $request->attributes->get('data');
  82.         if (null !== $data) {
  83.             $context[AbstractNormalizer::OBJECT_TO_POPULATE] = $data;
  84.         }
  85.         $request->attributes->set(
  86.             'data',
  87.             $this->serializer->deserialize($request->getContent(), $context['resource_class'], $format$context)
  88.         );
  89.     }
  90.     /**
  91.      * Extracts the format from the Content-Type header and check that it is supported.
  92.      *
  93.      * @throws UnsupportedMediaTypeHttpException
  94.      */
  95.     private function getFormat(Request $request): string
  96.     {
  97.         /**
  98.          * @var string|null
  99.          */
  100.         $contentType $request->headers->get('CONTENT_TYPE');
  101.         if (null === $contentType) {
  102.             throw new UnsupportedMediaTypeHttpException('The "Content-Type" header must exist.');
  103.         }
  104.         $format $this->formatMatcher->getFormat($contentType);
  105.         if (null === $format || !isset($this->formats[$format])) {
  106.             $supportedMimeTypes = [];
  107.             foreach ($this->formats as $mimeTypes) {
  108.                 foreach ($mimeTypes as $mimeType) {
  109.                     $supportedMimeTypes[] = $mimeType;
  110.                 }
  111.             }
  112.             throw new UnsupportedMediaTypeHttpException(sprintf(
  113.                 'The content-type "%s" is not supported. Supported MIME types are "%s".',
  114.                 $contentType,
  115.                 implode('", "'$supportedMimeTypes)
  116.             ));
  117.         }
  118.         return $format;
  119.     }
  120. }