JMS VirtualProperty with argument and custom listener/subscriber

懵懂的女人 提交于 2019-12-02 03:10:31

Please try to use serializer.post_serialize event instead of serializer.pre_serialize one. Also your virtual property name (user_results) should be different from any existing serializable fields.

The second argument of setData method must either be a regular scalar, or an array. It must not contain any objects. I suggest to inject JMS serializer into your listener class to serialize your objects array into array of scalars.

<?php

namespace AppBundle\Serializer;

use JMS\Serializer\EventDispatcher\EventSubscriberInterface;
use JMS\Serializer\EventDispatcher\PreSerializeEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use JMS\Serializer\EventDispatcher\ObjectEvent;
use JMS\Serializer\Serializer;

class ExerciseSubscriber implements EventSubscriberInterface
{
    private $currentUser;
    private $serializer;

    public function __construct(TokenStorage $tokenStorage, Serializer $serializer)
    {
        $this->currentUser = $tokenStorage->getToken()->getUser();
        $this->serializer  = $serializer;
    }

    public static function getSubscribedEvents()
    {
        return array(
            array(
                'event'  => 'serializer.post_serialize',
                'method' => 'onPostSerialize',
                'class'  => Exercise::class, // if no class, subscribe to every serialization
                'format' => 'json', // optional format
            ),
        );
    }

    public function onPostSerialize(ObjectEvent $event)
    {
        if (!$this->currentUser) {
            return;
        }

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

        $visitor->setData(
            'user_results',
            $this->serializer->toArray($exercise->getUserResults($this->currentUser))
        );
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!