src/EventSubscriber/AuthorEventSubscriber.php line 30

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventSubscriber;
  4. use App\Entity\Jurisprudence;
  5. use App\Entity\News;
  6. use App\Entity\Tuto;
  7. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
  10. class AuthorEventSubscriber implements EventSubscriberInterface
  11. {
  12.     private TokenStorageInterface $tokenStorage;
  13.     public function __construct(TokenStorageInterface $tokenStorage)
  14.     {
  15.         $this->tokenStorage $tokenStorage;
  16.     }
  17.     public static function getSubscribedEvents(): array
  18.     {
  19.         return [
  20.             BeforeEntityPersistedEvent::class => ['insertAuthor'],
  21.         ];
  22.     }
  23.     public function insertAuthor(BeforeEntityPersistedEvent $event): void
  24.     {
  25.         $entity $event->getEntityInstance();
  26.         
  27.         if ($entity instanceof Tuto || $entity instanceof News || $entity instanceof Jurisprudence) {
  28.             if (null !== $this->tokenStorage->getToken()) {
  29.                 $entity->setAuthor($this->tokenStorage->getToken()->getUser());
  30.             }
  31.         }
  32.     }
  33. }