View source
<?php
namespace Drupal\simplify_menu;
use Drupal\Core\Menu\MenuLinkTree;
use Drupal\Core\Menu\MenuTreeParameters;
class MenuItems {
protected $menuLinkTree;
public function __construct(MenuLinkTree $menu_link_tree) {
$this->menuLinkTree = $menu_link_tree;
}
protected function simplifyLinks(array $links, $submenuKey = 'submenu') {
$result = [];
foreach ($links as $item) {
$simplifiedLink = [
'text' => $item->link
->getTitle(),
'url' => $item->link
->getUrlObject()
->toString(),
];
if ($item->hasChildren) {
$simplifiedLink[$submenuKey] = $this
->simplifyLinks($item->subtree);
}
$result[] = $simplifiedLink;
}
return $result;
}
public function getMenuTree($menuId = 'main') {
$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),
];
}
}