src/EventSubscriber/UserEventSubscriber.php line 34
<?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
{
public function __construct(private EntityManagerInterface $entityManager, private 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();
}
}