You are here

function redirect_path_alias_update in Redirect 8

Implements hook_ENTITY_TYPE_update() for path_alias.

File

./redirect.module, line 89
The redirect module.

Code

function redirect_path_alias_update(PathAliasInterface $path_alias) {
  $config = \Drupal::config('redirect.settings');
  if (!$config
    ->get('auto_redirect')) {
    return;
  }

  /** @var \Drupal\path_alias\PathAliasInterface $original_path_alias */
  $original_path_alias = $path_alias->original;

  // Delete all redirects having the same source as this alias.
  redirect_delete_by_path($path_alias
    ->getAlias(), $path_alias
    ->language()
    ->getId(), FALSE);

  // Create redirect from the old path alias to the new one.
  if ($original_path_alias
    ->getAlias() != $path_alias
    ->getAlias()) {
    if (!redirect_repository()
      ->findMatchingRedirect($original_path_alias
      ->getAlias(), [], $original_path_alias
      ->language()
      ->getId())) {
      $redirect = Redirect::create();
      $redirect
        ->setSource($original_path_alias
        ->getAlias());
      $redirect
        ->setRedirect($path_alias
        ->getPath());
      $redirect
        ->setLanguage($original_path_alias
        ->language()
        ->getId());
      $redirect
        ->setStatusCode($config
        ->get('default_status_code'));
      $redirect
        ->save();
    }
  }
}