You are here

public function PageRedirect::getActionTarget in Rabbit Hole 8

Same name and namespace in other branches
  1. 2.x src/Plugin/RabbitHoleBehaviorPlugin/PageRedirect.php \Drupal\rabbit_hole\Plugin\RabbitHoleBehaviorPlugin\PageRedirect::getActionTarget()

Returns the action target URL object.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity the action is being performed on.

Return value

string|null Absolute destination URL or NULL if proper URL wasn't found.

1 call to PageRedirect::getActionTarget()
PageRedirect::performAction in src/Plugin/RabbitHoleBehaviorPlugin/PageRedirect.php
Perform the rabbit hole action.

File

src/Plugin/RabbitHoleBehaviorPlugin/PageRedirect.php, line 187

Class

PageRedirect
Redirects to another page.

Namespace

Drupal\rabbit_hole\Plugin\RabbitHoleBehaviorPlugin

Code

public function getActionTarget(EntityInterface $entity) {
  $target = $entity
    ->get('rh_redirect')->value;
  if (empty($target)) {
    $bundle_settings = $this
      ->getBundleSettings($entity);
    $target = $bundle_settings
      ->get('redirect');
    $this->cacheMetadata
      ->addCacheableDependency($bundle_settings);
  }

  // Replace any tokens if applicable.
  $langcode = $entity
    ->language()
    ->getId();
  if ($langcode == LanguageInterface::LANGCODE_NOT_APPLICABLE) {
    $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED;
  }

  // Convert <front> into valid URI.
  $target = $target === '<front>' ? 'base:/' : $target;
  $target = $this->token
    ->replace($target, [
    $entity
      ->getEntityTypeId() => $entity,
  ], [
    'clear' => TRUE,
    'langcode' => $langcode,
  ], $this->cacheMetadata);
  $target = PlainTextOutput::renderFromHtml($target);
  if (empty($target)) {
    return NULL;
  }

  // If non-absolute URI, pass URL through Drupal's URL generator to
  // handle languages etc.
  if (!UrlHelper::isExternal($target)) {
    $scheme = parse_url($target, PHP_URL_SCHEME);
    if ($scheme === NULL) {
      $target = 'internal:' . $target;
    }
    try {
      $target = Url::fromUri($target)
        ->toString();
    } catch (\InvalidArgumentException $exception) {
      return NULL;
    }
  }
  return $target;
}