You are here

public function GoogleAnalyticsEventTracking::addAttachments in Google Analytics Event Tracking 8.2

Same name and namespace in other branches
  1. 8 src/GoogleAnalyticsEventTracking.php \Drupal\google_analytics_et\GoogleAnalyticsEventTracking::addAttachments()

Adds our JS library and drupalSettings to provided page attachments.

Parameters

$attachments:

File

src/GoogleAnalyticsEventTracking.php, line 74

Class

GoogleAnalyticsEventTracking

Namespace

Drupal\google_analytics_et

Code

public function addAttachments(&$attachments) {
  if ($this::isGaAttached($attachments)) {
    $et_attached = FALSE;

    /** @var \Drupal\Core\Render\RendererInterface $renderer */
    $renderer = $this->renderer;
    $trackers = $this->entityTypeManager
      ->getStorage('google_analytics_event_tracker')
      ->loadMultiple();

    /** @var \Drupal\google_analytics_et\Entity\GoogleAnalyticsEventTrackerInterface $tracker */
    foreach ($trackers as $tracker) {
      if ($this
        ->isTrackerActive($tracker)) {

        // Attach the main library.
        if (!$et_attached) {
          $attachments['#attached']['library'][] = 'google_analytics_et/google_analytics_et';
        }
        $et_attached = TRUE;
        if (empty($attachments['#attached']['drupalSettings'])) {
          $attachments['#attached']['drupalSettings'] = [];
        }
        $attachments['#attached']['drupalSettings']['googleAnalyticsEt'][] = $tracker
          ->getJsSettings();
        $renderer
          ->addCacheableDependency($attachments, $tracker);
      }
    }
  }
}