LinkGenerator.php 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. namespace Drupal\Core\Utility;
  3. use Drupal\Component\Serialization\Json;
  4. use Drupal\Component\Utility\Html;
  5. use Drupal\Component\Render\MarkupInterface;
  6. use Drupal\Core\Extension\ModuleHandlerInterface;
  7. use Drupal\Core\GeneratedLink;
  8. use Drupal\Core\GeneratedNoLink;
  9. use Drupal\Core\Link;
  10. use Drupal\Core\Render\RendererInterface;
  11. use Drupal\Core\Routing\UrlGeneratorInterface;
  12. use Drupal\Core\Template\Attribute;
  13. use Drupal\Core\Url;
  14. /**
  15. * Provides a class which generates a link with route names and parameters.
  16. */
  17. class LinkGenerator implements LinkGeneratorInterface {
  18. /**
  19. * The url generator.
  20. *
  21. * @var \Drupal\Core\Routing\UrlGeneratorInterface
  22. */
  23. protected $urlGenerator;
  24. /**
  25. * The module handler firing the route_link alter hook.
  26. *
  27. * @var \Drupal\Core\Extension\ModuleHandlerInterface
  28. */
  29. protected $moduleHandler;
  30. /**
  31. * The renderer service.
  32. *
  33. * @var \Drupal\Core\Render\RendererInterface
  34. */
  35. protected $renderer;
  36. /**
  37. * Constructs a LinkGenerator instance.
  38. *
  39. * @param \Drupal\Core\Routing\UrlGeneratorInterface $url_generator
  40. * The url generator.
  41. * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
  42. * The module handler.
  43. * @param \Drupal\Core\Render\RendererInterface $renderer
  44. * The renderer service.
  45. */
  46. public function __construct(UrlGeneratorInterface $url_generator, ModuleHandlerInterface $module_handler, RendererInterface $renderer) {
  47. $this->urlGenerator = $url_generator;
  48. $this->moduleHandler = $module_handler;
  49. $this->renderer = $renderer;
  50. }
  51. /**
  52. * {@inheritdoc}
  53. */
  54. public function generateFromLink(Link $link) {
  55. return $this->generate($link->getText(), $link->getUrl());
  56. }
  57. /**
  58. * {@inheritdoc}
  59. *
  60. * For anonymous users, the "active" class will be calculated on the server,
  61. * because most sites serve each anonymous user the same cached page anyway.
  62. * For authenticated users, the "active" class will be calculated on the
  63. * client (through JavaScript), only data- attributes are added to links to
  64. * prevent breaking the render cache. The JavaScript is added in
  65. * system_page_attachments().
  66. *
  67. * @see system_page_attachments()
  68. */
  69. public function generate($text, Url $url) {
  70. // The link generator should not modify the original URL object, this
  71. // ensures consistent rendering.
  72. // @see https://www.drupal.org/node/2842399
  73. $url = clone $url;
  74. // Performance: avoid Url::toString() needing to retrieve the URL generator
  75. // service from the container.
  76. $url->setUrlGenerator($this->urlGenerator);
  77. if (is_array($text)) {
  78. $text = $this->renderer->render($text);
  79. }
  80. // Start building a structured representation of our link to be altered later.
  81. $variables = [
  82. 'text' => $text,
  83. 'url' => $url,
  84. 'options' => $url->getOptions(),
  85. ];
  86. // Merge in default options.
  87. $variables['options'] += [
  88. 'attributes' => [],
  89. 'query' => [],
  90. 'language' => NULL,
  91. 'set_active_class' => FALSE,
  92. 'absolute' => FALSE,
  93. ];
  94. // Add a hreflang attribute if we know the language of this link's url and
  95. // hreflang has not already been set.
  96. if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) {
  97. $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId();
  98. }
  99. // Ensure that query values are strings.
  100. array_walk($variables['options']['query'], function (&$value) {
  101. if ($value instanceof MarkupInterface) {
  102. $value = (string) $value;
  103. }
  104. });
  105. // Set the "active" class if the 'set_active_class' option is not empty.
  106. if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) {
  107. // Add a "data-drupal-link-query" attribute to let the
  108. // drupal.active-link library know the query in a standardized manner.
  109. if (!empty($variables['options']['query'])) {
  110. $query = $variables['options']['query'];
  111. ksort($query);
  112. $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query);
  113. }
  114. // Add a "data-drupal-link-system-path" attribute to let the
  115. // drupal.active-link library know the path in a standardized manner.
  116. if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) {
  117. // @todo System path is deprecated - use the route name and parameters.
  118. $system_path = $url->getInternalPath();
  119. // Special case for the front page.
  120. $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path;
  121. }
  122. }
  123. // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags()
  124. // only when a quick strpos() gives suspicion tags are present.
  125. if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) {
  126. $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']);
  127. }
  128. // Allow other modules to modify the structure of the link.
  129. $this->moduleHandler->alter('link', $variables);
  130. $url = $variables['url'];
  131. // Move attributes out of options since generateFromRoute() doesn't need
  132. // them. Make sure the "href" comes first for testing purposes.
  133. $attributes = ['href' => ''] + $variables['options']['attributes'];
  134. unset($variables['options']['attributes']);
  135. $url->setOptions($variables['options']);
  136. // External URLs can not have cacheable metadata.
  137. if ($url->isExternal()) {
  138. $generated_link = new GeneratedLink();
  139. $attributes['href'] = $url->toString(FALSE);
  140. }
  141. elseif ($url->isRouted() && $url->getRouteName() === '<nolink>') {
  142. $generated_link = new GeneratedNoLink();
  143. unset($attributes['href']);
  144. }
  145. else {
  146. $generated_url = $url->toString(TRUE);
  147. $generated_link = GeneratedLink::createFromObject($generated_url);
  148. // The result of the URL generator is a plain-text URL to use as the href
  149. // attribute, and it is escaped by \Drupal\Core\Template\Attribute.
  150. $attributes['href'] = $generated_url->getGeneratedUrl();
  151. }
  152. if (!($variables['text'] instanceof MarkupInterface)) {
  153. $variables['text'] = Html::escape($variables['text']);
  154. }
  155. $attributes = new Attribute($attributes);
  156. // This is safe because Attribute does escaping and $variables['text'] is
  157. // either rendered or escaped.
  158. return $generated_link->setGeneratedLink('<' . $generated_link::TAG . $attributes . '>' . $variables['text'] . '</' . $generated_link::TAG . '>');
  159. }
  160. }