src/EventSubscriber/PasswordUpdateSubscriber.php line 28

  1. <?php
  2. namespace App\EventSubscriber;
  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 PasswordUpdateSubscriber implements EventSubscriberInterface
  9. {
  10.     public function __construct(protected UserPasswordHasherInterface $passwordHasher)
  11.     {
  12.     }
  13.     /**
  14.      * @return array<string, string>
  15.      */
  16.     public static function getSubscribedEvents(): array
  17.     {
  18.         return [
  19.             BeforeEntityPersistedEvent::class => 'onBeforeEntityPersisted',
  20.             BeforeEntityUpdatedEvent::class   => 'onBeforeEntityPersisted',
  21.         ];
  22.     }
  23.     public function onBeforeEntityPersisted(BeforeEntityUpdatedEvent|BeforeEntityPersistedEvent $event): void
  24.     {
  25.         $entity = $event->getEntityInstance();
  26.         if (!$entity instanceof User) {
  27.             return;
  28.         }
  29.         if (!is_null($entity->getPlainPassword()) && '' != $entity->getPlainPassword()) {
  30.             $entity->setPassword(
  31.                 $this->passwordHasher->hashPassword($entity, $entity->getPlainPassword())
  32.             );
  33.         }
  34.     }
  35. }