src/EventSubsriber/UserCrudSubscriber.php line 20

  1. <?php
  2. namespace App\EventSubsriber;
  3. use App\Entity\User;
  4. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  8. class UserCrudSubscriber implements EventSubscriberInterface
  9. {
  10.     protected UserPasswordHasherInterface $passwordHasher;
  11.     public function __construct(UserPasswordHasherInterface $passwordHasher)
  12.     {
  13.         $this->passwordHasher $passwordHasher;
  14.     }
  15.     public function onBeforeEntityPersistedEvent(BeforeEntityPersistedEvent $event): void
  16.     {
  17.         /** @var User $entity */
  18.         $entity $event->getEntityInstance();
  19.         if (!$entity instanceof User) {
  20.             return;
  21.         }
  22.         $this->setPassword($entity);
  23.     }
  24.     public function onBeforeEntityUpdateEvent(BeforeEntityUpdatedEvent $event): void
  25.     {
  26.         /** @var User $entity */
  27.         $entity $event->getEntityInstance();
  28.         if (!$entity instanceof User) {
  29.             return;
  30.         }
  31.         $this->setPassword($entity);
  32.     }
  33.     public static function getSubscribedEvents(): array
  34.     {
  35.         return [
  36.             BeforeEntityPersistedEvent::class => 'onBeforeEntityPersistedEvent',
  37.             BeforeEntityUpdatedEvent::class => 'onBeforeEntityUpdateEvent',
  38.         ];
  39.     }
  40.     public function setPassword(User $entity): void
  41.     {
  42.         if (!empty($entity->getPlainPassword())) {
  43.             $entity->setPassword($this->passwordHasher->hashPassword($entity$entity->getPlainPassword()));
  44.         }
  45.     }
  46. }