Resolve "Menu annotation for controller" #1071

Merged
jankstudio merged 13 commits from 222-menu-annotation-for-controller into master 2019-06-08 07:24:18 +00:00
3 changed files with 96 additions and 0 deletions
Showing only changes of commit fa9bbe8989 - Show all commits

View file

@ -0,0 +1,13 @@
<?php
namespace Catalyst\MenuBundle\Annotation;
use Annotation;
/**
* @Annotation
*/
class Menu
{
public $selected;
}

View file

@ -0,0 +1,77 @@
<?php
namespace Catalyst\MenuBundle\Listener;
use Doctrine\Common\Annotations\Reader;
use ReflectionClass;
use ReflectionException;
use RuntimeException;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Catalyst\MenuBundle\Annotation\Menu as MenuAnnotation;
use Twig\Environment as TwigEnvironment;
// TODO: put the generator in our bundle
use App\Menu\Generator as MenuGenerator;
class MenuAnnotationListener
{
protected $annot_reader;
protected $menu_gen;
protected $twig;
protected $menu_name;
public function __construct(Reader $annot_reader, MenuGenerator $menu_gen, TwigEnvironment $twig, $menu_name)
{
$this->annot_reader = $annot_reader;
$this->menu_gen = $menu_gen;
$this->twig = $twig;
$this->menu_name = $menu_name;
}
public function onKernelController(FilterControllerEvent $event)
{
if (!$event->isMasterRequest())
return;
// get controller
$event_controller = $event->getController();
if (!is_array($event_controller))
return;
list($controller, $method_name) = $event_controller;
// get reflection class
try
{
$ref_controller = new ReflectionClass($controller);
}
catch (ReflectionException $e)
{
throw new RuntimeException('Cannot read menu annotation.');
}
// get method annotations
$ref_method = $ref_controller->getMethod($method_name);
$annotation = $this->annot_reader->getMethodAnnotation($ref_method, MenuAnnotation::class);
// check if we get anything
if ($annotation == null)
return;
$this->selectMenu($annotation->selected);
}
protected function selectMenu($selected)
{
// get menu
$menu = $this->menu_gen->getMenu($this->menu_name);
// set menu selected
$sel = $menu['index']->get($selected);
if ($sel != null)
$sel->setSelected();
// create twig global variable
$this->twig->addGlobal($this->menu_name, $menu);
}
}

View file

@ -118,4 +118,10 @@ services:
$cache_dir: "%kernel.cache_dir%"
$config_dir: "%kernel.root_dir%/../config"
$acl_file: "%api_acl_file%"
Catalyst\MenuBundle\Listener\MenuAnnotationListener:
arguments:
$menu_name: "main_menu"
tags:
- { name: kernel.event_listener, event: kernel.controller, method: onKernelController }