src/EventSubsriber/UserCrudSubscriber.php line 32
<?php
namespace App\EventSubsriber;
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 UserCrudSubscriber implements EventSubscriberInterface
{
protected UserPasswordHasherInterface $passwordHasher;
public function __construct(UserPasswordHasherInterface $passwordHasher)
{
$this->passwordHasher = $passwordHasher;
}
public function onBeforeEntityPersistedEvent(BeforeEntityPersistedEvent $event): void
{
/** @var User $entity */
$entity = $event->getEntityInstance();
if (!$entity instanceof User) {
return;
}
$this->setPassword($entity);
}
public function onBeforeEntityUpdateEvent(BeforeEntityUpdatedEvent $event): void
{
/** @var User $entity */
$entity = $event->getEntityInstance();
if (!$entity instanceof User) {
return;
}
$this->setPassword($entity);
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => 'onBeforeEntityPersistedEvent',
BeforeEntityUpdatedEvent::class => 'onBeforeEntityUpdateEvent',
];
}
public function setPassword(User $entity): void
{
if (!empty($entity->getPlainPassword())) {
$entity->setPassword($this->passwordHasher->hashPassword($entity, $entity->getPlainPassword()));
}
}
}