You are here

public function RedirectRepository::findMatchingRedirect in Redirect 8

Gets a redirect for given path, query and language.

Parameters

string $source_path: The redirect source path.

array $query: The redirect source path query.

$language: The language for which is the redirect.

Return value

\Drupal\redirect\Entity\Redirect The matched redirect entity.

Throws

\Drupal\redirect\Exception\RedirectLoopException

1 call to RedirectRepository::findMatchingRedirect()
RedirectRepository::findByRedirect in src/RedirectRepository.php
Helper function to find recursive redirects.

File

src/RedirectRepository.php, line 65

Class

RedirectRepository

Namespace

Drupal\redirect

Code

public function findMatchingRedirect($source_path, array $query = [], $language = Language::LANGCODE_NOT_SPECIFIED) {
  $source_path = ltrim($source_path, '/');
  $hashes = [
    Redirect::generateHash($source_path, $query, $language),
  ];
  if ($language != Language::LANGCODE_NOT_SPECIFIED) {
    $hashes[] = Redirect::generateHash($source_path, $query, Language::LANGCODE_NOT_SPECIFIED);
  }

  // Add a hash without the query string if using passthrough querystrings.
  if (!empty($query) && $this->config
    ->get('passthrough_querystring')) {
    $hashes[] = Redirect::generateHash($source_path, [], $language);
    if ($language != Language::LANGCODE_NOT_SPECIFIED) {
      $hashes[] = Redirect::generateHash($source_path, [], Language::LANGCODE_NOT_SPECIFIED);
    }
  }

  // Load redirects by hash. A direct query is used to improve performance.
  $rid = $this->connection
    ->query('SELECT rid FROM {redirect} WHERE hash IN (:hashes[]) ORDER BY LENGTH(redirect_source__query) DESC', [
    ':hashes[]' => $hashes,
  ])
    ->fetchField();
  if (!empty($rid)) {

    // Check if this is a loop.
    if (in_array($rid, $this->foundRedirects)) {
      throw new RedirectLoopException('/' . $source_path, $rid);
    }
    $this->foundRedirects[] = $rid;
    $redirect = $this
      ->load($rid);

    // Find chained redirects.
    if ($recursive = $this
      ->findByRedirect($redirect, $language)) {

      // Reset found redirects.
      $this->foundRedirects = [];
      return $recursive;
    }
    return $redirect;
  }

  // Reset found redirects.
  $this->foundRedirects = [];
  return NULL;
}