<?php
namespace App\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\User\UserInterface;
use Twig\Environment;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class ModuleSubscriber implements EventSubscriberInterface
{
private Environment $twig;
private TokenStorageInterface $tokenStorage;
public function __construct(
Environment $twig,
TokenStorageInterface $tokenStorage
) {
$this->twig = $twig;
$this->tokenStorage = $tokenStorage;
}
public function onKernelController(ControllerEvent $event)
{
$token = $this->tokenStorage->getToken();
if ($token === null) {
return false;
}
$user = $token->getUser();
$moduleActive = false;
if ($user instanceof UserInterface) {
$controller = $event->getController();
if (is_array($controller)) {
if (isset($controller[0]->module)) {
$moduleActive = $controller[0]->module;
}
}
}
$this->twig->addGlobal('module_active', $moduleActive);
}
public static function getSubscribedEvents(): array
{
return array(
KernelEvents::CONTROLLER => 'onKernelController',
);
}
}