0

I would like to visit recursively each property of the serializing Entity, check if a string is set and verify that the metadata property is properly set to string, otherwise change it in order to allow the serialization.

Imagine a users property which is an ArrayCollection, but I force the value to be a string in corner cases.

I set a SerializationSubscriber to catch the serializer.pre_serialize event, but I'm not finding any doc for take advantage of the Visitor and surroundings.

Any hint?

Bertuz
  • 2,390
  • 3
  • 25
  • 50

1 Answers1

0
class MyEventSubscriber implements JMS\Serializer\EventDispatcher\EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array(
            array('event' => 'serializer.pre_serialize', 'method' => 'onPreSerialize'),
        );
    }

    public function onPreSerialize(JMS\Serializer\EventDispatcher\PreSerializeEvent $event)
    {
        /*
         * @var YourEntity $object
         */
        $object = $event->getObject();
        $reflect = new \ReflectionClass($foo);
        $props = $reflect->getProperties(\ReflectionProperty::IS_PRIVATE);

        foreach ($props as $prop) {
            $method = 'get'.ucfirst($prop->getName());

            // here is call of methods like getId(), getName() etc,
            // depending on name of entity properties
            $object->$method();
        }
    }
}
michail_w
  • 4,318
  • 4
  • 26
  • 43
  • ouch! via reflection? Quite expensive, isn't it? – Bertuz Apr 20 '17 at 09:06
  • Unfortunately is not recursive: what I really would need is visiting each property and change the type if needed. Since there's no event to catch that moment of visiting a node, I should re-visit all the entity's property the way JMSSerialize follows. Quite expensive I'd say – Bertuz Apr 21 '17 at 14:07