<?php
namespace App\Listener;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Exception;
use Symfony\Component\Console\Event\ConsoleCommandEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
class ConsoleListener
{
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(EntityManagerInterface $em, TokenStorageInterface $tokenStorage)
{
$this->em = $em;
$this->tokenStorage = $tokenStorage;
}
public function onConsoleCommand(ConsoleCommandEvent $event)
{
try {
$user = $this->em->getRepository(User::class)->findUser('[email protected]');
if ($user instanceof User) {
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->tokenStorage->setToken($token);
}
} catch (\Exception $e) {
// When the database doesn't exists or hasn't been populated yet, we get an exception, this is ok.
}
}
}