View source
<?php
namespace Drupal\menu_select;
use Drupal\Component\Render\FormattableMarkup;
use Drupal\Core\Menu\MenuLinkInterface;
use Drupal\Core\Menu\MenuLinkTreeInterface;
use Drupal\Core\Menu\MenuTreeParameters;
class MenuSelectTreeBuilder implements MenuSelectTreeBuilderInterface {
protected $manipulators = [
[
'callable' => 'menu.default_tree_manipulators:checkNodeAccess',
],
[
'callable' => 'menu.default_tree_manipulators:checkAccess',
],
[
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
],
];
protected $menuTree;
public function __construct(MenuLinkTreeInterface $menuTree) {
$this->menuTree = $menuTree;
}
public function loadMenuTree($menu_name, $max_depth) {
$parameters = new MenuTreeParameters();
$parameters
->setMaxDepth($max_depth);
$tree = $this->menuTree
->load($menu_name, $parameters);
return $this->menuTree
->transform($tree, $this->manipulators);
}
public function buildRenderedMenu(array $menu_tree, $menu_id, $menu_label, $current_link_id) {
$menu_key = $this
->getMenuKey($menu_id);
$items[$menu_key] = [
'data' => $this
->generateMenuLink($menu_label, $this
->getMenuKey($menu_id)),
];
if (!empty($menu_tree)) {
$items[$menu_key]['children'] = $this
->buildNestedMenu($menu_tree, $menu_id, $current_link_id);
}
$build = [
'#theme' => 'item_list',
'#list_type' => 'ul',
'#wrapper_attributes' => [
'class' => [
'menu-select-menu-hierarchy',
'js-menu-select-menu-hierarchy',
],
],
'#attributes' => [
'class' => [
'menu-select-menu-level',
'js-menu-select-menu-level',
],
],
'#items' => $items,
];
return $build;
}
protected function buildNestedMenu(array $menu_tree, $menu_id, $current_link_id) {
$nested_menu = [];
foreach ($menu_tree as $data) {
if ($current_link_id === $data->link
->getPluginId()) {
continue;
}
$menu_key = $this
->getMenuKey($menu_id, $data->link);
$nested_menu[$menu_key]['data'] = $this
->generateLink($data->link, $menu_key);
if (!empty($data->subtree)) {
$nested_menu[$menu_key]['children'] = $this
->buildNestedMenu($data->subtree, $menu_id, $current_link_id);
}
}
return $nested_menu;
}
protected function generateLink(MenuLinkInterface $link, $menu_key) {
return [
'#markup' => new FormattableMarkup('<a data-mkey="@mkey" class="menu-select-menu-link js-menu-select-menu-link" href="#menu-select-parent-menu">@title</a>', [
'@title' => $link
->getTitle(),
'@mkey' => $menu_key,
]),
];
}
protected function generateMenuLink($menu_label, $menu_key) {
return [
'#markup' => new FormattableMarkup('<a data-mkey="@mkey" class="menu-select-menu-link js-menu-select-menu-link" href="#menu-select-parent-menu">@title</a>', [
'@title' => sprintf('%s (%s)', $menu_label, t('menu')),
'@mkey' => $menu_key,
]),
];
}
protected function getMenuKey($menu_id, MenuLinkInterface $link = NULL) {
return sprintf('%s:%s', $menu_id, $link ? $link
->getPluginId() : '');
}
}