vendor/lightbulb/symfony-common/src/EventSubscriber/ApiRequestPreProcessBodySubscriber.php line 40

Open in your IDE?
  1. <?php
  2. namespace Lightbulb\Symfony\EventSubscriber;
  3. use Lightbulb\Symfony\Controller\AbstractApiController;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpKernel\Event\ControllerArgumentsEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. use Symfony\Component\Serializer\Encoder\DecoderInterface;
  9. use Symfony\Component\Serializer\Exception\UnexpectedValueException;
  10. class ApiRequestPreProcessBodySubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var DecoderInterface
  14.      */
  15.     private $jsonDecoder;
  16.     /**
  17.      * ApiRequestValidationSubscriber constructor.
  18.      *
  19.      * @param DecoderInterface $jsonDecoder
  20.      */
  21.     public function __construct(DecoderInterface $jsonDecoder)
  22.     {
  23.         $this->jsonDecoder $jsonDecoder;
  24.     }
  25.     /**
  26.      * {@inheritDoc}
  27.      */
  28.     public static function getSubscribedEvents(): array
  29.     {
  30.         return [
  31.             KernelEvents::CONTROLLER_ARGUMENTS => 'onKernelControllerArguments',
  32.         ];
  33.     }
  34.     public function onKernelControllerArguments(ControllerArgumentsEvent $event): void
  35.     {
  36.         $controller $event->getController();
  37.         // when a controller class defines multiple action methods, the controller
  38.         // is returned as [$controllerInstance, 'methodName']
  39.         if (is_array($controller)) {
  40.             $controller $controller[0];
  41.         }
  42.         if ($controller instanceof AbstractApiController) {
  43.             foreach ($event->getArguments() as $argument) {
  44.                 if ($argument instanceof Request && 'json' === $argument->getContentType() && false === empty($argument->getContent())) {
  45.                     try {
  46.                         $content $this->jsonDecoder->decode($argument->getContent(), 'json');
  47.                         foreach ($content as $key => $value) {
  48.                             $argument->request->set($key$value);
  49.                         }
  50.                     } catch (UnexpectedValueException $e) {
  51.                     }
  52.                     break;
  53.                 }
  54.             }
  55.         }
  56.     }
  57. }