<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Security;
/**
* Access Controller Listener
*/
class AccessListener
{
/** @var RouterInterface $router */
protected $router;
/** @var Security $security */
protected $security;
public function __construct(RouterInterface $router, Security $security)
{
$this->router = $router;
$this->security = $security;
}
public function onAccessController(ControllerEvent $event)
{
$request = $event->getRequest();
// https://symfony.com/doc/current/routing.html#getting-the-route-name-and-parameters
$routeName = $request->attributes->get('_route');
$routeCollec = $this->router->getRouteCollection();
$activeRoute = $routeCollec->get($routeName ?? '');
if ($activeRoute) {
$roles = $activeRoute->getRequirements();
if (isset($roles['role'])) {
if (false === $this->security->isGranted($roles['role'])) {
throw new AccessDeniedException();
}
}
}
}
}