<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
//use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserEventSubscriber implements EventSubscriberInterface
{
private EntityManagerInterface $entityManager;
// private UserPasswordEncoderInterface $passwordEncoder;
private UserPasswordHasherInterface $UserPasswordHasherInterface;
public function __construct(EntityManagerInterface $entityManager, UserPasswordHasherInterface $userPasswordHasherInterface)
{
$this->entityManager = $entityManager;
$this->userPasswordHasherInterface = $userPasswordHasherInterface;
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['persistUser'],
BeforeEntityUpdatedEvent::class => ['updateUser'],
];
}
public function persistUser(BeforeEntityPersistedEvent $event): void
{
$user = $event->getEntityInstance();
if (!$user instanceof User) {
return;
}
$plainPassword = $user->getPlainPassword();
if ('' !== $plainPassword) {
$this->encodePassword($user);
} }
public function updateUser(BeforeEntityUpdatedEvent $event): void
{
$user = $event->getEntityInstance();
if (!$user instanceof User) {
return;
}
$plainPassword = $user->getPlainPassword();
if ('' !== $plainPassword) {
$this->encodePassword($user);
}
}
private function encodePassword(User $user)
{
$plainPassword = $user->getPlainPassword();
$user->setPassword(
$this->userPasswordHasherInterface->hashPassword(
$user,
$plainPassword
)
);
$this->entityManager->persist($user);
$this->entityManager->flush();
}
}