<?php
# src/EventSubscriber/EasyAdminSubscriber.php
namespace App\EventSubscriber;
use App\Controller\Admin\ProductCrudController;
use App\Entity\Product;
use App\Entity\Traits\UpdatableInterface;
use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class EasyAdminSubscriber implements EventSubscriberInterface
{
/** @var AdminUrlGenerator */
private $adminUrlGenerator;
/** @var Security */
private $security;
public function __construct(AdminUrlGenerator $adminUrlGenerator, Security $security)
{
$this->adminUrlGenerator = $adminUrlGenerator;
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [
BeforeCrudActionEvent::class => ['redirectDetail'],
BeforeEntityPersistedEvent::class => ['prePersist'],
BeforeEntityUpdatedEvent::class => ['preUpdate']
];
}
public function redirectDetail(BeforeCrudActionEvent $event)
{
$entity = $event->getAdminContext()->getEntity()->getInstance();
if ($event->getAdminContext()->getCrud()->getCurrentAction() == "detail") {
$entityName = $event->getAdminContext()->getEntity()->getFqcn();
$entityName = explode("\\", $entityName);
$entityName = $entityName[2];
$url = $this->adminUrlGenerator
->setController(("App\Controller\Admin\\" . $entityName . "CrudController"))
->setAction(Action::EDIT)
->setEntityId($entity->getId())
->generateUrl();
$event->setResponse(new RedirectResponse($url));
}
}
public function prePersist(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof UpdatableInterface) {
$entity->setCreatedAt(new \DateTime());
$entity->setCreator($this->security->getUser());
}
}
public function preUpdate(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof UpdatableInterface) {
$entity->setUpdatedAt(new \DateTime());
$entity->setUpdator($this->security->getUser());
}
}
}