View source
<?php
declare (strict_types=1);
namespace Drupal\simplify_menu;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\Access\AccessResultInterface;
class MenuItems {
protected $menuLinkTree;
protected $activeMenuTree;
public function __construct(MenuLinkTreeInterface $menu_link_tree) {
$this->menuLinkTree = $menu_link_tree;
}
protected function simplifyLinks(array $links, string $submenuKey = 'submenu') : array {
$result = [];
foreach ($links as $item) {
$link = $item->link;
if (!$link
->isEnabled()) {
continue;
}
if ($item->access !== NULL && !$item->access instanceof AccessResultInterface) {
throw new \DomainException('MenuLinkTreeElement::access must be either NULL or an AccessResultInterface object.');
}
if ($item->access instanceof AccessResultInterface && !$item->access
->isAllowed()) {
continue;
}
$simplifiedLink = [
'text' => $item->link
->getTitle(),
'url' => $item->link
->getUrlObject()
->toString(),
'active_trail' => FALSE,
'active' => FALSE,
];
$current_path = \Drupal::request()
->getRequestUri();
if ($current_path == $simplifiedLink['url']) {
$simplifiedLink['active'] = TRUE;
}
$plugin_id = $item->link
->getPluginId();
if (isset($this->activeMenuTree[$plugin_id]) && $this->activeMenuTree[$plugin_id] == TRUE) {
$simplifiedLink['active_trail'] = TRUE;
}
if ($item->hasChildren) {
$simplifiedLink[$submenuKey] = $this
->simplifyLinks($item->subtree);
}
$result[] = $simplifiedLink;
}
return $result;
}
public function getMenuTree(string $menuId = 'main') : array {
$this
->setActiveMenuTree($menuId);
$parameters = new MenuTreeParameters();
$parameters
->onlyEnabledLinks();
$manipulators = [
[
'callable' => 'menu.default_tree_manipulators:checkAccess',
],
[
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
],
];
$headerTreeLoad = $this->menuLinkTree
->load($menuId, $parameters);
$headerTransform = $this->menuLinkTree
->transform($headerTreeLoad, $manipulators);
return [
'menu_tree' => $this
->simplifyLinks($headerTransform),
];
}
public function setActiveMenuTree(string $menu_id) : void {
$menu_tree = \Drupal::menuTree();
$parameters = \Drupal::menuTree()
->getCurrentRouteMenuTreeParameters($menu_id);
$loaded_tree = $menu_tree
->load($menu_id, $parameters);
$this->activeMenuTree = $this
->checkActiveTrail($loaded_tree);
}
protected function checkActiveTrail(array $menuTree) : array {
$active = [];
foreach ($menuTree as $index => $tree) {
if ($tree->inActiveTrail) {
$active[$index] = TRUE;
}
else {
$active[$index] = FALSE;
}
if ($tree->hasChildren) {
$active += $this
->checkActiveTrail($tree->subtree);
}
}
return $active;
}
}