src/EventSubscriber/EasyAdminSubscriber.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 EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  9. class EasyAdminSubscriber implements EventSubscriberInterface
  10. {
  11.     private EntityManagerInterface $entityManager;
  12.     private UserPasswordHasherInterface $passwordEncoder;
  13.     public function __construct(EntityManagerInterface $entityManagerUserPasswordHasherInterface $passwordEncoder)
  14.     {
  15.         $this->entityManager $entityManager;
  16.         $this->passwordEncoder $passwordEncoder;
  17.     }
  18.     public static function getSubscribedEvents(): array
  19.     {
  20.         return [
  21.             BeforeEntityPersistedEvent::class => ['addUser'],
  22.             BeforeEntityUpdatedEvent::class => ['updateUser'],
  23.         ];
  24.     }
  25.     public function updateUser(BeforeEntityUpdatedEvent $event)
  26.     {
  27.         $entity $event->getEntityInstance();
  28.         if (!($entity instanceof User)) {
  29.             return;
  30.         }
  31.         if (empty($entity->getPlainPassword())) {
  32.             return;
  33.         }
  34.         $this->setPassword($entity);
  35.     }
  36.     public function addUser(BeforeEntityPersistedEvent $event)
  37.     {
  38.         $entity $event->getEntityInstance();
  39.         if (!($entity instanceof User)) {
  40.             return;
  41.         }
  42.         $this->setPassword($entity);
  43.     }
  44.     public function setPassword(User $entity): void
  45.     {
  46.         $pass $entity->getPlainPassword();
  47.         $entity->setPassword(
  48.             $this->passwordEncoder->hashPassword(
  49.                 $entity,
  50.                 $pass
  51.             )
  52.         );
  53.         $this->entityManager->persist($entity);
  54.         $this->entityManager->flush();
  55.     }
  56. }