Skip to content

Instantly share code, notes, and snippets.

@docteurklein
Created May 28, 2013 12:22
Show Gist options
  • Save docteurklein/5662375 to your computer and use it in GitHub Desktop.
Save docteurklein/5662375 to your computer and use it in GitHub Desktop.
services:
ss.serializer.serializer_listener:
class: SerializerListener
arguments:
- '@router' # surely you want to inject liipimagine stuff
tags:
- { name: jms_serializer.event_listener, event: serializer.post_serialize, method: onPostSerialize, class: SuperObjectWithPath, format: json, direction: serialization }
<?php
use Symfony\Bundle\FrameworkBundle\Routing\Router;
use JMS\Serializer\EventDispatcher\Event;
use Symfony\Component\Form\Util\PropertyPath;
class SerializerListener
{
private $router;
private $map;
public function __construct(Router $router, array $map)
{
$this->router = $router;
$this->map = $map;
}
public function onPostSerialize(Event $event)
{
$object = $event->getObject();
$config = $this->map[get_class($object)];
$params = array_map(function($path) use ($object) {
$propertyPath = new PropertyPath($path);
return $propertyPath->getValue($object);
}, $config['params']);
$url = $this->router->generate($config['route'], $params);
$event->getVisitor()->addData('url', $url);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment