You are here

public function CspSubscriber::onCspPolicyAlter in Googalytics - Google Analytics 8

Alter CSP policy for tracking requests.

Parameters

\Drupal\csp\Event\PolicyAlterEvent $alterEvent: The Policy Alter event.

File

src/EventSubscriber/CspSubscriber.php, line 34

Class

CspSubscriber
Alter CSP policy for Google Analytics.

Namespace

Drupal\ga\EventSubscriber

Code

public function onCspPolicyAlter(PolicyAlterEvent $alterEvent) {
  $policy = $alterEvent
    ->getPolicy();
  if ($policy
    ->hasDirective('img-src')) {
    $policy
      ->appendDirective('img-src', [
      self::TRACKING_DOMAIN,
    ]);
  }
  elseif ($policy
    ->hasDirective('default-src')) {
    $imgDirective = array_merge($policy
      ->getDirective('default-src'), [
      self::TRACKING_DOMAIN,
    ]);
    $policy
      ->setDirective('img-src', $imgDirective);
  }
  if ($policy
    ->hasDirective('connect-src')) {
    $policy
      ->appendDirective('connect-src', [
      self::TRACKING_DOMAIN,
    ]);
  }
  elseif ($policy
    ->hasDirective('default-src')) {
    $connectDirective = array_merge($policy
      ->getDirective('default-src'), [
      self::TRACKING_DOMAIN,
    ]);
    $policy
      ->setDirective('connect-src', $connectDirective);
  }
}