LinkGenerationTest.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. namespace Drupal\KernelTests\Core\Url;
  3. use Drupal\Component\Render\MarkupInterface;
  4. use Drupal\Core\Render\RenderContext;
  5. use Drupal\Core\Url;
  6. use Drupal\KernelTests\KernelTestBase;
  7. /**
  8. * Tests link generation with hooks.
  9. *
  10. * @group Utility
  11. */
  12. class LinkGenerationTest extends KernelTestBase {
  13. public static $modules = ['link_generation_test'];
  14. /**
  15. * Tests how hook_link_alter() can affect escaping of the link text.
  16. */
  17. public function testHookLinkAlter() {
  18. $url = Url::fromUri('http://example.com');
  19. $renderer = \Drupal::service('renderer');
  20. $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
  21. return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
  22. });
  23. $this->setRawContent($link);
  24. $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
  25. // Ensure the content of the link is not escaped.
  26. $this->assertRaw('<em>link with markup</em>');
  27. // Test just adding text to an already safe string.
  28. \Drupal::state()->set('link_generation_test_link_alter', TRUE);
  29. $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
  30. return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
  31. });
  32. $this->setRawContent($link);
  33. $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
  34. // Ensure the content of the link is escaped.
  35. $this->assertEscaped('<em>link with markup</em> <strong>Test!</strong>');
  36. // Test passing a safe string to t().
  37. \Drupal::state()->set('link_generation_test_link_alter_safe', TRUE);
  38. $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
  39. return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
  40. });
  41. $this->setRawContent($link);
  42. $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
  43. // Ensure the content of the link is escaped.
  44. $this->assertRaw('<em>link with markup</em> <strong>Test!</strong>');
  45. // Test passing an unsafe string to t().
  46. $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
  47. return \Drupal::l('<em>link with markup</em>', $url);
  48. });
  49. $this->setRawContent($link);
  50. $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
  51. // Ensure the content of the link is escaped.
  52. $this->assertEscaped('<em>link with markup</em>');
  53. $this->assertRaw('<strong>Test!</strong>');
  54. }
  55. }