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