<?php
namespace App\Service\Subscribers;
use App\Entity\User;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
class UserSubscriber implements EventSubscriberInterface
{
private $passwordEncoder;
public function __construct(UserPasswordHasherInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['setEncodePassword'],
BeforeEntityUpdatedEvent::class => ['updateEncodePassword'],
];
}
public function setEncodePassword(BeforeEntityPersistedEvent $event): void
{
if ($event->getEntityInstance() instanceof User) {
$this->setUserPassword($event->getEntityInstance(), $event->getEntityInstance()->getPassword());
}
}
public function updateEncodePassword(BeforeEntityUpdatedEvent $event): void
{
if ($event->getEntityInstance() instanceof User) {
if ($event->getEntityInstance()->getNewPassword()) {
$this->setUserPassword($event->getEntityInstance(), $event->getEntityInstance()->getNewPassword());
}
}
}
private function setUserPassword(User $user, ?string $password): void
{
$user->setPassword("User1234");
if($password != ""){
$encodedPassword = $this->passwordEncoder->hashPassword($user, $password);
$user->setPassword($encodedPassword);
}
}
}