src/EventSubscriber/UserSubscriber.php line 32

  1. <?php
  2. // src/EventSubscriber/EasyAdminSubscriber.php
  3. namespace App\EventSubscriber;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  7. use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
  8. use App\Entity\User;
  9. use App\Service\MailerService;
  10. class UserSubscriber implements EventSubscriberInterface
  11. {
  12.     private $passwordEncoder;
  13.     private $mailerService;
  14.     public function __construct(UserPasswordHasherInterface $passwordEncoderMailerService $mailerService)
  15.     {
  16.         $this->mailerService $mailerService;
  17.         $this->passwordEncoder $passwordEncoder;
  18.     }
  19.     public static function getSubscribedEvents()
  20.     {
  21.         return [
  22.             BeforeEntityPersistedEvent::class => ['hashPasswordOnPersist'],
  23.             BeforeEntityUpdatedEvent::class => ['hashPasswordOnUpdate'],
  24.         ];
  25.     }
  26.     public function hashPasswordOnPersist(BeforeEntityPersistedEvent $event)
  27.     {
  28.         $entity $event->getEntityInstance();
  29.         if (!($entity instanceof User)) {
  30.             return;
  31.         }
  32.         // Enviar correo electrónico de registro
  33.         $this->mailerService->sendRegistrationEmail($entity->getUserName(), $entity->getPlainPassword(), $entity->getEmail(), $entity->getRoles());
  34.         
  35.         $this->encodePassword($entity);
  36.     }
  37.     public function hashPasswordOnUpdate(BeforeEntityUpdatedEvent $event)
  38.     {
  39.         $entity $event->getEntityInstance();
  40.         if (!($entity instanceof User)) {
  41.             return;
  42.         }
  43.         // Solo codifica la contraseña si el campo de la contraseña no está vacío
  44.         if (!empty($entity->getPlainPassword())) {
  45.             $this->encodePassword($entity);
  46.         }
  47.     }
  48.     private function encodePassword(User $entity)
  49.     {
  50.         $plainPassword $entity->getPlainPassword();
  51.         // Verifica si getPlainPassword devuelve null
  52.         if ($plainPassword === null) {
  53.             return;
  54.         }
  55.         $entity->setPassword(
  56.             $this->passwordEncoder->hashPassword(
  57.                 $entity,
  58.                 $plainPassword
  59.             )
  60.         );
  61.         // Vacía la contraseña en texto plano para que no se guarde en la sesión
  62.         $entity->setPlainPassword(null);
  63.     }
  64. }
  65. ?>