You are here

class CspSubscriber in Googalytics - Google Analytics 8

Alter CSP policy for Google Analytics.

Hierarchy

  • class \Drupal\ga\EventSubscriber\CspSubscriber implements \Symfony\Component\EventDispatcher\EventSubscriberInterface

Expanded class hierarchy of CspSubscriber

1 file declares its use of CspSubscriber
CspSubscriberTest.php in tests/src/Unit/EventSubscriber/CspSubscriberTest.php
1 string reference to 'CspSubscriber'
ga.services.yml in ./ga.services.yml
ga.services.yml
1 service uses CspSubscriber
ga.csp_subscriber in ./ga.services.yml
Drupal\ga\EventSubscriber\CspSubscriber

File

src/EventSubscriber/CspSubscriber.php, line 12

Namespace

Drupal\ga\EventSubscriber
View source
class CspSubscriber implements EventSubscriberInterface {
  const TRACKING_DOMAIN = 'https://www.google-analytics.com';

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    if (!class_exists(CspEvents::class)) {
      return [];
    }
    $events[CspEvents::POLICY_ALTER] = [
      'onCspPolicyAlter',
    ];
    return $events;
  }

  /**
   * Alter CSP policy for tracking requests.
   *
   * @param \Drupal\csp\Event\PolicyAlterEvent $alterEvent
   *   The Policy Alter event.
   */
  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);
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CspSubscriber::getSubscribedEvents public static function Returns an array of event names this subscriber wants to listen to.
CspSubscriber::onCspPolicyAlter public function Alter CSP policy for tracking requests.
CspSubscriber::TRACKING_DOMAIN constant