动态删除JMS序列化程序事件订阅者中的实体

时间:2017-03-06 09:23:45

标签: symfony doctrine-orm jmsserializerbundle

我有一个Doctrine实体,我使用JMS序列化器在我的API中呈现它。

我想添加一个像这样的布尔字段:

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

我还使用EventSubscriber在序列化之前向我的实体添加一些数据。

我希望根据$isSerialized值动态包含或不包含每个实体(我无法修改Doctrine查询)。

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
        }
    }
}

我无法在JMS注释文档中找到有关此内容的任何信息。

1 个答案:

答案 0 :(得分:0)

这是我的 EventListener,但我没有删除对象,而是跳过了空字段。

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]);
            }
        }
    }
}