<?php
declare(strict_types=1);
namespace App\EventsSubscriber\EasyAdmin;
use App\Entity\Manager;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class EasyAdminSubscriber implements EventSubscriberInterface
{
private ?string $password = null;
public function __construct(
private EntityManagerInterface $entityManager,
) {
}
public static function getSubscribedEvents()
{
return [
BeforeCrudActionEvent::class => ['getManagerPassword'],
AfterEntityUpdatedEvent::class => ['setManagerPassword'],
];
}
public function getManagerPassword(BeforeCrudActionEvent $event): void
{
$entity = $event->getAdminContext()->getEntity();
if (!$entity->getInstance() instanceof Manager) {
return;
}
$this->password = $entity->getInstance()->getPassword();
}
public function setManagerPassword(AfterEntityUpdatedEvent $event): void
{
$entity = $event->getEntityInstance();
if (!$entity instanceof Manager) {
return;
}
if ($entity->getPassword() === '' && $this->password !== null) {
$entity->setPassword($this->password);
$this->entityManager->flush();
}
}
}