src/EventListener/DeserializeListener.php line 18

Open in your IDE?
  1. <?php
  2. namespace MedBrief\MSR\EventListener;
  3. use ApiPlatform\Core\EventListener\DeserializeListener as DecoratedListener;
  4. use ApiPlatform\Core\Serializer\SerializerContextBuilderInterface;
  5. use ApiPlatform\Core\Util\RequestAttributesExtractor;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Serializer\Normalizer\DenormalizerInterface;
  9. class DeserializeListener
  10. {
  11. public function __construct(private readonly DenormalizerInterface $denormalizer, private readonly SerializerContextBuilderInterface $serializerContextBuilder, private readonly DecoratedListener $decorated)
  12. {
  13. }
  14. public function onKernelRequest(RequestEvent $event): void
  15. {
  16. $request = $event->getRequest();
  17. if ($request->isMethodSafe() || $request->isMethod(Request::METHOD_DELETE)) {
  18. return;
  19. }
  20. if ('form' === $request->getContentType()) {
  21. $this->denormalizeFormRequest($request);
  22. } else {
  23. $this->decorated->onKernelRequest($event);
  24. }
  25. }
  26. private function denormalizeFormRequest(Request $request): void
  27. {
  28. if (!$attributes = RequestAttributesExtractor::extractAttributes($request)) {
  29. return;
  30. }
  31. $context = $this->serializerContextBuilder->createFromRequest($request, false, $attributes);
  32. $populated = $request->attributes->get('data');
  33. if (null !== $populated) {
  34. $context['object_to_populate'] = $populated;
  35. }
  36. $data = $request->request->all();
  37. $object = $this->denormalizer->denormalize($data, $attributes['resource_class'], null, $context);
  38. $request->attributes->set('data', $object);
  39. }
  40. }