src/EventSubscriber/BeforeActionSubscriber.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  5. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  6. use Symfony\Component\HttpKernel\KernelEvents;
  7. class BeforeActionSubscriber implements EventSubscriberInterface
  8. {
  9.     public static function getSubscribedEvents()
  10.     {
  11.         return array(
  12.             KernelEvents::CONTROLLER => 'convertJsonStringToArray',
  13.         );
  14.     }
  15.     public function convertJsonStringToArray(ControllerEvent $event)
  16.     {
  17.         $request $event->getRequest();
  18.         if ($request->getContentType() != 'json' || !$request->getContent()) {
  19.             return;
  20.         }
  21.         $data json_decode($request->getContent(), true);
  22.         if (json_last_error() !== JSON_ERROR_NONE) {
  23.             throw new BadRequestHttpException('invalid json body: '.json_last_error_msg());
  24.         }
  25.         $request->request->replace(is_array($data) ? $data : array());
  26.     }
  27. }