Skip to content

Instantly share code, notes, and snippets.

@aliemre
Created June 2, 2020 22:19
Show Gist options
  • Save aliemre/afd1c859391206dcaf98b4c2a159ed85 to your computer and use it in GitHub Desktop.
Save aliemre/afd1c859391206dcaf98b4c2a159ed85 to your computer and use it in GitHub Desktop.
Symfony 5: Redirect the current user to another route on HTTP Response Event
<?php
namespace App\EventListener;
use App\Entity\User;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Security;
final class OnboardingListener
{
private $security;
private $router;
public function __construct(Security $security, RouterInterface $router)
{
$this->security = $security;
$this->router = $router;
}
public function __invoke(ResponseEvent $event): void
{
$user = $this->security->getUser();
if ($user instanceof User) {
if (! $user->getOnboarding()) {
$routeName = $event->getRequest()->attributes->get('_route');
$allowedRouteNames = [
'app_route_1',
'app_route_2',
];
if (!in_array($routeName, $allowedRouteNames)) {
$response = new RedirectResponse($this->router->generate('app_default_onboardingStepOne'));
$event->setResponse($response);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment