Symfony 5 - Вернуть текущие данные пользователя в Trait не работает - PullRequest
0 голосов
/ 20 июня 2020

Я создал черту, чтобы добавить два свойства / столбца «user_created» и «user_updated» в каждую сущность (в той же философии, что и черта «Timestamptable», найденная в Интернете)

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface\UserInterface;

trait UserTrack
{
    /**
        * @ORM\ManyToOne(targetEntity=User::class)
    */      
    private $createdUser;
    
    /**
        * @ORM\ManyToOne(targetEntity=User::class)
    */  
    private $updatedUser;
    
    private $security;
    private $me;
    

    public function __construct(Security $security, UserInterface $user)
    {
        $this->security = $security;
        // $this->me = $this->getUser()->getId();  //ERROR
        // $this->me = $this->security->getUser()->getId();  //ERROR
        // $this->me = $user->getId(); //ERROR
    }       
    
    
    
    /**
        * @ORM\PrePersist
    */
    public function setCreatedUserAutomatically()
    {
        if ($this->getCreatedUser() === null) {
            $this->setCreatedUser($this->me);
        }
    }
    
    /**
        * @ORM\PreUpdate
    */
    public function setUpdatedUserAutomatically()
    {
        $this->setUpdatedUser($this->me);
    }
}       

Как вы можете видите, я добавил метод "construct", пытаясь получить мой объект User, но он не работает ..

Не могли бы вы мне помочь?

Спасибо!

1 Ответ

1 голос
/ 21 июня 2020

Благодаря Jakumi и Julien B, следующий код выполняет задание:

EventListener \ EntityListener. php

<?php
namespace App\EventListener;

use Doctrine\ORM\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class EntityListener
{
    private $tokenStorage;
    
    public function __construct(TokenStorageInterface $tokenStorage = null) 
    {
        $this->tokenStorage = $tokenStorage;
    }
    
    public function prePersist(LifecycleEventArgs $args)
    {
        $entity = $args->getEntity();
        if (null !== $currentUser = $this->getUser()) {
            $entity->setCreatedUser($currentUser);
        }
    }       
    
    public function preUpdate(LifecycleEventArgs $args)
    {       
        $entity = $args->getEntity();
        if (null !== $currentUser = $this->getUser()) {
            $entity->setUpdatedUser($currentUser);
        }
    }
    
    public function getUser()
    {
        if (!$this->tokenStorage) {
            throw new \LogicException('The SecurityBundle is not registered in your application.');
        }
        
        if (null === $token = $this->tokenStorage->getToken()) {
            return;
        }
        
        if (!is_object($user = $token->getUser())) {
            // e.g. anonymous authentication
            return;
        }
        
        return $user;
    }
}   

config / services.yaml

my.listener:
    class: App\EventListener\EntityListener
    arguments: ['@security.token_storage']
    tags:
        - { name: doctrine.event_listener, event: prePersist }    
        - { name: doctrine.event_listener, event: preUpdate }

    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...