Drupal Version
9.2.2
Domain module version
(8.x) 1.x-dev
Expected Behavior
[What did you try to do? What URL did you use to do it?]
Get the active domain from DomainNegotiator::getActiveDomain()
Actual Behavior
[What actually happened?]
DomainNegotiator::getActiveDomain() returns null in some circumstances, causing unexpected behaviors like 403 in domain front pages when combined with domain_site_settings & domain_access (see
#3126141: Node access restricted for Anonymous →
), null pointer exceptions, etc.
It seems to be more frequent when called from event subscribers. Actually some existing implementations call getActiveDomain twice as a workaround (- 1 -) (- 2 -).
Steps to reproduce
[A bullet list of steps to reproduce the error. Note if the error always happens or sometimes happens.]
Unfortunately it is not clear what are the exact circumstances that makes DomainNegotiator::getActiveDomain() return null. It might be related to the state of cache or some other arbitrary condition. Commit 68ecdbf4 seems to be related.
Proposed solution
Ensure that DomainNegotiator::getActiveDomain() tries to look up the active domain when is is called for the first time, avoiding to do so by domain negotiator consumers as:
...
$active = \Drupal::service('domain.negotiator')->getActiveDomain();
if (empty($active)) {
$active = \Drupal::service('domain.negotiator')->getActiveDomain(TRUE);
}
...
Review the method documentation, there is no mention that it could return NULL, e.g., when no domain records defined.