1<?php
2
3namespace Drupal\Core\Breadcrumb;
4
5use Drupal\Core\Cache\RefinableCacheableDependencyInterface;
6use Drupal\Core\Cache\RefinableCacheableDependencyTrait;
7use Drupal\Core\Link;
8use Drupal\Core\Render\RenderableInterface;
9
10/**
11 * Used to return generated breadcrumbs with associated cacheability metadata.
12 */
13class Breadcrumb implements RenderableInterface, RefinableCacheableDependencyInterface {
14
15  use RefinableCacheableDependencyTrait;
16
17  /**
18   * An ordered list of links for the breadcrumb.
19   *
20   * @var \Drupal\Core\Link[]
21   */
22  protected $links = [];
23
24  /**
25   * Gets the breadcrumb links.
26   *
27   * @return \Drupal\Core\Link[]
28   */
29  public function getLinks() {
30    return $this->links;
31  }
32
33  /**
34   * Sets the breadcrumb links.
35   *
36   * @param \Drupal\Core\Link[] $links
37   *   The breadcrumb links.
38   *
39   * @return $this
40   *
41   * @throws \LogicException
42   *   Thrown when setting breadcrumb links after they've already been set.
43   */
44  public function setLinks(array $links) {
45    if (!empty($this->links)) {
46      throw new \LogicException('Once breadcrumb links are set, only additional breadcrumb links can be added.');
47    }
48
49    $this->links = $links;
50
51    return $this;
52  }
53
54  /**
55   * Appends a link to the end of the ordered list of breadcrumb links.
56   *
57   * @param \Drupal\Core\Link $link
58   *   The link appended to the breadcrumb.
59   *
60   * @return $this
61   */
62  public function addLink(Link $link) {
63    $this->links[] = $link;
64
65    return $this;
66  }
67
68  /**
69   * {@inheritdoc}
70   */
71  public function toRenderable() {
72    $build = [
73      '#cache' => [
74        'contexts' => $this->cacheContexts,
75        'tags' => $this->cacheTags,
76        'max-age' => $this->cacheMaxAge,
77      ],
78    ];
79    if (!empty($this->links)) {
80      $build += [
81        '#theme' => 'breadcrumb',
82        '#links' => $this->links,
83      ];
84    }
85    return $build;
86  }
87
88}
89