Breadcrumb.php 1.8 KB

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