<?php
namespace App\EventListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
class KernelListener
{
public function onKernelRequest(RequestEvent $event)
{
$request = $event->getRequest();
if ($this->isJsonRequest($request) === false) {
return;
}
if ($this->decodeRequest($request) === false) {
$response = new Response('Unable to parse request.', 400);
$event->setResponse($response);
}
}
private function isJsonRequest(Request $request): bool
{
return 'json' === $request->getContentType() && $request->getContent();
}
private function decodeRequest(Request $request): bool
{
$data = json_decode($request->getContent(), true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false;
}
if (is_array($data)) {
$request->request->replace($data);
}
return true;
}
}