Skip to content

Instantly share code, notes, and snippets.

@Tjorriemorrie
Created March 6, 2014 12:38
Show Gist options
  • Save Tjorriemorrie/9388696 to your computer and use it in GitHub Desktop.
Save Tjorriemorrie/9388696 to your computer and use it in GitHub Desktop.
Listener for JMS Serializer
<?php
namespace Talentec\MainBundle\Listener;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Doctrine\Common\Annotations\Reader;
use Doctrine\Common\Util\ClassUtils;
use Talentec\MainBundle\Annotation\Serialize;
use Symfony\Component\HttpFoundation\JsonResponse;
use JMS\Serializer\Serializer;
class JsonSerializerListener
{
/** @var \Doctrine\Common\Annotations\Reader */
private $annotationReader;
/** @var Serializer */
private $serializer;
/** @var Serialize */
private $serializeAnnotation;
public function __construct(Reader $annotationReader, Serializer $serializer)
{
$this->annotationReader = $annotationReader;
$this->serializer = $serializer;
}
public function onKernelController(FilterControllerEvent $event)
{
//die(var_dump($event));
$controller = $event->getController();
//die(var_dump($controller));
list($object, $method) = $controller;
//die(var_dump($object));
//die(var_dump($method));
// the controller could be a proxy, e.g. when using the JMSSecuriyExtraBundle or JMSDiExtraBundle
$className = ClassUtils::getClass($object);
//die(var_dump($className));
$reflectionClass = new \ReflectionClass($className);
$reflectionMethod = $reflectionClass->getMethod($method);
//die(var_dump($reflectionMethod));
$allAnnotations = $this->annotationReader->getMethodAnnotations($reflectionMethod);
//die(var_dump($allAnnotations));
$serializeAnnotations = array_filter($allAnnotations, function($annotation) {
return $annotation instanceof Serialize;
});
$this->serializeAnnotation = reset($serializeAnnotations);
}
public function onKernelView(GetResponseForControllerResultEvent $event)
{
//die(var_dump($event));
//die(var_dump($event->getControllerResult()));
$data = $event->getControllerResult();
// die(var_dump($this->serializeAnnotation));
// die(var_dump($this->serializeAnnotation->getSerializationContext()));
if ($this->serializeAnnotation) {
$dataSerialized = $this->serializer->serialize(
$data,
$this->serializeAnnotation->getFormat(),
$this->serializeAnnotation->getSerializationContext()
);
$response = new JsonResponse();
$response->setContent($dataSerialized);
$event->setResponse($response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment