Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mateusfmello/a00edbeeffceb5ece4c6006180ab646e to your computer and use it in GitHub Desktop.
Save mateusfmello/a00edbeeffceb5ece4c6006180ab646e to your computer and use it in GitHub Desktop.
<?php
namespace App\EventSubscriber;
use function json_last_error;
use function json_last_error_msg;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\KernelEvents;
class BeforeActionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return array(
KernelEvents::CONTROLLER => 'convertJsonStringToArray',
);
}
public function convertJsonStringToArray(ControllerEvent $event)
{
$request = $event->getRequest();
if ($request->getContentType() != 'json' || !$request->getContent()) {
return;
}
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadRequestHttpException('invalid json body: ' . json_last_error_msg());
}
$request->request->replace(is_array($data) ? $data : array());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment