Last active
October 2, 2016 17:59
-
-
Save sokil/e1169ca039e633722beef9d8a4cc0f71 to your computer and use it in GitHub Desktop.
Convert JSON request in Symfony app
This file contains hidden or 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 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)), | |
| ); | |
| } | |
| } |
This file contains hidden or 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
| 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