Spaces:
No application file
No application file
File size: 2,877 Bytes
d2897cd |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
<?php
namespace Mautic\CoreBundle\Menu;
use Knp\Menu\FactoryInterface;
use Knp\Menu\Loader\ArrayLoader;
use Knp\Menu\Matcher\MatcherInterface;
use Mautic\CoreBundle\CoreEvents;
use Mautic\CoreBundle\Event\MenuEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
class MenuBuilder
{
/**
* @var \Symfony\Component\EventDispatcher\ContainerAwareEventDispatcher
*/
private $dispatcher;
public function __construct(
private FactoryInterface $factory,
private MatcherInterface $matcher,
EventDispatcherInterface $dispatcher,
private MenuHelper $menuHelper
) {
$this->dispatcher = $dispatcher;
}
/**
* @return mixed
*/
public function __call($name, $arguments)
{
$name = str_replace('Menu', '', $name);
return $this->buildMenu($name);
}
/**
* Used by breadcrumbs to determine active link.
*
* @param \Knp\Menu\ItemInterface $menu
* @param string $forRouteUri
* @param string $forRouteName
*
* @return \Knp\Menu\ItemInterface|null
*/
public function getCurrentMenuItem($menu, $forRouteUri, $forRouteName)
{
try {
/** @var \Knp\Menu\ItemInterface $item */
foreach ($menu as $item) {
if ('current' == $forRouteUri && $this->matcher->isCurrent($item)) {
// current match
return $item;
} elseif ('current' != $forRouteUri && $item->getUri() == $forRouteUri) {
// route uri match
return $item;
} elseif (!empty($forRouteName) && $forRouteName == $item->getExtra('routeName')) {
// route name match
return $item;
}
if ($item->getChildren() && $current_child = $this->getCurrentMenuItem($item, $forRouteUri, $forRouteName)) {
return $current_child;
}
}
} catch (\Exception) {
// do nothing
}
return null;
}
/**
* @return mixed
*/
private function buildMenu($name)
{
static $menus = [];
if (!isset($menus[$name])) {
$loader = new ArrayLoader($this->factory);
// dispatch the MENU_BUILD event to retrieve bundle menu items
$event = new MenuEvent($this->menuHelper, $name);
$this->dispatcher->dispatch($event, CoreEvents::BUILD_MENU);
$menuItems = $event->getMenuItems();
// KNP Menu explicitly requires a menu name since v3
if (empty($menuItems['name'])) {
$menuItems['name'] = $name;
}
$menus[$name] = $loader->load($menuItems);
}
return $menus[$name];
}
}
|