src/Listener/MenuListener.php line 20

Open in your IDE?
  1. <?php
  2. namespace App\Listener;
  3. use App\System\MenuItem;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  6. use Symfony\Component\Security\Core\Security;
  7. use Twig\Environment;
  8. class MenuListener
  9. {
  10.     public function __construct(
  11.         private Environment $twig,
  12.         private Security $security,
  13.         private UrlGeneratorInterface $url
  14.     ) {
  15.     }
  16.     public function __invoke(RequestEvent $event)
  17.     {
  18.         if (!$event->isMainRequest()) {
  19.             return;
  20.         }
  21.         $request $event->getRequest();
  22.         $name $request->attributes->get('_route');
  23.         // $path = $request->getPathInfo();
  24.         $menu = [MenuItem::make('Home'$this->url->generate('home'), 'home' === $name)];
  25.         if ($this->security->isGranted('ROLE_ADMIN')) {
  26.             $admin MenuItem::make('Admin Menu''''admin' === $name);
  27.             $admin->addChild(MenuItem::make('Admin''admin''admin' === $name));
  28.             $menu[] = $admin;
  29.         }
  30.         $this->twig->addGlobal('navMenus'$menu);
  31.     }
  32. }