You are here

function commerce_demo_menu_links_discovered_alter in Commerce Demo 8

Implements hook_menu_links_discovered_alter().

Workaround for taxonomy_menu not supporting custom paths. See #2865894.

File

./commerce_demo.module, line 32
Provides a demo store for Commerce.

Code

function commerce_demo_menu_links_discovered_alter(&$links) {
  $alias_cleaner = \Drupal::service('pathauto.alias_cleaner');
  $facet_storage = \Drupal::entityTypeManager()
    ->getStorage('facets_facet');
  $term_storage = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term');
  try {
    $view_url = Url::fromRoute('view.product_catalog.page_1');
    $view_url = $view_url
      ->getInternalPath();
  } catch (RouteNotFoundException $e) {

    // The catalog View may have been disabled or deleted.
    return;
  }
  foreach ($links as &$link) {
    $menu_name = isset($link['menu_name']) ? $link['menu_name'] : '';
    if ($link['provider'] == 'taxonomy_menu' && $menu_name == 'catalog') {

      // Generate the path to the view + facets.
      // Assumes that the facet is named the same as the vocabulary.
      $term = $term_storage
        ->load($link['metadata']['taxonomy_term_id']);
      $facet = $facet_storage
        ->load($term
        ->bundle());
      if (!$facet instanceof FacetInterface) {
        continue;
      }

      // It is possible for the facet to be NULL if it was deleted, in which
      // case we only link to the view (which is better than nothing).
      $link['url'] = 'internal:/' . $view_url;
      if ($facet) {
        $label = $alias_cleaner
          ->cleanString($term
          ->label());
        $link['url'] .= '/' . $facet
          ->getUrlAlias() . '/' . $label . '-' . $term
          ->id();
      }
      $link['route_name'] = '';
      $link['route_parameters'] = [];
      $link['load arguments'] = [];
    }
  }
}