src/EventListener/DeserializeListener.php line 34

Open in your IDE?
  1. <?php
  2. /*
  3.  * Created on Fri Dec 02 2022
  4.  *
  5.  * DAVID-OLIVIER DESCOMBES
  6.  *
  7.  * @licence
  8.  * You may not sell, sub-license, rent or lease any portion of the Software or Documentation to anyone.
  9.  *
  10.  * Copyright (c) 2022 dodarchitecte.com (https://dodarchitecte.com)
  11.  *
  12.  * Developed by developpeur-informatique.ma (https://www.developpeur-informatique.ma)
  13.  */
  14. namespace App\EventListener;
  15. use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
  16. use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
  17. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  18. use Symfony\Component\HttpFoundation\Request;
  19. use Symfony\Component\HttpKernel\Event\RequestEvent;
  20. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  21. class DeserializeListener
  22. {
  23.     public function __construct(
  24.         private DecoratedListener $decorated,
  25.         private SerializerContextBuilderInterface $serializerContextBuilder,
  26.         private DenormalizerInterface $denormalizer,
  27.     ) {
  28.     }
  29.     public function onKernelRequest(RequestEvent $event): void
  30.     {
  31.         // dd($event->getRequest()->getContentType());
  32.         $request $event->getRequest();
  33.         if ($request->isMethodCacheable() || $request->isMethod(Request::METHOD_DELETE))
  34.             return;
  35.         if ($request->getContentType() === 'multipart' || $request->getContentType() === 'form' || $request->getContentType() === 'multipart/form-data') {
  36.             $this->denormalizeFormRequest($request);
  37.         } else {
  38.             $this->decorated->onKernelRequest($event);
  39.         }
  40.         // $this->decorated->onKernelRequest($event);
  41.     }
  42.     private function denormalizeFormRequest(Request $request): void
  43.     {
  44.         $attributs =  RequestAttributesExtractor::extractAttributes($request);
  45.         if (empty($attributs))
  46.             return;
  47.         else {
  48.             
  49.             $context $this->serializerContextBuilder->createFromRequest($requestfalse$attributs);
  50.             $populated $request->attributes->get('data');
  51.             if($populated != null)
  52.               $context['object_to_populate'] = $populated;
  53.             $data $request->request->all();
  54.             $files $request->files->all();
  55.             // dd($files);
  56.             $object $this->denormalizer->denormalize(array_merge($data$files), $attributs['resource_class'], null$context);
  57.             $request->attributes->set('data'$object);
  58.         }
  59.     }
  60. }