<?php
namespace App\EventSubscriber;
use App\Entity\User;
use Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\ResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\Security;
class AccountBanned implements EventSubscriberInterface
{
private $router;
private $security;
public function __construct(RouterInterface $router, Security $security)
{
$this->router = $router;
$this->security = $security;
}
public function onKernelResponse(ResponseEvent $event)
{
/** @var User $user */
$user = $this->security->getUser();
// On vérifie si l'utilisateur est connecté et si son compte est activé
if ($user && $user->getStatus() == "banned") {
$route = 'user_logout';
if ($route === $event->getRequest()->get('_route')
|| 'user_welcome' === $event->getRequest()->get('_route')
|| 'user_login' === $event->getRequest()->get('_route')
) {
return;
}
$url = $this->router->generate($route);
$response = new RedirectResponse($url);
$event->setResponse($response);
}
}
public static function getSubscribedEvents()
{
return [
// On doit définir une priorité élevée
KernelEvents::RESPONSE => [['onKernelResponse', 20]],
];
}
}