<?php
namespace App\EventSubscriber;
use App\Entity\User\AdminUser;
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;
class EasyAdminSubscriber implements EventSubscriberInterface
{
public function __construct(private EntityManagerInterface $entityManager, private UserPasswordEncoderInterface $passwordEncoder)
{
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['addUser'],
BeforeEntityUpdatedEvent::class => ['updateUser'],
];
}
public function updateUser(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof AdminUser)) {
return;
}
$this->setPassword($entity);
}
public function addUser(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if (!($entity instanceof AdminUser)) {
return;
}
$this->setPassword($entity);
}
public function setPassword(AdminUser $entity): void
{
$pass = $entity->getPassword();
$entity->setPassword(
$this->passwordEncoder->encodePassword(
$entity,
$pass
)
);
$this->entityManager->persist($entity);
$this->entityManager->flush();
}
}