带参数和自定义侦听器/订阅者

时间:2017-08-01 15:06:46

标签: symfony doctrine jms-serializer

我正在尝试序列化一个属于Doctrine Criteria的属性:

public function getUserResults(User $user)
{
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq('user', $user))
    ;

    return $this->getResults()->matching($criteria);
}

我不能使用@VirtualProperty,因为它需要一个参数,所以我在这篇帖子之后为我的一个类型实现了一个自定义订阅者:

https://stackoverflow.com/a/44244747

<?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;

class ExerciseSubscriber implements EventSubscriberInterface
{
    private $currentUser;

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

    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();

        $results = $exercise->getUserResults($this->currentUser);
        dump($results); // <-- It is an ArrayCollection with many elements

        $visitor->setData(
            'my_user_results',
            $results // <-- when rendered is an empty {}
        );
    }
}

不幸的是,user_results属性始终为空! 我查看了序列化器的源代码,我发现:

/**
 * Allows you to add additional data to the current object/root element.
 * @deprecated use setData instead
 * @param string $key
 * @param integer|float|boolean|string|array|null $value This value must either be a regular scalar, or an array.
 *                                                       It must not contain any objects anymore.
 */
public function addData($key, $value)
{
    if (isset($this->data[$key])) {
        throw new InvalidArgumentException(sprintf('There is already data for "%s".', $key));
    }

    $this->data[$key] = $value;
}

请注意不得再包含任何对象。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

请尝试使用serializer.post_serialize个活动,而不是serializer.pre_serialize个活动。此外,您的虚拟属性名称(user_results)应与任何现有的可序列化字段不同。

setData方法的第二个参数必须是常规标量或数组。它不能包含任何对象。我建议将JMS序列化程序注入到侦听器类中,以将对象数组序列化为标量数组。

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