src/Listener/ConsoleListener.php line 29

Open in your IDE?
  1. <?php
  2. namespace App\Listener;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Exception;
  6. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  7. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
  9. class ConsoleListener
  10. {
  11.     /**
  12.      * @var EntityManagerInterface
  13.      */
  14.     private $em;
  15.     /**
  16.      * @var TokenStorageInterface
  17.      */
  18.     private $tokenStorage;
  19.     public function __construct(EntityManagerInterface $emTokenStorageInterface $tokenStorage)
  20.     {
  21.         $this->em $em;
  22.         $this->tokenStorage $tokenStorage;
  23.     }
  24.     public function onConsoleCommand(ConsoleCommandEvent $event)
  25.     {
  26.         try {
  27.             $user $this->em->getRepository(User::class)->findUser('[email protected]');
  28.             if ($user instanceof User) {
  29.                 $token = new UsernamePasswordToken($usernull'main'$user->getRoles());
  30.                 $this->tokenStorage->setToken($token);
  31.             }
  32.         } catch (\Exception $e) {
  33.             // When the database doesn't exists or hasn't been populated yet, we get an exception, this is ok.
  34.         }
  35.     }
  36. }