You are here

public function CheeseburgerMenuService::buildMenuFromVocabulary in Cheeseburger Menu 5.0.x

Returns cheeseburger menu from taxonomy vocabulary.

Parameters

array $vocabulary_menu_settings: The menu settings.

bool $parent_menu_as_link: Whether parent menu item should be links or not.

Return value

\Drupal\cheeseburger_menu\CheeseburgerMenu Built cheeseburger menu.

File

src/CheeseburgerMenuService.php, line 346

Class

CheeseburgerMenuService
Base service providing functions.

Namespace

Drupal\cheeseburger_menu

Code

public function buildMenuFromVocabulary(array $vocabulary_menu_settings, $parent_menu_as_link = FALSE) {

  /** @var \Drupal\taxonomy\TermStorage $term_storage */
  $term_storage = $this->entityTypeManager
    ->getStorage('taxonomy_term');

  /** @var \Drupal\taxonomy\Entity\Vocabulary $vocabulary */
  $vocabulary = $this->entityTypeManager
    ->getStorage('taxonomy_vocabulary')
    ->load($vocabulary_menu_settings['id']);

  // @todo Optimize this.
  $route_parameters = $this->currentRouteMatch
    ->getParameters();
  $active_trail = [];
  if ($route_parameters
    ->has('taxonomy_term')) {
    $current_taxonomy_term = $route_parameters
      ->get('taxonomy_term');
    $current_taxonomy_term_id = FALSE;
    if (is_numeric($current_taxonomy_term)) {
      $current_taxonomy_term_id = $current_taxonomy_term;
    }
    elseif ($current_taxonomy_term instanceof Term) {
      $current_taxonomy_term_id = $current_taxonomy_term
        ->id();
    }
    if ($current_taxonomy_term_id) {
      $parents = $term_storage
        ->loadAllParents($current_taxonomy_term_id);
      $active_trail = array_combine(array_keys($parents), array_keys($parents));
    }
  }

  // @todo Test load tree without max depth vs get children.
  $top_tree_taxonomy_terms = $term_storage
    ->loadTree($vocabulary_menu_settings['id'], 0, 1, TRUE);
  $cheeseburger_menu = CheeseburgerMenu::createFromSettings($vocabulary_menu_settings, $vocabulary);
  $max_depth = $vocabulary_menu_settings['settings']['max_depth'];
  $menu_item_settings = [
    'parent_as_link' => $parent_menu_as_link,
    'active_trail' => $active_trail,
    'expanded' => $vocabulary_menu_settings['settings']['default_expanded'],
  ];
  $langcode = $this->languageManager
    ->getCurrentLanguage(LanguageInterface::TYPE_CONTENT)
    ->getId();
  foreach ($top_tree_taxonomy_terms as $taxonomy_term) {
    if ($taxonomy_term
      ->access('view')) {
      if ($vocabulary_menu_settings['settings']['show_links_in_navigation']) {
        $cheeseburger_menu
          ->addNavigationMenuItem(CheeseburgerMenuItem::createFromTaxonomyVocabulary($taxonomy_term, $menu_item_settings, $max_depth, 1, $langcode));
      }
      else {
        $cheeseburger_menu
          ->addMenuItem(CheeseburgerMenuItem::createFromTaxonomyVocabulary($taxonomy_term, $menu_item_settings, $max_depth, 1, $langcode));
      }
    }
  }
  return $cheeseburger_menu;
}