<?php
namespace Cofondateur\SocleTechniqueBundle\EventSubscriber;
use Cofondateur\SocleTechniqueBundle\Traits\UpdatableInterface;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Security;
class EasyAdminSubscriber implements EventSubscriberInterface
{
/** @var Security */
private $security;
public function __construct(Security $security)
{
$this->security = $security;
}
public static function getSubscribedEvents()
{
return [
BeforeEntityPersistedEvent::class => ['prePersist'],
BeforeEntityUpdatedEvent::class => ['preUpdate']
];
}
public function prePersist(BeforeEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof UpdatableInterface) {
$entity->setCreatedAt(new \DateTime());
$entity->setCreatedBy($this->security->getUser());
}
}
public function preUpdate(BeforeEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof UpdatableInterface) {
$entity->setUpdatedAt(new \DateTime());
$entity->setUpdatedBy($this->security->getUser());
}
}
}