<?php
namespace App\Listener;
use App\System\MenuItem;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Security;
use Twig\Environment;
class MenuListener
{
public function __construct(
private Environment $twig,
private Security $security,
private UrlGeneratorInterface $url
) {
}
public function __invoke(RequestEvent $event)
{
if (!$event->isMainRequest()) {
return;
}
$request = $event->getRequest();
$name = $request->attributes->get('_route');
// $path = $request->getPathInfo();
$menu = [MenuItem::make('Home', $this->url->generate('home'), 'home' === $name)];
if ($this->security->isGranted('ROLE_ADMIN')) {
$admin = MenuItem::make('Admin Menu', '', 'admin' === $name);
$admin->addChild(MenuItem::make('Admin', 'admin', 'admin' === $name));
$menu[] = $admin;
}
$this->twig->addGlobal('navMenus', $menu);
}
}