public function UrlTest::testLinkAttributes in Drupal 9
Tests that default and custom attributes are handled correctly on links.
File
- core/
modules/ system/ tests/ src/ Kernel/ Common/ UrlTest.php, line 79
Class
- UrlTest
- Confirm that \Drupal\Core\Url, \Drupal\Component\Utility\UrlHelper::filterQueryParameters(), \Drupal\Component\Utility\UrlHelper::buildQuery(), and \Drupal\Core\Utility\LinkGeneratorInterface::generate() work correctly with various input.
Namespace
Drupal\Tests\system\Kernel\CommonCode
public function testLinkAttributes() {
/** @var \Drupal\Core\Render\RendererInterface $renderer */
$renderer = $this->container
->get('renderer');
// Test that hreflang is added when a link has a known language.
$language = new Language([
'id' => 'fr',
'name' => 'French',
]);
$hreflang_link = [
'#type' => 'link',
'#options' => [
'language' => $language,
],
'#url' => Url::fromUri('https://www.drupal.org'),
'#title' => 'bar',
];
$langcode = $language
->getId();
// Test that the default hreflang handling for links does not override a
// hreflang attribute explicitly set in the render array.
$hreflang_override_link = $hreflang_link;
$hreflang_override_link['#options']['attributes']['hreflang'] = 'foo';
$rendered = $renderer
->renderRoot($hreflang_link);
$this
->assertTrue($this
->hasAttribute('hreflang', $rendered, $langcode), new FormattableMarkup('hreflang attribute with value @langcode is present on a rendered link when langcode is provided in the render array.', [
'@langcode' => $langcode,
]));
$rendered = $renderer
->renderRoot($hreflang_override_link);
$this
->assertTrue($this
->hasAttribute('hreflang', $rendered, 'foo'), new FormattableMarkup('hreflang attribute with value @hreflang is present on a rendered link when @hreflang is provided in the render array.', [
'@hreflang' => 'foo',
]));
// Test adding a custom class in links produced by
// \Drupal\Core\Utility\LinkGeneratorInterface::generate() and #type 'link'.
// Test the link generator.
$class_l = $this
->randomMachineName();
$link_l = Link::fromTextAndUrl($this
->randomMachineName(), Url::fromRoute('common_test.destination', [], [
'attributes' => [
'class' => [
$class_l,
],
],
]))
->toString();
$this
->assertTrue($this
->hasAttribute('class', $link_l, $class_l), new FormattableMarkup('Custom class @class is present on link when requested by Link::toString()', [
'@class' => $class_l,
]));
// Test #type.
$class_theme = $this
->randomMachineName();
$type_link = [
'#type' => 'link',
'#title' => $this
->randomMachineName(),
'#url' => Url::fromRoute('common_test.destination'),
'#options' => [
'attributes' => [
'class' => [
$class_theme,
],
],
],
];
$link_theme = $renderer
->renderRoot($type_link);
$this
->assertTrue($this
->hasAttribute('class', $link_theme, $class_theme), new FormattableMarkup('Custom class @class is present on link when requested by #type', [
'@class' => $class_theme,
]));
}