You are here

public function HierarchyBasedBreadcrumbBuilder::build in Entity Reference Hierarchy 3.x

Same name and namespace in other branches
  1. 8.2 modules/entity_hierarchy_breadcrumb/src/HierarchyBasedBreadcrumbBuilder.php \Drupal\entity_hierarchy_breadcrumb\HierarchyBasedBreadcrumbBuilder::build()

Builds the breadcrumb.

Parameters

\Drupal\Core\Routing\RouteMatchInterface $route_match: The current route match.

Return value

\Drupal\Core\Breadcrumb\Breadcrumb A breadcrumb.

Overrides BreadcrumbBuilderInterface::build

File

modules/entity_hierarchy_breadcrumb/src/HierarchyBasedBreadcrumbBuilder.php, line 104

Class

HierarchyBasedBreadcrumbBuilder
Entity hierarchy based breadcrumb builder.

Namespace

Drupal\entity_hierarchy_breadcrumb

Code

public function build(RouteMatchInterface $route_match) {
  $breadcrumb = new Breadcrumb();
  $breadcrumb
    ->addCacheContexts([
    'route',
  ]);

  /** @var \Drupal\Core\Entity\ContentEntityInterface $route_entity */
  $route_entity = $this
    ->getEntityFromRouteMatch($route_match);
  $entity_type = $route_entity
    ->getEntityTypeId();
  $storage = $this->storageFactory
    ->get($this
    ->getHierarchyFieldFromEntity($route_entity), $entity_type);
  $ancestors = $storage
    ->findAncestors($this->nodeKeyFactory
    ->fromEntity($route_entity));

  // Pass in the breadcrumb object for caching.
  $ancestor_entities = $this->mapper
    ->loadAndAccessCheckEntitysForTreeNodes($entity_type, $ancestors, $breadcrumb);
  $links = [];
  foreach ($ancestor_entities as $ancestor_entity) {
    if (!$ancestor_entities
      ->contains($ancestor_entity)) {

      // Doesn't exist or is access hidden.
      continue;
    }
    $entity = $ancestor_entities
      ->offsetGet($ancestor_entity);

    // Show just the label for the entity from the route.
    if ($entity
      ->id() == $route_entity
      ->id()) {
      $links[] = Link::createFromRoute($entity
        ->label(), '<none>');
    }
    else {
      $links[] = $entity
        ->toLink();
    }
  }
  array_unshift($links, Link::createFromRoute(new TranslatableMarkup('Home'), '<front>'));
  $breadcrumb
    ->setLinks($links);
  return $breadcrumb;
}