schmittjoh/serializer — pull request #19 by cabello (2013-01-07 18:01:09+00:00)
Title: In case of circular reference fire an event so we can decide what to do.

Hi,

We serialize a lot of Doctrine entities and sometimes they have circular reference by example:

File -> User -> Avatar (File)

On those cases the `isVisiting` method returns `true` on `GraphNavigator` file:

if ($this->context->isVisiting($data)) {
return null;
}

And the attribute avatar might be dropped, that is, it doesn't appear on response or `NULL`, both cases are bad but the second one is a problem because it's lying, the property is set and not null.

Because of that we decided to fire an event when isVisiting find some node that's already visiting, that way a listener/handler can decide what to do with the response object, in our case, our handler breaks the circular reference by exchanging it by the id of the object, something like this:

public function onSerializeVisited(SerializeVisitedEvent $event)
{
$object = $event->getObject();

if ( ! method_exists($object, 'getId')) {
$event->setObject(null);

return;
}

$event->setObject(array('id' => $object->getId()));
}

I am really open to change the event name, the use of $object as the value that is changed when the event happens.

This will fix a bug we are facing daily basis every time our rest service serialize an entity.

Thanks!