You are here

function domain_alias_domain_request_alter in Domain Access 8

Implements hook_domain_request_alter().

The logic in this function gives us the following matches for a request to foo.example.com.

'foo.*' '*.example.com' 'foo.*.com' 'foo.example.*' '*.foo.example.com' 'foo.example.com.*'

These patterns should be sufficient for most conditions.

File

domain_alias/domain_alias.module, line 29
Maps multiple host requests to a single domain record.

Code

function domain_alias_domain_request_alter(DomainInterface &$domain) {

  // During the installation the entity definition is not yet added when this
  // hook is invoked, so skip if not present.
  $has_definition = \Drupal::entityTypeManager()
    ->hasDefinition('domain_alias');

  // If an exact match has loaded, do nothing.
  if ($domain
    ->getMatchType() === DomainNegotiatorInterface::DOMAIN_MATCHED_EXACT || !$has_definition) {
    return;
  }

  // If no exact match, then run the alias load routine.
  $hostname = $domain
    ->getHostname();
  $alias_storage = \Drupal::entityTypeManager()
    ->getStorage('domain_alias');
  $domain_storage = \Drupal::entityTypeManager()
    ->getStorage('domain');

  /** @var \Drupal\domain_alias\Entity\DomainAlias $alias */
  if ($alias = $alias_storage
    ->loadByHostname($hostname)) {

    /** @var \Drupal\domain\Entity\Domain $domain */
    if ($domain = $domain_storage
      ->load($alias
      ->getDomainId())) {
      $domain
        ->addProperty('alias', $alias);
      $domain
        ->setMatchType(DomainNegotiatorInterface::DOMAIN_MATCHED_ALIAS);
      $redirect = $alias
        ->getRedirect();
      if (!empty($redirect)) {
        $domain
          ->setRedirect($redirect);
      }
    }
    else {

      // If the domain did not load, report an error.
      \Drupal::logger('domain_alias')
        ->error('Found matching alias %alias for host request %hostname, but failed to load matching domain with id %id.', [
        '%alias' => $alias
          ->getPattern(),
        '%hostname' => $hostname,
        '%id' => $alias
          ->getDomainId(),
      ]);
    }
  }
}