<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Entity\Jurisprudence;
use App\Entity\News;
use App\Entity\Tuto;
use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class AuthorEventSubscriber implements EventSubscriberInterface
{
private TokenStorageInterface $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents(): array
{
return [
BeforeEntityPersistedEvent::class => ['insertAuthor'],
];
}
public function insertAuthor(BeforeEntityPersistedEvent $event): void
{
$entity = $event->getEntityInstance();
if ($entity instanceof Tuto || $entity instanceof News || $entity instanceof Jurisprudence) {
if (null !== $this->tokenStorage->getToken()) {
$entity->setAuthor($this->tokenStorage->getToken()->getUser());
}
}
}
}