src/EventSubscriber/Identity/NewPasswordSubscriber.php line 23

  1. <?php
  2. namespace App\EventSubscriber\Identity;
  3. use App\Entity\Identity\Password;
  4. use App\Event\Identity\NewPasswordEvent;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. final readonly class NewPasswordSubscriber implements EventSubscriberInterface
  8. {
  9.     public function __construct(
  10.         private EntityManagerInterface $entityManager,
  11.     ) {}
  12.     public static function getSubscribedEvents(): array
  13.     {
  14.         return [
  15.             NewPasswordEvent::IDENTIFIER => 'process'
  16.         ];
  17.     }
  18.     public function process(NewPasswordEvent $event): void
  19.     {
  20.         $user $event->getUser();
  21.         // Expire previous password
  22.         $entities $this->entityManager->getRepository(Password::class)->findBy([
  23.             'user' => $user,
  24.             'expired' => false
  25.         ]);
  26.         foreach ($entities as $entity) {
  27.             $entity->setExpired(true);
  28.             $this->entityManager->persist($entity);
  29.         }
  30.         // Log new password
  31.         $entity = new Password();
  32.         $entity->setUser($user);
  33.         $entity->setValue($user->getPassword());
  34.         $this->entityManager->persist($entity);
  35.         $this->entityManager->flush();
  36.     }
  37. }