RequestListener.php 1.61 KB
<?php

namespace App\EventListener;

use App\Utils\CotisationUtils;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class RequestListener
{
    private $em;
    private $tokenStorage;
    private $router;
    private $cotisationUtils;

    public function __construct(EntityManagerInterface $em, TokenStorageInterface $tokenStorage, RouterInterface $router, CotisationUtils $cotisationUtils)
    {
        $this->em = $em;
        $this->tokenStorage = $tokenStorage;
        $this->router = $router;
        $this->cotisationUtils = $cotisationUtils;
    }

    public function onKernelRequest(RequestEvent $event)
    {
        if (!$event->isMasterRequest()) {
            // don't do anything if it's not the master request
            return;
        }

        $user = $this->tokenStorage->getToken()->getUser();
        $route = $event->getRequest()->attributes->get('_route');
        if (null != $user &&
            (
                ($user->isGranted('ROLE_ADHERENT') &&
                null != $user->getAdherent()) ||
                ($user->isGranted('ROLE_PRESTATAIRE') &&
                null != $this->session->get('_prestagere'))
            ) &&
            false === $this->cotisationUtils->isCotisationValid($user) &&
            'cotisation_invalid' != $route
        ) {
            $event->setResponse(new RedirectResponse($this->router->generate('cotisation_invalid')));
        }
    }
}