PathBasedBreadcrumbBuilder.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. <?php
  2. namespace Drupal\system;
  3. use Drupal\Component\Utility\Unicode;
  4. use Drupal\Core\Access\AccessManagerInterface;
  5. use Drupal\Core\Breadcrumb\Breadcrumb;
  6. use Drupal\Core\Breadcrumb\BreadcrumbBuilderInterface;
  7. use Drupal\Core\Config\ConfigFactoryInterface;
  8. use Drupal\Core\Controller\TitleResolverInterface;
  9. use Drupal\Core\Link;
  10. use Drupal\Core\ParamConverter\ParamNotConvertedException;
  11. use Drupal\Core\Path\CurrentPathStack;
  12. use Drupal\Core\Path\PathMatcherInterface;
  13. use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
  14. use Drupal\Core\Routing\RequestContext;
  15. use Drupal\Core\Routing\RouteMatch;
  16. use Drupal\Core\Routing\RouteMatchInterface;
  17. use Drupal\Core\Session\AccountInterface;
  18. use Drupal\Core\StringTranslation\StringTranslationTrait;
  19. use Drupal\Core\Url;
  20. use Symfony\Component\HttpFoundation\Request;
  21. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  22. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  23. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  24. use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
  25. /**
  26. * Class to define the menu_link breadcrumb builder.
  27. */
  28. class PathBasedBreadcrumbBuilder implements BreadcrumbBuilderInterface {
  29. use StringTranslationTrait;
  30. /**
  31. * The router request context.
  32. *
  33. * @var \Drupal\Core\Routing\RequestContext
  34. */
  35. protected $context;
  36. /**
  37. * The menu link access service.
  38. *
  39. * @var \Drupal\Core\Access\AccessManagerInterface
  40. */
  41. protected $accessManager;
  42. /**
  43. * The dynamic router service.
  44. *
  45. * @var \Symfony\Component\Routing\Matcher\RequestMatcherInterface
  46. */
  47. protected $router;
  48. /**
  49. * The inbound path processor.
  50. *
  51. * @var \Drupal\Core\PathProcessor\InboundPathProcessorInterface
  52. */
  53. protected $pathProcessor;
  54. /**
  55. * Site config object.
  56. *
  57. * @var \Drupal\Core\Config\Config
  58. */
  59. protected $config;
  60. /**
  61. * The title resolver.
  62. *
  63. * @var \Drupal\Core\Controller\TitleResolverInterface
  64. */
  65. protected $titleResolver;
  66. /**
  67. * The current user object.
  68. *
  69. * @var \Drupal\Core\Session\AccountInterface
  70. */
  71. protected $currentUser;
  72. /**
  73. * The current path service.
  74. *
  75. * @var \Drupal\Core\Path\CurrentPathStack
  76. */
  77. protected $currentPath;
  78. /**
  79. * The patch matcher service.
  80. *
  81. * @var \Drupal\Core\Path\PathMatcherInterface
  82. */
  83. protected $pathMatcher;
  84. /**
  85. * Constructs the PathBasedBreadcrumbBuilder.
  86. *
  87. * @param \Drupal\Core\Routing\RequestContext $context
  88. * The router request context.
  89. * @param \Drupal\Core\Access\AccessManagerInterface $access_manager
  90. * The menu link access service.
  91. * @param \Symfony\Component\Routing\Matcher\RequestMatcherInterface $router
  92. * The dynamic router service.
  93. * @param \Drupal\Core\PathProcessor\InboundPathProcessorInterface $path_processor
  94. * The inbound path processor.
  95. * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
  96. * The config factory service.
  97. * @param \Drupal\Core\Controller\TitleResolverInterface $title_resolver
  98. * The title resolver service.
  99. * @param \Drupal\Core\Session\AccountInterface $current_user
  100. * The current user object.
  101. * @param \Drupal\Core\Path\CurrentPathStack $current_path
  102. * The current path.
  103. * @param \Drupal\Core\Path\PathMatcherInterface $path_matcher
  104. * The path matcher service.
  105. */
  106. public function __construct(RequestContext $context, AccessManagerInterface $access_manager, RequestMatcherInterface $router, InboundPathProcessorInterface $path_processor, ConfigFactoryInterface $config_factory, TitleResolverInterface $title_resolver, AccountInterface $current_user, CurrentPathStack $current_path, PathMatcherInterface $path_matcher = NULL) {
  107. $this->context = $context;
  108. $this->accessManager = $access_manager;
  109. $this->router = $router;
  110. $this->pathProcessor = $path_processor;
  111. $this->config = $config_factory->get('system.site');
  112. $this->titleResolver = $title_resolver;
  113. $this->currentUser = $current_user;
  114. $this->currentPath = $current_path;
  115. $this->pathMatcher = $path_matcher ?: \Drupal::service('path.matcher');
  116. }
  117. /**
  118. * {@inheritdoc}
  119. */
  120. public function applies(RouteMatchInterface $route_match) {
  121. return TRUE;
  122. }
  123. /**
  124. * {@inheritdoc}
  125. */
  126. public function build(RouteMatchInterface $route_match) {
  127. $breadcrumb = new Breadcrumb();
  128. $links = [];
  129. // Add the url.path.parent cache context. This code ignores the last path
  130. // part so the result only depends on the path parents.
  131. $breadcrumb->addCacheContexts(['url.path.parent']);
  132. // Do not display a breadcrumb on the frontpage.
  133. if ($this->pathMatcher->isFrontPage()) {
  134. return $breadcrumb;
  135. }
  136. // General path-based breadcrumbs. Use the actual request path, prior to
  137. // resolving path aliases, so the breadcrumb can be defined by simply
  138. // creating a hierarchy of path aliases.
  139. $path = trim($this->context->getPathInfo(), '/');
  140. $path_elements = explode('/', $path);
  141. $exclude = [];
  142. // Don't show a link to the front-page path.
  143. $front = $this->config->get('page.front');
  144. $exclude[$front] = TRUE;
  145. // /user is just a redirect, so skip it.
  146. // @todo Find a better way to deal with /user.
  147. $exclude['/user'] = TRUE;
  148. while (count($path_elements) > 1) {
  149. array_pop($path_elements);
  150. // Copy the path elements for up-casting.
  151. $route_request = $this->getRequestForPath('/' . implode('/', $path_elements), $exclude);
  152. if ($route_request) {
  153. $route_match = RouteMatch::createFromRequest($route_request);
  154. $access = $this->accessManager->check($route_match, $this->currentUser, NULL, TRUE);
  155. // The set of breadcrumb links depends on the access result, so merge
  156. // the access result's cacheability metadata.
  157. $breadcrumb = $breadcrumb->addCacheableDependency($access);
  158. if ($access->isAllowed()) {
  159. $title = $this->titleResolver->getTitle($route_request, $route_match->getRouteObject());
  160. if (!isset($title)) {
  161. // Fallback to using the raw path component as the title if the
  162. // route is missing a _title or _title_callback attribute.
  163. $title = str_replace(['-', '_'], ' ', Unicode::ucfirst(end($path_elements)));
  164. }
  165. $url = Url::fromRouteMatch($route_match);
  166. $links[] = new Link($title, $url);
  167. }
  168. }
  169. }
  170. // Add the Home link.
  171. $links[] = Link::createFromRoute($this->t('Home'), '<front>');
  172. return $breadcrumb->setLinks(array_reverse($links));
  173. }
  174. /**
  175. * Matches a path in the router.
  176. *
  177. * @param string $path
  178. * The request path with a leading slash.
  179. * @param array $exclude
  180. * An array of paths or system paths to skip.
  181. *
  182. * @return \Symfony\Component\HttpFoundation\Request
  183. * A populated request object or NULL if the path couldn't be matched.
  184. */
  185. protected function getRequestForPath($path, array $exclude) {
  186. if (!empty($exclude[$path])) {
  187. return NULL;
  188. }
  189. // @todo Use the RequestHelper once https://www.drupal.org/node/2090293 is
  190. // fixed.
  191. $request = Request::create($path);
  192. // Performance optimization: set a short accept header to reduce overhead in
  193. // AcceptHeaderMatcher when matching the request.
  194. $request->headers->set('Accept', 'text/html');
  195. // Find the system path by resolving aliases, language prefix, etc.
  196. $processed = $this->pathProcessor->processInbound($path, $request);
  197. if (empty($processed) || !empty($exclude[$processed])) {
  198. // This resolves to the front page, which we already add.
  199. return NULL;
  200. }
  201. $this->currentPath->setPath($processed, $request);
  202. // Attempt to match this path to provide a fully built request.
  203. try {
  204. $request->attributes->add($this->router->matchRequest($request));
  205. return $request;
  206. }
  207. catch (ParamNotConvertedException $e) {
  208. return NULL;
  209. }
  210. catch (ResourceNotFoundException $e) {
  211. return NULL;
  212. }
  213. catch (MethodNotAllowedException $e) {
  214. return NULL;
  215. }
  216. catch (AccessDeniedHttpException $e) {
  217. return NULL;
  218. }
  219. }
  220. }