You are here

public function LinkcheckerLinkLinkExtractorTest::testLinkExtractor in Link checker 8

Test Link field extractor.

File

tests/src/Kernel/LinkcheckerLinkLinkExtractorTest.php, line 74

Class

LinkcheckerLinkLinkExtractorTest
Test html link extractor.

Namespace

Drupal\Tests\linkchecker\Kernel

Code

public function testLinkExtractor() {
  $type = NodeType::create([
    'name' => 'Links',
    'type' => 'links',
  ]);
  $type
    ->save();
  FieldStorageConfig::create([
    'field_name' => 'field_test',
    'entity_type' => 'node',
    'entity_bundle' => 'links',
    'type' => 'link',
    'cardinality' => -1,
  ])
    ->save();
  FieldConfig::create([
    'entity_type' => 'node',
    'field_name' => 'field_test',
    'bundle' => 'links',
    'settings' => [
      'link_type' => LinkItemInterface::LINK_GENERIC,
    ],
  ])
    ->save();
  $node = $this
    ->createNode([
    'type' => 'links',
    'field_test' => [
      [
        $this
          ->getTestLinks(),
      ],
    ],
  ]);
  $node
    ->set('field_test', $this
    ->getTestLinks());
  $htmlTagConfig = [
    'from_audio',
    'from_embed',
    'from_iframe',
    'from_img',
    'from_object',
    'from_video',
  ];

  // First disable extraction from each tag.
  foreach ($htmlTagConfig as $tagConfigName) {
    $this->linkcheckerSetting
      ->set('extract.' . $tagConfigName, FALSE);
  }

  // Enable from_a for checking link field items.
  $this->linkcheckerSetting
    ->set('extract.from_a', TRUE);
  $this->linkcheckerSetting
    ->save(TRUE);
  $testCases = $this
    ->getTestUrlList();
  $extractedUrls = [];
  $field_values = $node
    ->get('field_test')
    ->getValue();

  // Loop over field values extracting URLs from each.
  foreach ($field_values as $fv) {
    $extractedUrls = array_merge($extractedUrls, $this->linkLinkExtractor
      ->extract([
      $fv,
    ]));
  }

  // Assert that each URL is found.
  foreach ($testCases as $url) {
    $this
      ->assertContains($url, $extractedUrls, new FormattableMarkup('URL @url was not extracted from tag @tag!', [
      '@url' => $url,
      '@tag' => str_replace('from_', '', 'from_a'),
    ]));
  }

  // Assert that the number of extracted URLs matches the number of test
  // cases.
  $countTestCases = count($testCases);
  $countExtractedLinks = count($extractedUrls);
  $this
    ->assertEquals($countTestCases, $countExtractedLinks, new FormattableMarkup('Expected to extract @count but get @actual links.', [
    '@count' => $countTestCases,
    '@actual' => $countExtractedLinks,
  ]));
}