Created
October 14, 2013 12:29
-
-
Save alex88/6974874 to your computer and use it in GitHub Desktop.
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 Acme\DemoBundle\Annotation; | |
/** | |
* The Annotation class | |
* | |
* @Annotation | |
*/ | |
class RequestJsonDecoder | |
{ | |
} |
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 Acme\DemoBundle\Annotation\Driver; | |
use Doctrine\Common\Annotations\Reader; | |
use Symfony\Bridge\Monolog\Logger; | |
use Symfony\Component\HttpFoundation\ParameterBag; | |
use Symfony\Component\HttpKernel\Event\FilterControllerEvent; | |
use Acme\DemoBundle\Exception\WrongArgumentsException; | |
use Acme\DemoBundle\Annotations; | |
/** | |
* A listener that decodes a json from a request in case the related annotation is present | |
*/ | |
class RequestJsonDecoder | |
{ | |
private $reader; | |
private $logger; | |
/** | |
* Construct the service with the annotation reader | |
* | |
* @param mixed $reader The annotation reader | |
* @param Logger $logger The logger service | |
*/ | |
public function __construct($reader, Logger $logger) | |
{ | |
$this->reader = $reader; | |
$this->logger = $logger; | |
} | |
/** | |
* This event will fire during any controller call | |
* This will check if there is the RequestJsonDecoder() annotation | |
* | |
* @param FilterControllerEvent $event THe controller call event | |
* | |
* @throws \Acme\DemoBundle\Exception\WrongArgumentsException | |
*/ | |
public function onKernelController(FilterControllerEvent $event) | |
{ | |
if (!is_array($controller = $event->getController())) { | |
return; | |
} | |
$object = new \ReflectionObject($controller[0]); | |
$method = $object->getMethod($controller[1]); | |
foreach ($this->reader->getMethodAnnotations($method) as $configuration) { | |
if (get_class($configuration) == 'Acme\DemoBundle\Annotation\RequestJsonDecoder') { | |
$request = $event->getRequest(); | |
if (!count($request->request->all()) && in_array($request->getMethod(), array('POST', 'PUT', 'PATCH', 'DELETE')) && $request->getContent() != '') { | |
$data = json_decode($request->getContent(), true); | |
if (is_null($data)) { | |
$this->logger->err('Error parsing request json'); | |
throw new WrongArgumentsException(null, 'Json error'); | |
} | |
if (is_array($data)) { | |
$request->request = new ParameterBag($data); | |
} | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment