You are here

public function JavascriptLocalCache::fetchGoogleAnalyticsJavascript in Google Analytics 4.x

Download/Synchronize/Cache tracking code file locally.

Parameters

string $tracking_id: The GA Tracking ID

bool $synchronize: Synchronize to local cache if remote file has changed.

Return value

string The path to the local or remote tracking file.

File

src/JavascriptLocalCache.php, line 63

Class

JavascriptLocalCache

Namespace

Drupal\google_analytics

Code

public function fetchGoogleAnalyticsJavascript(string $tracking_id, bool $synchronize = FALSE) {
  $path = 'public://google_analytics';
  $remote_url = self::GOOGLE_ANALYTICS_JAVASCRIPT_URL . '?id=' . $tracking_id;
  $file_destination = $path . '/gtag.js';

  // If cache is disabled, just return the URL for GA
  if (!$this->configFactory
    ->get('google_analytics.settings')
    ->get('cache')) {
    return $remote_url;
  }
  if (!file_exists($file_destination) || $synchronize) {

    // Download the latest tracking code.
    try {
      $data = (string) $this->httpClient
        ->get($remote_url)
        ->getBody();
      if (file_exists($file_destination)) {

        // Synchronize tracking code and replace local file if outdated.
        $data_hash_local = Crypt::hashBase64(file_get_contents($file_destination));
        $data_hash_remote = Crypt::hashBase64($data);

        // Check that the files directory is writable.
        if ($data_hash_local != $data_hash_remote && $this->fileSystem
          ->prepareDirectory($path)) {

          // Save updated tracking code file to disk.
          $this->fileSystem
            ->saveData($data, $file_destination, FileSystemInterface::EXISTS_REPLACE);

          // Based on Drupal Core class AssetDumper.
          if (extension_loaded('zlib') && $this->configFactory
            ->get('system.performance')
            ->get('js.gzip')) {
            $this->fileSystem
              ->saveData(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FileSystemInterface::EXISTS_REPLACE);
          }
          $this->logger
            ->info('Locally cached tracking code file has been updated.');

          // Change query-strings on css/js files to enforce reload for all
          // users.
          _drupal_flush_css_js();
        }
      }
      else {

        // Check that the files directory is writable.
        if ($this->fileSystem
          ->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY)) {

          // There is no need to flush JS here as core refreshes JS caches
          // automatically, if new files are added.
          $this->fileSystem
            ->saveData($data, $file_destination, FileSystemInterface::EXISTS_REPLACE);

          // Based on Drupal Core class AssetDumper.
          if (extension_loaded('zlib') && $this->configFactory
            ->get('system.performance')
            ->get('js.gzip')) {
            $this->fileSystem
              ->saveData(gzencode($data, 9, FORCE_GZIP), $file_destination . '.gz', FileSystemInterface::EXISTS_REPLACE);
          }
          $this->logger
            ->info('Locally cached tracking code file has been saved.');
        }
      }
    } catch (RequestException $exception) {
      watchdog_exception('google_analytics', $exception);
      return $remote_url;
    }
  }

  // Return the local JS file path.
  $query_string = '?' . (\Drupal::state()
    ->get('system.css_js_query_string') ?: '0');
  return file_url_transform_relative(file_create_url($file_destination)) . $query_string;
}