src/EventSubscriber/EasyAdminSubscriber.php line 32

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3.  
  4. use App\Entity\User
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  10. class EasyAdminSubscriber implements EventSubscriberInterface
  11. {
  12.     private $entityManager;
  13.     private $passwordEncoder;
  14.     public function __construct(EntityManagerInterface $entityManagerUserPasswordEncoderInterface $passwordEncoder)
  15.     {
  16.         $this->entityManager $entityManager;
  17.         $this->passwordEncoder $passwordEncoder;
  18.     }
  19.     public static function getSubscribedEvents()
  20.     {
  21.         return [
  22.             BeforeEntityPersistedEvent::class => ['addUtilisateur'],
  23.             BeforeEntityUpdatedEvent::class => ['updateUtilisateur'],
  24.         ];
  25.     }
  26.     public function updateUtilisateur(BeforeEntityUpdatedEvent $event)
  27.     {
  28.         $entity $event->getEntityInstance(); 
  29.         if (!($entity instanceof User)   ) { 
  30.             return;
  31.         } 
  32.         $this->setPassword($entity); 
  33.     }
  34.     public function addUtilisateur(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($entity): void
  46.     {
  47.         $pass       $entity->getPassword();
  48.         if($pass!=""){ 
  49.             $newpasword $this->passwordEncoder->encodePassword($entity,$pass ); 
  50.             $entity->setPassword($newpasword);
  51.             $this->entityManager->persist($entity);
  52.             $this->entityManager->flush();
  53.         }
  54.     }
  55. }