src/EventSubscriber/UserSubscriber.php line 46
<?php// src/EventSubscriber/EasyAdminSubscriber.phpnamespace App\EventSubscriber;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;use App\Entity\User;use App\Service\MailerService;class UserSubscriber implements EventSubscriberInterface{private $passwordEncoder;private $mailerService;public function __construct(UserPasswordHasherInterface $passwordEncoder, MailerService $mailerService){$this->mailerService = $mailerService;$this->passwordEncoder = $passwordEncoder;}public static function getSubscribedEvents(){return [BeforeEntityPersistedEvent::class => ['hashPasswordOnPersist'],BeforeEntityUpdatedEvent::class => ['hashPasswordOnUpdate'],];}public function hashPasswordOnPersist(BeforeEntityPersistedEvent $event){$entity = $event->getEntityInstance();if (!($entity instanceof User)) {return;}// Enviar correo electrónico de registro$this->mailerService->sendRegistrationEmail($entity->getUserName(), $entity->getPlainPassword(), $entity->getEmail(), $entity->getRoles());$this->encodePassword($entity);}public function hashPasswordOnUpdate(BeforeEntityUpdatedEvent $event){$entity = $event->getEntityInstance();if (!($entity instanceof User)) {return;}// Solo codifica la contraseña si el campo de la contraseña no está vacíoif (!empty($entity->getPlainPassword())) {$this->encodePassword($entity);}}private function encodePassword(User $entity){$plainPassword = $entity->getPlainPassword();// Verifica si getPlainPassword devuelve nullif ($plainPassword === null) {return;}$entity->setPassword($this->passwordEncoder->hashPassword($entity,$plainPassword));// Vacía la contraseña en texto plano para que no se guarde en la sesión$entity->setPlainPassword(null);}}?>