You are here

public function RedirectAPITest::testLoopDetection in Redirect 8

Test loop detection.

File

tests/src/Kernel/RedirectAPITest.php, line 203

Class

RedirectAPITest
Redirect entity and redirect API test coverage.

Namespace

Drupal\Tests\redirect\Kernel

Code

public function testLoopDetection() {

  // Add a chained redirect that isn't a loop.

  /** @var \Drupal\redirect\Entity\Redirect $one */
  $one = $this->storage
    ->create();
  $one
    ->setSource('my-path');
  $one
    ->setRedirect('node');
  $one
    ->save();

  /** @var \Drupal\redirect\Entity\Redirect $two */
  $two = $this->storage
    ->create();
  $two
    ->setSource('second-path');
  $two
    ->setRedirect('my-path');
  $two
    ->save();

  /** @var \Drupal\redirect\Entity\Redirect $three */
  $three = $this->storage
    ->create();
  $three
    ->setSource('third-path');
  $three
    ->setRedirect('second-path');
  $three
    ->save();

  /** @var \Drupal\redirect\RedirectRepository $repository */
  $repository = \Drupal::service('redirect.repository');
  $found = $repository
    ->findMatchingRedirect('third-path');
  if (!empty($found)) {
    $this
      ->assertEquals($found
      ->getRedirectUrl()
      ->toString(), '/node', 'Chained redirects properly resolved in findMatchingRedirect.');
  }
  else {
    $this
      ->fail('Failed to resolve a chained redirect.');
  }

  // Create a loop.
  $one
    ->setRedirect('third-path');
  $one
    ->save();
  try {
    $repository
      ->findMatchingRedirect('third-path');
    $this
      ->fail('Failed to detect a redirect loop.');
  } catch (RedirectLoopException $e) {
    $this
      ->pass('Properly detected a redirect loop.');
  }
}