src/EventListener/JsonRequestListener.php line 46

Open in your IDE?
  1. <?php
  2. /*
  3. * Disclaimer: This source code is protected by copyright law and by
  4. * international conventions.
  5. *
  6. * Any reproduction or partial or total distribution of the source code, by any
  7. * means whatsoever, is strictly forbidden.
  8. *
  9. * Anyone not complies with these provisions will be guilty of the offense of
  10. * infringement and the penal sanctions provided for by law.
  11. *
  12. * © 2022 All rights reserved.
  13. */
  14. namespace App\EventListener;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  17. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  18. use Symfony\Component\HttpKernel\KernelEvents;
  19. /**
  20.  * Class JsonRequestListener
  21.  *
  22.  * @author Rémy P. <r.peyron@ingeno.eu>
  23.  * @package App\EventListener
  24.  */
  25. class JsonRequestListener implements EventSubscriberInterface
  26. {
  27.     /**
  28.      * @return string[]
  29.      */
  30.     public static function getSubscribedEvents(): array
  31.     {
  32.         return [KernelEvents::CONTROLLER => 'convertJsonStringToArray'];
  33.     }
  34.     /**
  35.      * @param ControllerEvent $event
  36.      * @return void
  37.      */
  38.     public function convertJsonStringToArray(ControllerEvent $event)
  39.     {
  40.         $request $event->getRequest();
  41.         if ($request->getContentType() !== 'json' || !$request->getContent()) {
  42.             return;
  43.         }
  44.         $data json_decode($request->getContent(), true);
  45.         if (json_last_error() !== JSON_ERROR_NONE) {
  46.             throw new BadRequestHttpException('invalid json body: ' json_last_error_msg());
  47.         }
  48.         $request->request->replace(is_array($data) ? $data : []);
  49.     }
  50. }