src/EventSubscriber/SwitchUserSubscriber.php line 24
<?phpnamespace App\EventSubscriber;use Symfony\Component\EventDispatcher\EventSubscriberInterface;use Symfony\Component\Routing\RouterInterface;use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;use Symfony\Component\Security\Http\Event\SwitchUserEvent;use Symfony\Component\Security\Http\SecurityEvents;use Symfony\Bundle\SecurityBundle\Security;use Symfony\Component\HttpFoundation\RedirectResponse;use Symfony\Component\Security\Core\Role\RoleHierarchyInterface;class SwitchUserSubscriber implements EventSubscriberInterface{protected $router;protected $roleHierarchy;public function __construct(RouterInterface $router, RoleHierarchyInterface $roleHierarchy) {$this->router = $router;$this->roleHierarchy = $roleHierarchy;}public function onSwitchUser(SwitchUserEvent $event): void{$user = $event->getTargetUser();if ($this->hasRole($user, "ROLE_ADMIN")) :$response = new RedirectResponse($this->router->generate('admin_default'), 302);$response->send();endif;if ($this->hasRole($user, "ROLE_CUSTOMER")) :$response = new RedirectResponse($this->router->generate('customer_default'), 302);$event->getRequest()->getSession()->set('username', 'impersonator');$response->send();endif;if ($this->hasRole($user, "ROLE_WRITER")) :$response = new RedirectResponse($this->router->generate('writer_default'), 302);$event->getRequest()->getSession()->set('username', 'impersonator');$response->send();endif;}private function hasRole(\App\Entity\User $user, string $role): bool{$reachableRoles = $this->roleHierarchy->getReachableRoleNames($user->getRoles());foreach ($reachableRoles as $reachableRole) {if ($reachableRole === $role) {return true;}}return false;}public static function getSubscribedEvents(): array{return [SecurityEvents::SWITCH_USER => 'onSwitchUser',];}}