src/EventListener/VerifiedUserEventListener.php line 29

Open in your IDE?
  1. <?php
  2. // src/EventListener/CheckUserEnabledListener.php
  3. namespace App\EventListener;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\RequestStack;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use Symfony\Component\HttpKernel\Event\RequestEvent;
  8. use Symfony\Component\Routing\RouterInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. class VerifiedUserEventListener
  11. {
  12.     private $security;
  13.     private $router;
  14.     private $session;
  15.     private $requestStack;
  16.     public function __construct(Security $securityRouterInterface $routerSessionInterface $sessionRequestStack $requestStack)
  17.     {
  18.         $this->security $security;
  19.         $this->router $router;
  20.         $this->session $session;
  21.         $this->requestStack $requestStack;
  22.     }
  23.     public function onKernelRequest(RequestEvent $event)
  24.     {
  25.         $request $this->requestStack->getCurrentRequest();
  26.         $currentRoute $request->attributes->get('_route');
  27.         // Skip if the current route is for user activation or any other you wish to exclude
  28.         if (in_array($currentRoute, ['app_user_activation'])) {
  29.             return;
  30.         }
  31.         $user $this->security->getUser();
  32.         // Check if the request has a user and they are not enabled
  33.         if ($user && !$user->isEnabled()) {
  34.             // Add flash message
  35.             $this->session->getFlashBag()->add('warning''Your account is not enabled.');
  36.             // Redirect to the login page or any other page
  37.             $response = new RedirectResponse($this->router->generate('app_user_activation'));
  38.             // Set the response to redirect
  39.             $event->setResponse($response);
  40.         }
  41.     }
  42. }