Forked from peterlafferty/symfony-json-body-BeforeActionSubscriber.php
Last active
July 17, 2019 06:03
-
-
Save mateusfmello/a00edbeeffceb5ece4c6006180ab646e 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\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