module-symfony icon indicating copy to clipboard operation
module-symfony copied to clipboard

User from Security service is not available in Doctrine Listeners

Open BastienLedon opened this issue 3 years ago • 10 comments

Hello,

When trying to test a part of our code with an Event Listener like:

<?php
namespace App\EventListener\Doctrine;

use Symfony\Component\Security\Core\Security;

class Listener
{
    private Security $security;
    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    public function prePersist(Entity $entity)
    {
        $user = $this->security->getUser();
        $entity->setUser($user);
    }
}

$user is always null

I found this SO question with the exact same problem: https://stackoverflow.com/questions/57609821/make-security-available-for-doctrine-onflush-within-functional-test

Do you recommend using the workaround given in the SO answers or something else ?

BastienLedon avatar Nov 09 '20 16:11 BastienLedon