src/EventSubscriber/EasyAdminSubscriber.php line 43

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\User;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. //use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  9. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  10. class EasyAdminSubscriber implements EventSubscriberInterface
  11. {
  12.     private $entityManager;
  13.     private $passwordEncoder;
  14.     public function __construct(EntityManagerInterface $entityManagerUserPasswordHasherInterface $passwordEncoder)
  15.     {
  16.         $this->entityManager $entityManager;
  17.         $this->passwordEncoder $passwordEncoder;
  18.     }
  19.     public static function getSubscribedEvents()
  20.     {
  21.         return [
  22.             BeforeEntityPersistedEvent::class => ['addUser'],
  23.            // 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é ...
  24.         ];
  25.     }
  26. /*    public function updateUser(BeforeEntityUpdatedEvent $event)
  27.     {
  28.         $entity = $event->getEntityInstance();
  29.         if (!($entity instanceof User)) {
  30.             return;
  31.         }
  32.         $this->setPassword($entity);
  33.     }*/
  34.     public function addUser(BeforeEntityPersistedEvent $event)
  35.     {
  36.         $entity $event->getEntityInstance();
  37.         if (!($entity instanceof User)) {
  38.             return;
  39.         }
  40.         $this->setPassword($entity);
  41.     }
  42.     /**
  43.      * @param User $entity
  44.      */
  45.     public function setPassword(User $entity): void
  46.     {
  47.         $pass $entity->getPassword();
  48.         $entity->setPassword(
  49.             $this->passwordEncoder->hashPassword(
  50.                 $entity,
  51.                 $pass
  52.             )
  53.         );
  54.         $this->entityManager->persist($entity);
  55.         $this->entityManager->flush();
  56.     }
  57. }