src/Shared/Infrastructure/Symfony/EventListener/JsonToArrayRequestListener.php line 27

  1. <?php
  2. namespace App\Shared\Infrastructure\Symfony\EventListener;
  3. use App\Shared\Domain\Helper\Inflector;
  4. use App\Shared\Infrastructure\Service\Serializer\SerializerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\ParameterBag;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpKernel\Event\RequestEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. final class JsonToArrayRequestListener implements EventSubscriberInterface
  11. {
  12.     public static function getSubscribedEvents()
  13.     {
  14.         return array(
  15.             KernelEvents::REQUEST => 'onKernelRequest'
  16.         );
  17.     }
  18.     public function __construct(private SerializerInterface $serializer)
  19.     {
  20.     }
  21.     public function onKernelRequest(RequestEvent $event): void
  22.     {
  23.         $request $event->getRequest();
  24.         if ($request->getMethod() === Request::METHOD_GET) {
  25.             return;
  26.         }
  27.         $content $request->getContent(false);
  28.         if (!$this->isJson($content)) {
  29.             return;
  30.         }
  31.         $content = new ParameterBag($this->deserialize($content));
  32.         $request->request $content;
  33.     }
  34.     public function onKernelRequests(RequestEvent $event): void
  35.     {
  36.         $request $event->getRequest();
  37.         if ($request->getMethod() !== Request::METHOD_GET) {
  38.             $content $request->getContent(false);
  39.             if ($this->isJson($content)) {
  40.                 $content = new ParameterBag($this->deserialize($content));
  41.                 $request->request $content;
  42.             }
  43.         }
  44.     }
  45.     private function isJson($string)
  46.     {
  47.         json_decode($string);
  48.         return (json_last_error() === JSON_ERROR_NONE);
  49.     }
  50.     private function deserialize(string $content)
  51.     {
  52.         $data $this->serializer->deserialize($content);
  53.         return $this->decamelize($data);
  54.     }
  55.     private function decamelize(array $data)
  56.     {
  57.         $newArray = array();
  58.         foreach ($data as $k => $v) {
  59.             $value $data[$k];
  60.             if (is_array($data[$k])) {
  61.                 $value self::decamelize($data[$k]);
  62.             }
  63.             $key Inflector::fromCamelCaseToSnakeCase($k);
  64.             $newArray[$key] = $value;
  65.         }
  66.         return $newArray;
  67.     }
  68. }