function LinkGeneratorTest::assertLink

Same name in other branches
  1. 9 core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php \Drupal\Tests\Core\Utility\LinkGeneratorTest::assertLink()
  2. 10 core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php \Drupal\Tests\Core\Utility\LinkGeneratorTest::assertLink()
  3. 11.x core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php \Drupal\Tests\Core\Utility\LinkGeneratorTest::assertLink()

Checks that a link with certain properties exists in a given HTML snippet.

Parameters

array $properties: An associative array of link properties, with the following keys:

  • attributes: optional array of HTML attributes that should be present.
  • content: optional link content.

\Drupal\Component\Render\MarkupInterface $html: The HTML to check.

int $count: How many times the link should be present in the HTML. Defaults to 1.

10 calls to LinkGeneratorTest::assertLink()
LinkGeneratorTest::testGenerate in core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php
Tests the generate() method with a route.
LinkGeneratorTest::testGenerateActive in core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php
Tests the active class on the link method.
LinkGeneratorTest::testGenerateAttributes in core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php
Tests the link method with additional attributes.
LinkGeneratorTest::testGenerateExternal in core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php
Tests the generate() method with an external URL.
LinkGeneratorTest::testGenerateHrefs in core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php
Tests the link method with certain hrefs.

... See full list

File

core/tests/Drupal/Tests/Core/Utility/LinkGeneratorTest.php, line 624

Class

LinkGeneratorTest
@coversDefaultClass \Drupal\Core\Utility\LinkGenerator @group Utility

Namespace

Drupal\Tests\Core\Utility

Code

public static function assertLink(array $properties, MarkupInterface $html, $count = 1) {
    // Provide default values.
    $properties += [
        'attributes' => [],
    ];
    // Create an XPath query that selects a link element.
    $query = '//a';
    // Append XPath predicates for the attributes and content text.
    $predicates = [];
    foreach ($properties['attributes'] as $attribute => $value) {
        $predicates[] = "@{$attribute}='{$value}'";
    }
    if (!empty($properties['content'])) {
        $predicates[] = "contains(.,'{$properties['content']}')";
    }
    if (!empty($predicates)) {
        $query .= '[' . implode(' and ', $predicates) . ']';
    }
    // Execute the query.
    $document = new \DOMDocument();
    $document->loadHTML($html);
    $xpath = new \DOMXPath($document);
    self::assertEquals($count, $xpath->query($query)->length);
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.