You are here

class GoogleTagManager in Analytics 8

Google Tag Manager analytics service plugin.

Plugin annotation


@AnalyticsService(
  id = "google_tag_manager",
  label = @Translation("Google Tag Manager"),
  multiple = true,
)

Hierarchy

Expanded class hierarchy of GoogleTagManager

File

src/Plugin/AnalyticsService/GoogleTagManager.php, line 20

Namespace

Drupal\analytics\Plugin\AnalyticsService
View source
class GoogleTagManager extends ServicePluginBase {
  use ServiceDataTrait;

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [
      'container_id' => '',
      'data_layer' => [
        'name' => 'dataLayer',
        'value' => '',
      ],
      'optimize_anti_flicker' => FALSE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form['container_id'] = [
      '#type' => 'textfield',
      '#title' => t('Container ID'),
      '#default_value' => $this->configuration['container_id'],
      '#required' => TRUE,
      '#size' => 15,
      '#placeholder' => 'GTM-XXXX',
    ];
    $form['data_layer'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('Data Layer'),
      '#open' => TRUE,
    ];
    $form['data_layer']['name'] = [
      '#type' => 'textfield',
      '#title' => t('Data Layer variable'),
      '#default_value' => $this->configuration['data_layer']['name'],
      '#size' => 15,
      '#required' => TRUE,
    ];
    $form['data_layer']['value'] = [
      '#type' => 'textarea',
      '#title' => t('Data Layer value JSON'),
      '#default_value' => $this->configuration['data_layer']['value'],
      '#element_validate' => [
        [
          get_class($this),
          'validateJson',
        ],
      ],
    ];
    $form['optimize_anti_flicker'] = [
      '#type' => 'checkbox',
      '#title' => $this
        ->t('Add the <a href="@url">Optimize anti-flicker snippet</a>', [
        '@url' => 'https://support.google.com/optimize/answer/7100284',
      ]),
      '#description' => $this
        ->t('If you notice page flicker when using Google Optimize, adding this snippet can help.'),
      '#default_value' => $this->configuration['optimize_anti_flicker'],
      '#weight' => 50,
      '#return_value' => TRUE,
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getOutput() {
    $output = [];
    $data_layer_name = $this->configuration['data_layer']['name'];
    if ($data = $this
      ->getData()) {
      $data_layer_json = json_encode($data, JSON_PRETTY_PRINT);
      $data_layer_js = <<<END
var {<span class="php-variable">$data_layer_name</span>} = window.dataLayer = window.dataLayer || [];
{<span class="php-variable">$data_layer_name</span>}.push({<span class="php-variable">$data_layer_json</span>});
END;
      $output['#attached']['html_head'][] = [
        [
          '#type' => 'html_tag',
          '#tag' => 'script',
          '#value' => Markup::create($data_layer_js),
          // This always needs to be super early.
          '#weight' => -900,
        ],
        'analytics_' . $this
          ->getServiceId() . '_data_layer',
      ];
    }
    if ($this->configuration['optimize_anti_flicker']) {

      // This only needs to be output once so it has the same ID every time.
      $output['#attached']['html_head'][] = [
        [
          '#type' => 'html_tag',
          '#tag' => 'style',
          '#value' => Markup::create('.async-hide { opacity: 0 !important}'),
        ],
        'google_analytics_optimize_anti_flicker_css',
      ];
      $optimize_js = <<<END
(function(a,s,y,n,c,h,i,d,e){s.className+=' '+y;h.start=1*new Date;
h.end=i=function(){s.className=s.className.replace(RegExp(' ?'+y),'')};
(a[n]=a[n]||[]).hide=h;setTimeout(function(){i();h.end=null},c);h.timeout=c;
})(window,document.documentElement,'async-hide','dataLayer',4000,
{'{<span class="php-variable">$this</span>-&gt;<span class="php-function-or-constant property member-of-self">configuration</span>[<span class="php-string">'container_id'</span>]}':true});
END;
      $output['#attached']['html_head'][] = [
        [
          '#type' => 'html_tag',
          '#tag' => 'script',
          '#value' => Markup::create($optimize_js),
        ],
        'analytics_' . $this
          ->getServiceId() . '_optimize_anti_flicker_js',
      ];
    }
    $tag_manager_js = <<<END
(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','{<span class="php-variable">$data_layer_name</span>}','{<span class="php-variable">$this</span>-&gt;<span class="php-function-or-constant property member-of-self">configuration</span>[<span class="php-string">'container_id'</span>]}');
END;
    $output['#attached']['html_head'][] = [
      [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#value' => AnalyticsJsMarkup::create($tag_manager_js),
      ],
      'analytics_' . $this
        ->getServiceId() . '_tag_manager',
    ];
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultData() {
    if (!empty($this->configuration['data_layer']['value'])) {
      return json_decode($this->configuration['data_layer']['value'], TRUE) ?? [];
    }
    else {
      return [];
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
GoogleTagManager::buildConfigurationForm public function Form constructor. Overrides ServicePluginBase::buildConfigurationForm
GoogleTagManager::defaultConfiguration public function Gets default configuration for this plugin. Overrides ServicePluginBase::defaultConfiguration
GoogleTagManager::defaultData public function Overrides ServiceDataTrait::defaultData
GoogleTagManager::getOutput public function Returns the output of the analytics service. Overrides ServicePluginBase::getOutput
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance.
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
ServiceDataTrait::getData public function
ServiceDataTrait::moduleHandler abstract protected function Wraps the module handler.
ServicePluginBase::$hasMultiple protected property
ServicePluginBase::$serviceId protected property The ID of the service config entity using this plugin.
ServicePluginBase::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides DependentPluginInterface::calculateDependencies
ServicePluginBase::canTrack public function Determines if the current service can track the current request. Overrides ServicePluginInterface::canTrack
ServicePluginBase::getAmpOutput public function Build an <amp-analytics> tag for output on an amp-enabled page request.
ServicePluginBase::getCacheableUrls public function Overrides ServicePluginInterface::getCacheableUrls
ServicePluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ServicePluginBase::getLabel public function Returns the label of the analytics service. Overrides ServicePluginInterface::getLabel
ServicePluginBase::getServiceId public function Gets the current service config entity ID that is using this plugin. Overrides ServicePluginInterface::getServiceId
ServicePluginBase::hasMultipleInstances public function
ServicePluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
ServicePluginBase::setServiceId public function Sets the current service config entity ID that is using this plugin. Overrides ServicePluginInterface::setServiceId
ServicePluginBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm
ServicePluginBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm
ServicePluginBase::validateJson public static function Form element validation callback for a JSON textarea field.
ServicePluginBase::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PluginBase::__construct
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.