Skip to content

Instantly share code, notes, and snippets.

@gnugat
Created October 3, 2014 10:05
Show Gist options
  • Save gnugat/20ce20dd75bf7df5f269 to your computer and use it in GitHub Desktop.
Save gnugat/20ce20dd75bf7df5f269 to your computer and use it in GitHub Desktop.
gnugat/ripozi - SubmitJsonListener
<?php
namespace Gnugat\Ripozi\EventListener;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* PHP does not populate $_POST with the data submitted via a JSON Request,
* causing an empty $request->request.
*
* This listener fixes this.
*/
class SubmitJsonListener
{
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
$contentType = $request->headers->get('Content-Type');
if ('POST' !== $request->getMethod() && 'application/json' !== $contentType) {
return;
}
$content = $request->getContent();
$data = json_decode($content, true);
if (JSON_ERROR_NONE !== json_last_error()) {
$data = array('message' => 'Invalid or malformed JSON');
$response = new JsonResponse($data, 400);
$event->setResponse($this->render);
}
$request->request->add($data ?: array());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment