Dynamically remove entities inside a JMS serializer event subscriber
Asked Answered
C

1

6

I have a Doctrine entity and I use JMS serializer to render it in my API.

I'd like to add a boolean field like this :

/**
 * @var bool
 *
 * @ORM\Column(name = "is_serialized", type = "boolean")
 */
protected $isSerialized = true;

I also use an EventSubscriber to add some data to my entity before serialization.

I'd like to dynamically include or not each entity, based on the $isSerialized value (I can't modify the Doctrine Query).

class SerializationEventSubscriber extends EventSubscriberInterface
{
    /**
     * @param ObjectEvent $event
     */
    public function onPostSerialize(ObjectEvent $event)
    {
        if (!$this->isGroup('api', $event)) {
            return;
        }

        $entity  = $event->getObject();
        $visitor = $event->getVisitor();

        if (!$object->isSerialized()) {
            // Skip the current object and remove it from serialization
        }
    }
}

I can't find any information about this, neither in the JMS annotation documentation.

Carsoncarstensz answered 6/3, 2017 at 9:23 Comment(0)
H
0

Here is my EventListener, but instead of removing the object I just skip nulled field.

use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\EntityManagerInterface;
use JMS\Serializer\JsonSerializationVisitor;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\Metadata\ClassMetadata as JMSClassMetadata;
use JMS\Serializer\Metadata\StaticPropertyMetadata;

class EntitySerializerListener
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function onPostSerialize(ObjectEvent $event)
    {
        /** @var JsonSerializationVisitor $visitor */
        $object = $event->getObject();
        $visitor = $event->getVisitor();
        $context = $event->getContext();
        $type = $event->getType();

        /** @var JMSClassMetadata $metadata */
        $metadata = $context->getMetadataFactory()->getMetadataForClass($type['name']);

        $data = $visitor->endVisitingObject($metadata, $object, $type);
        $visitor->startVisitingObject($metadata, $object, $type);

        // Here I remove unnecessary fields
        $this->prune($type['name'], $data);
 
        // Reset fresh serialized data
        foreach ($data as $field => $value) {
            $visitor->visitProperty(new StaticPropertyMetadata($type['name'], $field, $value), $value);
        }
    }

    /**
     * Prune the empty field which was set to NULL by MaxDepth annotation but left in the data graph by JWT serializer.
     *
     * @param string $fqcn
     * @param array $data
     */
    protected function prune(string $fqcn, array & $data)
    {
        /** @var ClassMetadata $metadata */
        $metadata = $this->em->getMetadataFactory()->getMetadataFor($fqcn);

        // Handle association
        $associations = $metadata->getAssociationMappings();
        foreach ($associations as $field => $association) {
            if (!array_key_exists($field, $data)) {
                continue;
            }
            
            // Here remove entity or any other field which you want
            if (empty($data[$field])) {
                unset($data[$field]);
            } else {
                $this->prune($association['targetEntity'], $data[$field]);
            }
        }
    }
}
Hepta answered 30/12, 2020 at 13:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.