3 namespace Drupal\Core\Breadcrumb;
5 use Drupal\Core\Extension\ModuleHandlerInterface;
6 use Drupal\Core\Routing\RouteMatchInterface;
9 * Provides a breadcrumb manager.
11 * Can be assigned any number of BreadcrumbBuilderInterface objects by calling
12 * the addBuilder() method. When build() is called it iterates over the objects
13 * in priority order and uses the first one that returns TRUE from
14 * BreadcrumbBuilderInterface::applies() to build the breadcrumbs.
16 * @see \Drupal\Core\DependencyInjection\Compiler\RegisterBreadcrumbBuilderPass
18 class BreadcrumbManager implements ChainBreadcrumbBuilderInterface {
21 * The module handler to invoke the alter hook.
23 * @var \Drupal\Core\Extension\ModuleHandlerInterface
25 protected $moduleHandler;
28 * Holds arrays of breadcrumb builders, keyed by priority.
32 protected $builders = [];
35 * Holds the array of breadcrumb builders sorted by priority.
37 * Set to NULL if the array needs to be re-calculated.
39 * @var \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface[]|null
41 protected $sortedBuilders;
44 * Constructs a \Drupal\Core\Breadcrumb\BreadcrumbManager object.
46 * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
49 public function __construct(ModuleHandlerInterface $module_handler) {
50 $this->moduleHandler = $module_handler;
56 public function addBuilder(BreadcrumbBuilderInterface $builder, $priority) {
57 $this->builders[$priority][] = $builder;
58 // Force the builders to be re-sorted.
59 $this->sortedBuilders = NULL;
65 public function applies(RouteMatchInterface $route_match) {
72 public function build(RouteMatchInterface $route_match) {
73 $breadcrumb = new Breadcrumb();
74 $context = ['builder' => NULL];
75 // Call the build method of registered breadcrumb builders,
76 // until one of them returns an array.
77 foreach ($this->getSortedBuilders() as $builder) {
78 if (!$builder->applies($route_match)) {
79 // The builder does not apply, so we continue with the other builders.
83 $breadcrumb = $builder->build($route_match);
85 if ($breadcrumb instanceof Breadcrumb) {
86 $context['builder'] = $builder;
90 throw new \UnexpectedValueException('Invalid breadcrumb returned by ' . get_class($builder) . '::build().');
93 // Allow modules to alter the breadcrumb.
94 $this->moduleHandler->alter('system_breadcrumb', $breadcrumb, $route_match, $context);
100 * Returns the sorted array of breadcrumb builders.
102 * @return \Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface[]
103 * An array of breadcrumb builder objects.
105 protected function getSortedBuilders() {
106 if (!isset($this->sortedBuilders)) {
107 // Sort the builders according to priority.
108 krsort($this->builders);
109 // Merge nested builders from $this->builders into $this->sortedBuilders.
110 $this->sortedBuilders = [];
111 foreach ($this->builders as $builders) {
112 $this->sortedBuilders = array_merge($this->sortedBuilders, $builders);
115 return $this->sortedBuilders;