You are here

public function TaxonomyBreadcrumb::build in Taxonomy Breadcrumb 8

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

src/TaxonomyBreadcrumb.php, line 106

Class

TaxonomyBreadcrumb

Namespace

Drupal\taxonomy_breadcrumb

Code

public function build(RouteMatchInterface $route_match) {
  $breadcrumb = new Breadcrumb();
  $node_object = $route_match
    ->getParameters()
    ->get('node');
  $node_is_fieldable = $node_object instanceof FieldableEntityInterface;

  // Generate the HOME breadcrumb.
  if ($this->config
    ->get('taxonomy_breadcrumb_home')) {
    $home = $this->config
      ->get('taxonomy_breadcrumb_home');
    $breadcrumb
      ->addLink(Link::createFromRoute($home, '<front>'));
  }

  // Generate the VOCABULARY breadcrumb.
  if ($node_is_fieldable) {

    // Check all taxonomy terms applying to the current page.
    foreach ($node_object
      ->getFields() as $field) {
      if ($field
        ->getSetting('target_type') == 'taxonomy_term') {
        $vocabulary_bundles = $field
          ->getSettings()['handler_settings']['target_bundles'];

        // For now doing for nodes with single vocabulary as reference.
        $vocabulary_machine_name = reset($vocabulary_bundles);
        $entity_type = 'taxonomy_vocabulary';
        $vocabulary_label = $vocabulary_bundles[$vocabulary_machine_name];
        $vocabulary_entity = \Drupal::entityTypeManager()
          ->getStorage($entity_type)
          ->load($vocabulary_machine_name);
        $taxonomy_breadcrumb_path = isset($vocabulary_entity
          ->getThirdPartySettings("taxonomy_breadcrumb", "taxonomy_breadcrumb_path")['taxonomy_breadcrumb_path']) ? $vocabulary_entity
          ->getThirdPartySettings("taxonomy_breadcrumb", "taxonomy_breadcrumb_path")['taxonomy_breadcrumb_path'] : '';
        if ($taxonomy_breadcrumb_path) {
          $breadcrumb
            ->addLink(Link::fromTextAndUrl($vocabulary_label, Url::fromUri('base:/' . $taxonomy_breadcrumb_path)));
        }

        // Generate the TERM breadcrumb.
        foreach ($field
          ->referencedEntities() as $term) {
          if ($term
            ->get('taxonomy_breadcrumb_path')
            ->getValue()) {
            $breadcrumb
              ->addLink(Link::fromTextAndUrl($term
              ->get('taxonomy_breadcrumb_path')
              ->getValue()[0]['title'], Url::fromUri($term
              ->get('taxonomy_breadcrumb_path')
              ->getValue()[0]['uri'])));
          }
          else {
            $breadcrumb
              ->addLink(Link::createFromRoute($term
              ->getName(), 'entity.taxonomy_term.canonical', [
              'taxonomy_term' => $term
                ->id(),
            ]));
          }
        }
      }
    }
  }
  return $breadcrumb;
}