Created
January 23, 2018 20:29
-
-
Save peterlafferty/4fa7364231c0d423ed58e498b35c8ae4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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\FilterControllerEvent; | |
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(FilterControllerEvent $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
The
Symfony\Component\HttpKernel\Event\FilterControllerEvent
class is deprecated, I made a fork and I proposed some changes.