You are here

protected function HelpTopicsSyntaxTest::validateHtml in Drupal 9

Validates the HTML and header hierarchy for topic text.

Parameters

string $body: Body text to validate.

string $id: ID of help topic (for error messages).

1 call to HelpTopicsSyntaxTest::validateHtml()
HelpTopicsSyntaxTest::verifyTopic in core/modules/help_topics/tests/src/Functional/HelpTopicsSyntaxTest.php
Verifies rendering and standards compliance of one help topic.

File

core/modules/help_topics/tests/src/Functional/HelpTopicsSyntaxTest.php, line 174

Class

HelpTopicsSyntaxTest
Verifies that all core Help topics can be rendered and comply with standards.

Namespace

Drupal\Tests\help_topics\Functional

Code

protected function validateHtml(string $body, string $id) {
  $doc = new \DOMDocument();
  $doc->strictErrorChecking = TRUE;
  $doc->validateOnParse = FALSE;
  libxml_use_internal_errors(TRUE);
  if (!$doc
    ->loadXML('<html><body>' . $body . '</body></html>')) {
    foreach (libxml_get_errors() as $error) {
      $this
        ->fail('Topic ' . $id . ' fails HTML validation: ' . $error->message);
    }
    libxml_clear_errors();
  }

  // Check for headings hierarchy.
  $levels = [
    1,
    2,
    3,
    4,
    5,
    6,
  ];
  foreach ($levels as $level) {
    $num_headings[$level] = $doc
      ->getElementsByTagName('h' . $level)->length;
    if ($level == 1) {
      $this
        ->assertSame(0, $num_headings[1], 'Topic ' . $id . ' has no H1 tag');

      // Set num_headings to 1 for this level, so the rest of the hierarchy
      // can be tested using simpler code.
      $num_headings[1] = 1;
    }
    else {

      // We should either not have this heading, or if we do have one at this
      // level, we should also have the next-smaller level. That is, if we
      // have an h3, we should have also had an h2.
      $this
        ->assertTrue($num_headings[$level - 1] > 0 || $num_headings[$level] == 0, 'Topic ' . $id . ' has the correct H2-H6 heading hierarchy');
    }
  }
}