. */ declare(strict_types=1); namespace App\EventSubscriber; use App\Entity\UserSystem\User; use App\Events\SecurityEvent; use App\Events\SecurityEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Security\Core\Authentication\Token\SwitchUserToken; use Symfony\Component\Security\Http\Event\SwitchUserEvent; use Symfony\Contracts\EventDispatcher\EventDispatcherInterface; class SwitchUserEventSubscriber implements EventSubscriberInterface { public function __construct(private readonly EventDispatcherInterface $eventDispatcher) { } public static function getSubscribedEvents() { return [ 'security.switch_user' => 'onSwitchUser', ]; } public function onSwitchUser(SwitchUserEvent $event): void { $target_user = $event->getTargetUser(); // We can only handle User objects if (!$target_user instanceof User) { return; } //We are only interested in impersonation (not unimpersonation) if (!$event->getToken() instanceof SwitchUserToken) { return; } $security_event = new SecurityEvent($target_user); $this->eventDispatcher->dispatch($security_event, SecurityEvents::USER_IMPERSONATED); } }