function domain_alias_domain_load in Domain Access 8
Same name and namespace in other branches
- 7.3 domain_alias/domain_alias.domain.inc \domain_alias_domain_load()
Implements hook_ENTITY_TYPE_load().
File
- domain_alias/
domain_alias.module, line 86 - Maps multiple host requests to a single domain record.
Code
function domain_alias_domain_load($entities) {
static $enabled;
// We can only perform meaningful actions if url.site is a cache context.
// Otherwise, the render process ignores our changes.
if (!isset($enabled)) {
$required_cache_contexts = \Drupal::getContainer()
->getParameter('renderer.config')['required_cache_contexts'];
if (!in_array('url.site', $required_cache_contexts) && !in_array('url', $required_cache_contexts)) {
$enabled = FALSE;
return;
}
$enabled = TRUE;
}
// We cannot run before the negotiator service has fired.
$negotiator = \Drupal::service('domain.negotiator');
$active = $negotiator
->getActiveDomain();
// Do nothing if no domain is active.
if (empty($active)) {
return;
}
// Load and rewrite environment-specific aliases.
$alias_storage = \Drupal::entityTypeManager()
->getStorage('domain_alias');
if (isset($active->alias) && $active->alias
->getEnvironment() != 'default') {
foreach ($entities as $id => $domain) {
if ($environment_aliases = $alias_storage
->loadByEnvironmentMatch($domain, $active->alias
->getEnvironment())) {
foreach ($environment_aliases as $environment_alias) {
$pattern = $environment_alias
->getPattern();
// Add a canonical property.
$domain
->setCanonical();
// Override the domain hostname and path. We always prefer a string
// match.
if (substr_count($pattern, '*') < 1) {
$domain
->setHostname($pattern);
$domain
->setPath();
$domain
->setUrl();
break;
}
else {
// Do a wildcard replacement based on the current request.
$request = $negotiator
->negotiateActiveHostname();
// First, check for a wildcard port.
if (substr_count($pattern, ':*') > 0) {
// Do not replace ports unless they are nonstandard. See
// \Symfony\Component\HttpFoundation\Request\getHttpHost().
if (substr_count($request, ':') > 0) {
$search = explode(':', $pattern);
$replace = explode(':', $request);
if (!empty($search[1]) && !empty($replace[1])) {
$pattern = str_replace(':' . $search[1], ':' . $replace[1], $pattern);
}
}
else {
$pattern = str_replace(':*', '', $pattern);
}
}
$replacements = [
'.' => '\\.',
'*' => '(.+?)',
];
$regex = '/^' . strtr($active->alias
->getPattern(), $replacements) . '$/';
if (preg_match($regex, $request, $matches) && isset($matches[1])) {
$pattern = str_replace('*', $matches[1], $pattern);
}
// Do not let the domain loop back on itself.
if ($pattern != $domain
->getCanonical()) {
$domain
->setHostname($pattern);
$domain
->setPath();
$domain
->setUrl();
}
}
}
}
}
}
}