2015-08-17 17:00:26 -07:00
< ? php
namespace Drupal\taxonomy ;
use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface ;
2015-09-04 13:20:09 -07:00
use Drupal\Core\Breadcrumb\Breadcrumb ;
2015-08-17 17:00:26 -07:00
use Drupal\Core\Entity\EntityManagerInterface ;
use Drupal\Core\Link ;
use Drupal\Core\Routing\RouteMatchInterface ;
use Drupal\Core\StringTranslation\StringTranslationTrait ;
/**
* Provides a custom taxonomy breadcrumb builder that uses the term hierarchy .
*/
class TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {
use StringTranslationTrait ;
/**
* The entity manager .
*
* @ var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager ;
/**
* The taxonomy storage .
*
2015-09-04 13:20:09 -07:00
* @ var \Drupal\Taxonomy\TermStorageInterface
2015-08-17 17:00:26 -07:00
*/
protected $termStorage ;
/**
* Constructs the TermBreadcrumbBuilder .
*
* @ param \Drupal\Core\Entity\EntityManagerInterface $entityManager
* The entity manager .
*/
public function __construct ( EntityManagerInterface $entityManager ) {
$this -> entityManager = $entityManager ;
$this -> termStorage = $entityManager -> getStorage ( 'taxonomy_term' );
}
/**
* { @ inheritdoc }
*/
public function applies ( RouteMatchInterface $route_match ) {
return $route_match -> getRouteName () == 'entity.taxonomy_term.canonical'
&& $route_match -> getParameter ( 'taxonomy_term' ) instanceof TermInterface ;
}
/**
* { @ inheritdoc }
*/
public function build ( RouteMatchInterface $route_match ) {
2015-09-04 13:20:09 -07:00
$breadcrumb = new Breadcrumb ();
$breadcrumb -> addLink ( Link :: createFromRoute ( $this -> t ( 'Home' ), '<front>' ));
2015-08-17 17:00:26 -07:00
$term = $route_match -> getParameter ( 'taxonomy_term' );
2015-09-04 13:20:09 -07:00
// Breadcrumb needs to have terms cacheable metadata as a cacheable
// dependency even though it is not shown in the breadcrumb because e.g. its
// parent might have changed.
$breadcrumb -> addCacheableDependency ( $term );
2015-08-17 17:00:26 -07:00
// @todo This overrides any other possible breadcrumb and is a pure
// hard-coded presumption. Make this behavior configurable per
// vocabulary or term.
2015-09-04 13:20:09 -07:00
$parents = $this -> termStorage -> loadAllParents ( $term -> id ());
// Remove current term being accessed.
array_shift ( $parents );
foreach ( array_reverse ( $parents ) as $term ) {
2015-08-17 17:00:26 -07:00
$term = $this -> entityManager -> getTranslationFromContext ( $term );
2015-09-04 13:20:09 -07:00
$breadcrumb -> addCacheableDependency ( $term );
$breadcrumb -> addLink ( Link :: createFromRoute ( $term -> getName (), 'entity.taxonomy_term.canonical' , array ( 'taxonomy_term' => $term -> id ())));
2015-08-17 17:00:26 -07:00
}
2015-09-04 13:20:09 -07:00
// This breadcrumb builder is based on a route parameter, and hence it
// depends on the 'route' cache context.
2015-10-08 11:40:12 -07:00
$breadcrumb -> addCacheContexts ([ 'route' ]);
2015-08-17 17:00:26 -07:00
return $breadcrumb ;
}
}