<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
class AccessSubscriber implements EventSubscriberInterface
{
private Security $security;
private UrlGeneratorInterface $urlGenerator;
private const ACCESS_DENIED_ROUTE = 'app_403_page';
private const RESTRICTED_ROUTE_ARRAY = [
'dh_auditor_list_audits',
'dh_auditor_show_transaction',
'dh_auditor_show_entity_history'
];
public function __construct(Security $security, UrlGeneratorInterface $urlGenerator){
$this->security = $security;
$this->urlGenerator = $urlGenerator;
}
public function onKernelRequest(RequestEvent $event)
{
$routeName = $event->getRequest()->attributes->get('_route');
$user = $this->security->getUser();
// Implement your logic to check user's userType and allowed routes
if ($user && $user->getUserType() !== 777 && in_array($routeName, self::RESTRICTED_ROUTE_ARRAY, true)) {
$event->setResponse(new RedirectResponse($this->urlGenerator->generate(self::ACCESS_DENIED_ROUTE)));
}
}
public static function getSubscribedEvents() : array
{
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
}