src/EventSubscriber/BeforeActionSubscriber.php line 17

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