Skip to content

Instantly share code, notes, and snippets.

@sokil
Last active October 2, 2016 17:59
Show Gist options
  • Save sokil/e1169ca039e633722beef9d8a4cc0f71 to your computer and use it in GitHub Desktop.
Save sokil/e1169ca039e633722beef9d8a4cc0f71 to your computer and use it in GitHub Desktop.
Convert JSON request in Symfony app
<?php
namespace Sokil\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class JsonRequestListener implements EventSubscriberInterface
{
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if ('json' !== $request->getContentType()) {
return;
}
$content = $request->getContent();
$requestPayload = json_decode($content, true);
// error decoding request
if($requestPayload === null && json_last_error() !== JSON_ERROR_NONE) {
return;
}
$request->request->replace($requestPayload);
}
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array(array('onKernelRequest', 16)),
);
}
}
services:
json_request_listener:
class: Sokil\EventListener\JsonRequestListener
tags:
- {name: kernel.event_listener, event: kernel.request, method: onKernelRequest, priority: -255 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment