src/EventSubscriber/BlameableSubscriber.php line 21

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber;
  3. use App\Entity\Question;
  4. use App\Entity\User;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  6. use LogicException;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. class BlameableSubscriber implements EventSubscriberInterface
  10. {
  11.     private Security $security;
  12.     public function __construct(Security $security)
  13.     {
  14.         $this->security $security;
  15.     }
  16.     public function onBeforeEntityUpdatedEvent(BeforeEntityUpdatedEvent $event): void
  17.     {
  18.         $question $event->getEntityInstance();
  19.         if (!$question instanceof Question) {
  20.             return;
  21.         }
  22.         $user $this->security->getUser();
  23.         // We always should have a User object in EA
  24.         if (!$user instanceof User) {
  25.             throw new LogicException('Currently logged in user is not an instance of User?!');
  26.         }
  27.         $question->setUpdatedBy($user);
  28.     }
  29.     public static function getSubscribedEvents(): array
  30.     {
  31.         return [
  32.             BeforeEntityUpdatedEvent::class => 'onBeforeEntityUpdatedEvent',
  33.         ];
  34.     }
  35. }