src/EventSubscriber/UserAfterCreate.php line 35

Open in your IDE?
  1. <?php
  2. # src/EventSubscriber/EasyAdminSubscriber.php
  3. namespace App\EventSubscriber;
  4. use App\Entity\User;
  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. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  10. class UserAfterCreate implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var UserPasswordEncoderInterface
  14.      */
  15.     private $passwordEncoder;
  16.     /**
  17.      * EasyAdminSubscriber constructor.
  18.      *
  19.      * @param UserPasswordEncoderInterface $passwordEncoder
  20.      */
  21.     public function __construct(UserPasswordHasherInterface $passwordEncoder) {
  22.         $this->passwordEncoder $passwordEncoder;
  23.     }
  24.     public static function getSubscribedEvents()
  25.     {
  26.         return [
  27.             BeforeEntityPersistedEvent::class => ['preUpdateEntity'],
  28.         ];
  29.     }
  30.     public function preUpdateEntity(BeforeEntityPersistedEvent $event)
  31.     {
  32.         $entity $event->getEntityInstance();
  33.         if (!($entity instanceof User)) {
  34.             return;
  35.         }
  36.         $plain_password $entity->getPlainPassword();
  37.         if(!empty($plain_password)) {
  38.             $new_password $this->passwordEncoder->hashPassword($entity$plain_password);
  39.             $entity->setPassword($new_password);
  40.             $entity->eraseCredentials(null);
  41.         }
  42.     }
  43. }