src/EventSubscriber/EasyAdminSubscriberUserPasswordChange.php line 31

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. class EasyAdminSubscriberUserPasswordChange implements EventSubscriberInterface
  10. {
  11.     private $entityManager;
  12.     private $passwordHasher;
  13.       public function __construct(EntityManagerInterface $entityManagerUserPasswordHasherInterface $passwordHasher)
  14.       {
  15.           $this->entityManager $entityManager;
  16.           $this->passwordHasher $passwordHasher;
  17.       }
  18.       public static function getSubscribedEvents()
  19.       {
  20.           return [
  21.             //   BeforeEntityPersistedEvent::class => ['addUser'],
  22.               BeforeEntityUpdatedEvent::class => ['updateUser'], //surtout utile lors d'un reset de mot passe plutôt qu'un réel update, car l'update va de nouveau encrypter le mot de passe DEJA encrypté ...
  23.           ];
  24.       }
  25.       public function updateUser(BeforeEntityUpdatedEvent $event)
  26.       {
  27.           $entity $event->getEntityInstance();
  28.           if (!($entity instanceof User)) {
  29.               return;
  30.           }
  31.           $this->setPassword($entity);
  32.       }
  33.     //   public function addUser(BeforeEntityPersistedEvent $event)
  34.     //   {
  35.     //       $entity = $event->getEntityInstance();
  36.     //       if (!($entity instanceof User)) {
  37.     //           return;
  38.     //       }
  39.     //       $this->setPassword($entity);
  40.     //   }
  41.       /**
  42.        * @param User $entity
  43.        */
  44.       public function setPassword(User $entity): void
  45.       {
  46.           $pass $entity->getPassword();
  47.           $entity->setPassword(
  48.               $this->passwordHasher->hashPassword(
  49.                   $entity,
  50.                   $pass
  51.               )
  52.           );
  53.           $this->entityManager->persist($entity);
  54.           $this->entityManager->flush();
  55.       }
  56. }