Upgraded drupal core with security updates
[yaffs-website] / web / core / modules / taxonomy / src / TermBreadcrumbBuilder.php
1 <?php
2
3 namespace Drupal\taxonomy;
4
5 use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
6 use Drupal\Core\Breadcrumb\Breadcrumb;
7 use Drupal\Core\Entity\EntityManagerInterface;
8 use Drupal\Core\Link;
9 use Drupal\Core\Routing\RouteMatchInterface;
10 use Drupal\Core\StringTranslation\StringTranslationTrait;
11
12 /**
13  * Provides a custom taxonomy breadcrumb builder that uses the term hierarchy.
14  */
15 class TermBreadcrumbBuilder implements BreadcrumbBuilderInterface {
16   use StringTranslationTrait;
17
18   /**
19    * The entity manager.
20    *
21    * @var \Drupal\Core\Entity\EntityManagerInterface
22    */
23   protected $entityManager;
24
25   /**
26    * The taxonomy storage.
27    *
28    * @var \Drupal\Taxonomy\TermStorageInterface
29    */
30   protected $termStorage;
31
32   /**
33    * Constructs the TermBreadcrumbBuilder.
34    *
35    * @param \Drupal\Core\Entity\EntityManagerInterface $entityManager
36    *   The entity manager.
37    */
38   public function __construct(EntityManagerInterface $entityManager) {
39     $this->entityManager = $entityManager;
40     $this->termStorage = $entityManager->getStorage('taxonomy_term');
41   }
42
43   /**
44    * {@inheritdoc}
45    */
46   public function applies(RouteMatchInterface $route_match) {
47     return $route_match->getRouteName() == 'entity.taxonomy_term.canonical'
48       && $route_match->getParameter('taxonomy_term') instanceof TermInterface;
49   }
50
51   /**
52    * {@inheritdoc}
53    */
54   public function build(RouteMatchInterface $route_match) {
55     $breadcrumb = new Breadcrumb();
56     $breadcrumb->addLink(Link::createFromRoute($this->t('Home'), '<front>'));
57     $term = $route_match->getParameter('taxonomy_term');
58     // Breadcrumb needs to have terms cacheable metadata as a cacheable
59     // dependency even though it is not shown in the breadcrumb because e.g. its
60     // parent might have changed.
61     $breadcrumb->addCacheableDependency($term);
62     // @todo This overrides any other possible breadcrumb and is a pure
63     //   hard-coded presumption. Make this behavior configurable per
64     //   vocabulary or term.
65     $parents = $this->termStorage->loadAllParents($term->id());
66     // Remove current term being accessed.
67     array_shift($parents);
68     foreach (array_reverse($parents) as $term) {
69       $term = $this->entityManager->getTranslationFromContext($term);
70       $breadcrumb->addCacheableDependency($term);
71       $breadcrumb->addLink(Link::createFromRoute($term->getName(), 'entity.taxonomy_term.canonical', ['taxonomy_term' => $term->id()]));
72     }
73
74     // This breadcrumb builder is based on a route parameter, and hence it
75     // depends on the 'route' cache context.
76     $breadcrumb->addCacheContexts(['route']);
77
78     return $breadcrumb;
79   }
80
81 }