JMS序列化为实体

时间:2018-02-02 12:41:05

标签: symfony fosrestbundle jmsserializerbundle

我使用jms序列化和restbundle为json respone 我有关系实体

class Questions
{

    /**
 * @var ArrayCollection|Notes[]
 *
 * @ORM\OneToMany(targetEntity="AppBundle\Entity\Notes", mappedBy="questions", cascade={"persist"})
 * @Annotation\Groups({
 *     "get_question", "get_questions"
 * })
 */
private $note;

和我的行动

        $context = SerializationContext::create()->enableMaxDepthChecks();
    if ($groups) {
        $context->setGroups(["get_questions"]);
    }

    if ($withEmptyField) {
        $context->setSerializeNull(true);
    }

    return View::create()
        ->setStatusCode(self::HTTP_STATUS_CODE_OK)
        ->setData($questions)
        ->setSerializationContext($context);

并且一切正常,作为回应,我有noteNotes个对象的密钥

      "note": [
    {
      "author": {
          "id": 17,
          "name": "qq"
      },
      "id": 4,
      "text": "aaawww"
    },

但我想为此添加一些条件,例如我希望作者Notes,例如我想要过滤器用户身份验证。我可以添加SerializesAccessor并添加" getter",但我只能在实体中创建getter功能,如何在实体中获取认证用户...?或者如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决。我使用jms序列化事件。在此事件发生后,我可以通过身份验证用户条件

更改我的回复中的ArrayCollection
class SerializationListener implements EventSubscriberInterface
{
private $tokenStorage;

private $user;

private $notesRepository;

public function __construct(
    TokenStorageInterface $tokenStorage,
    NotesRepository $notesRepository
) {
    $this->tokenStorage = $tokenStorage;
    $this->notesRepository = $notesRepository;
    $this->user = $tokenStorage->getToken()->getUser();
}

/**
 * @inheritdoc
 */
static public function getSubscribedEvents()
{
    return array(
        array(
            'event' => 'serializer.pre_serialize',
            'class' => Questions::class,
            'method' => 'onPreSerialize'
        )
    );
}

public function onPreSerialize(PreSerializeEvent $event)
{
    /** @var Questions $question */
    $question = $event->getObject();
    if ($this->user instanceof User) {
        $authorNotes = $this->notesRepository->findBy(['user' => $this->user, 'questions' => $question]);
        $question->setNoteCollection($authorNotes);
    }
}
}

和配置

    app.listener.serializationlistener:
    class: "%app.serialization_listener.class%"
    arguments:
        - "@security.token_storage"
        - "@app.repository.notes"
    tags:
        - {name: jms_serializer.event_subscriber}

并设置Collection

    /**
 * @param Notes[] $notes
 * @return $this
 */
public function setNoteCollection(array $notes)
{
    $this->getNote()->clear();
    foreach ($notes as $note) {
        $this->addNote($note);
    }

    return $this;
}
相关问题