<?php
/*
* Created on Fri Dec 02 2022
*
* DAVID-OLIVIER DESCOMBES
*
* @licence
* You may not sell, sub-license, rent or lease any portion of the Software or Documentation to anyone.
*
* Copyright (c) 2022 dodarchitecte.com (https://dodarchitecte.com)
*
* Developed by developpeur-informatique.ma (https://www.developpeur-informatique.ma)
*/
namespace App\EventListener;
use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
use ApiPlatform\Core\Util\RequestAttributesExtractor;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
class DeserializeListener
{
public function __construct(
private DecoratedListener $decorated,
private SerializerContextBuilderInterface $serializerContextBuilder,
private DenormalizerInterface $denormalizer,
) {
}
public function onKernelRequest(RequestEvent $event): void
{
// dd($event->getRequest()->getContentType());
$request = $event->getRequest();
if ($request->isMethodCacheable() || $request->isMethod(Request::METHOD_DELETE))
return;
if ($request->getContentType() === 'multipart' || $request->getContentType() === 'form' || $request->getContentType() === 'multipart/form-data') {
$this->denormalizeFormRequest($request);
} else {
$this->decorated->onKernelRequest($event);
}
// $this->decorated->onKernelRequest($event);
}
private function denormalizeFormRequest(Request $request): void
{
$attributs = RequestAttributesExtractor::extractAttributes($request);
if (empty($attributs))
return;
else {
$context = $this->serializerContextBuilder->createFromRequest($request, false, $attributs);
$populated = $request->attributes->get('data');
if($populated != null)
$context['object_to_populate'] = $populated;
$data = $request->request->all();
$files = $request->files->all();
// dd($files);
$object = $this->denormalizer->denormalize(array_merge($data, $files), $attributs['resource_class'], null, $context);
$request->attributes->set('data', $object);
}
}
}