3 namespace Drupal\KernelTests\Core\Url;
5 use Drupal\Component\Render\MarkupInterface;
6 use Drupal\Core\Render\RenderContext;
8 use Drupal\KernelTests\KernelTestBase;
11 * Tests link generation with hooks.
15 class LinkGenerationTest extends KernelTestBase {
17 public static $modules = ['link_generation_test'];
20 * Tests how hook_link_alter() can affect escaping of the link text.
22 public function testHookLinkAlter() {
23 $url = Url::fromUri('http://example.com');
24 $renderer = \Drupal::service('renderer');
26 $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
27 return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
29 $this->setRawContent($link);
30 $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
31 // Ensure the content of the link is not escaped.
32 $this->assertRaw('<em>link with markup</em>');
34 // Test just adding text to an already safe string.
35 \Drupal::state()->set('link_generation_test_link_alter', TRUE);
36 $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
37 return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
39 $this->setRawContent($link);
40 $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
41 // Ensure the content of the link is escaped.
42 $this->assertEscaped('<em>link with markup</em> <strong>Test!</strong>');
44 // Test passing a safe string to t().
45 \Drupal::state()->set('link_generation_test_link_alter_safe', TRUE);
46 $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
47 return \Drupal::l(['#markup' => '<em>link with markup</em>'], $url);
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->assertRaw('<em>link with markup</em> <strong>Test!</strong>');
54 // Test passing an unsafe string to t().
55 $link = $renderer->executeInRenderContext(new RenderContext(), function () use ($url) {
56 return \Drupal::l('<em>link with markup</em>', $url);
58 $this->setRawContent($link);
59 $this->assertTrue($link instanceof MarkupInterface, 'The output of link generation is marked safe as it is a link.');
60 // Ensure the content of the link is escaped.
61 $this->assertEscaped('<em>link with markup</em>');
62 $this->assertRaw('<strong>Test!</strong>');