You are here

public function MenuItemParser::parse in Menu Firstchild 2.x

Same name and namespace in other branches
  1. 8 src/MenuItemParser.php \Drupal\menu_firstchild\MenuItemParser::parse()

Parses a menu item and modifies it if menu_firstchild is enabled.

Parameters

array $item: Menu item array.

string $menu_name: Menu machine name.

Return value

array Menu item array.

File

src/MenuItemParser.php, line 26

Class

MenuItemParser
Class MenuItemParser.

Namespace

Drupal\menu_firstchild

Code

public function parse(array $item, $menu_name) {

  // If menu_firstchild is enabled on the menu item, continue parsing it.
  if ($this
    ->enabled($item)) {
    $tree = $this
      ->childTree($item, $menu_name);

    // Preserve Title.
    $original_attributes = $item['url']
      ->getOption('attributes');
    $original_title = isset($original_attributes['title']) ? $original_attributes['title'] : FALSE;

    // Children found, get url of first one.
    if (count($tree)) {
      $first_child = reset($tree);
      $url = $first_child->link
        ->getUrlObject();
    }
    else {
      $first_child = NULL;
      $url = Url::fromRoute('<none>');
    }

    // Create a new URL so we don't copy attributes etc.
    if ($url
      ->isRouted()) {
      $item['url'] = Url::fromRoute($url
        ->getRouteName(), $url
        ->getRouteParameters());
    }
    else {
      $item['url'] = Url::fromUri($url
        ->getUri());
    }

    // Add a class on the menu item so it can be themed accordingly.
    $item['attributes']
      ->addClass('menu-firstchild');

    // Add title user entered from Menu Link form.
    if ($original_title) {
      $new_attrs = $item['url']
        ->getOption('attributes');
      $new_attrs['title'] = $original_title;
      $item['url']
        ->setOption("attributes", $new_attrs);
    }
    \Drupal::moduleHandler()
      ->alter('menu_firstchild_item', $item, $first_child);
  }

  // Parse all children if any are found.
  if (!empty($item['below'])) {
    foreach ($item['below'] as &$below) {
      $below = $this
        ->parse($below, $menu_name);
    }
  }
  return $item;
}