You are here

public function LinkItemUrlValidationTest::testExternalLinkValidation in Drupal 9

Tests link validation.

File

core/modules/link/tests/src/Kernel/LinkItemUrlValidationTest.php, line 22

Class

LinkItemUrlValidationTest
Tests link field validation.

Namespace

Drupal\Tests\link\Kernel

Code

public function testExternalLinkValidation() {
  $definition = \Drupal::typedDataManager()
    ->createDataDefinition('field_item:link');
  $link_item = \Drupal::typedDataManager()
    ->create($definition);
  $test_links = $this
    ->getTestLinks();
  foreach ($test_links as $data) {
    [
      $value,
      $expected_violations,
    ] = $data;
    $link_item
      ->setValue($value);
    $violations = $link_item
      ->validate();
    $expected_count = count($expected_violations);
    $this
      ->assertCount($expected_count, $violations, sprintf('Violation message count error for %s', $value));
    if ($expected_count) {
      $i = 0;
      foreach ($expected_violations as $error_msg) {

        // If the expected message contains a '%' add the current link value.
        if (strpos($error_msg, '%')) {
          $error_msg = sprintf($error_msg, $value);
        }
        $this
          ->assertEquals($error_msg, $violations[$i++]
          ->getMessage());
      }
    }
  }
}