You are here

protected function MenuItems::simplifyLinks in Simplify Menu 8.2

Same name and namespace in other branches
  1. 8 src/MenuItems.php \Drupal\simplify_menu\MenuItems::simplifyLinks()

Map menu tree into an array.

Parameters

array $links: The array of menu tree links.

string $submenuKey: The key for the submenu to simplify.

Return value

array The simplified menu tree array.

1 call to MenuItems::simplifyLinks()
MenuItems::getMenuTree in src/MenuItems.php
Get header menu links.

File

src/MenuItems.php, line 53

Class

MenuItems
Class MenuItems.

Namespace

Drupal\simplify_menu

Code

protected function simplifyLinks(array $links, string $submenuKey = 'submenu') : array {
  $result = [];
  foreach ($links as $item) {

    // Per DefaultMenuLinkTreeManipulators::checkAccess(), which we run in
    // getMenuTree, "inaccessible links are *not* removed; it's up to the code
    // doing something with the tree to exclude inaccessible links, just like
    // MenuLinkTree::build() does" - whose code we replicate here.

    /** @var \Drupal\Core\Menu\MenuLinkInterface $link */
    $link = $item->link;

    // Generally we only deal with visible links, but just in case.
    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.');
    }

    // Only render accessible links.
    if ($item->access instanceof AccessResultInterface && !$item->access
      ->isAllowed()) {
      continue;
    }

    // Build the link item.
    $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;
    }

    /* @var string $plugin_id */
    $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;
}