You are here

class MenuItems in Simplify Menu 8

Same name and namespace in other branches
  1. 8.2 src/MenuItems.php \Drupal\simplify_menu\MenuItems

Class MenuItems.

@package \Drupal\simplify_menu

Hierarchy

Expanded class hierarchy of MenuItems

1 file declares its use of MenuItems
MenuItemsTwigExtension.php in src/TwigExtension/MenuItemsTwigExtension.php
1 string reference to 'MenuItems'
simplify_menu.services.yml in ./simplify_menu.services.yml
simplify_menu.services.yml
1 service uses MenuItems
simplify_menu.menu_items in ./simplify_menu.services.yml
Drupal\simplify_menu\MenuItems

File

src/MenuItems.php, line 13

Namespace

Drupal\simplify_menu
View source
class MenuItems {

  /**
   * MenuLinkTree definition.
   *
   * @var \Drupal\Core\Menu\MenuLinkTree
   */
  protected $menuLinkTree;

  /**
   * MenuItems constructor.
   *
   * @param MenuLinkTree $menu_link_tree
   *   The MenuLinkTree service.
   */
  public function __construct(MenuLinkTree $menu_link_tree) {
    $this->menuLinkTree = $menu_link_tree;
  }

  /**
   * Map menu tree into an array.
   *
   * @param array $links
   *   The array of menu tree links.
   * @param string $submenuKey
   *   The key for the submenu to simplify.
   *
   * @return array
   *   The simplified menu tree array.
   */
  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;
  }

  /**
   * Get header menu links.
   *
   * @params string $menuId
   *   Menu drupal id.
   *
   * @return array
   *   Render array of menu items.
   */
  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),
    ];
  }

}

Members

Namesort descending Modifiers Type Description Overrides
MenuItems::$menuLinkTree protected property MenuLinkTree definition.
MenuItems::getMenuTree public function Get header menu links.
MenuItems::simplifyLinks protected function Map menu tree into an array.
MenuItems::__construct public function MenuItems constructor.