<?php
namespace BackendApi\Application\EventSubscriber;
use BackendApi\Domain\Security\Account;
use BackendApi\Domain\Security\Role;
use BackendApi\Domain\Security\RoleTypeEnum;
use Doctrine\ORM\EntityManagerInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\PasswordHasher\Hasher\PasswordHasherFactoryInterface;
class EasyAdminListener implements EventSubscriberInterface
{
public function __construct(
private SessionInterface $session,
private EntityManagerInterface $entityManager,
private PasswordHasherFactoryInterface $userPasswordHasher,
)
{
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['beforeEntityPersistedEvent'],
BeforeEntityUpdatedEvent::class => ['beforeEntityUpdatedEvent'],
AfterEntityPersistedEvent::class => ['flashMessageAfterPersist'],
AfterEntityUpdatedEvent::class => ['flashMessageAfterUpdate'],
AfterEntityDeletedEvent::class => ['flashMessageAfterDelete'],
];
}
public function beforeEntityPersistedEvent(BeforeEntityPersistedEvent $event): void
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Account)) {
return;
}
if ($entity->getPassword()) {
$encoder = $this->userPasswordHasher->getPasswordHasher($entity);
$entity->setPassword(
$encoder->hash($entity->getPassword(), $entity->getSalt())
);
}
$this->updateAccount($entity);
}
public function beforeEntityUpdatedEvent(BeforeEntityUpdatedEvent $event): void
{
$entity = $event->getEntityInstance();
if (!($entity instanceof Account)) {
return;
}
$this->updateAccount($entity);
}
private function updateAccount(Account $entity): void
{
//$entity->setUsername($entity->getEmailAddress());
}
public function flashMessageAfterPersist(AfterEntityPersistedEvent $event): void
{
$this->session->getFlashBag()->add('success', sprintf('Entity %s has been created', (string)$event->getEntityInstance()));
}
public function flashMessageAfterUpdate(AfterEntityUpdatedEvent $event): void
{
$this->session->getFlashBag()->add('success', sprintf('Entity %s has been updated', (string)$event->getEntityInstance()));
}
public function flashMessageAfterDelete(AfterEntityDeletedEvent $event): void
{
$this->session->getFlashBag()->add('success', sprintf('Entity %s has been deleted', (string)$event->getEntityInstance()));
}
}