Skip to content

Writing an analytics service plugin

Other modules can provide more services as #[AnalyticsService] plugins in src/Plugin/AnalyticsService, extending Drupal\analytics\Plugin\ServicePluginBase. Each analytics service that site builders add at Administration > Configuration > Web services > Analytics services is a config entity that uses one plugin and holds its settings.

A minimal plugin

<?php

declare(strict_types=1);

namespace Drupal\my_module\Plugin\AnalyticsService;

use Drupal\analytics\Attribute\AnalyticsService;
use Drupal\analytics\Plugin\ServicePluginBase;
use Drupal\analytics\Render\AnalyticsJsMarkup;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;

#[AnalyticsService(
  id: 'example_analytics',
  label: new TranslatableMarkup('Example Analytics'),
)]
class ExampleAnalytics extends ServicePluginBase {

  public function defaultConfiguration(): array {
    return parent::defaultConfiguration() + [
      'site_key' => '',
    ];
  }

  public function buildConfigurationForm(array $form, FormStateInterface $form_state): array {
    $form['site_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Site key'),
      '#description' => $this->t('Shown under <em>Settings > Tracking code</em> in Example Analytics. See <a href=":url">how to find the site key</a>.', [':url' => 'https://example.com/docs/site-key']),
      '#default_value' => $this->configuration['site_key'],
      '#required' => TRUE,
    ];
    return $form;
  }

  public function getOutput() {
    // Json::encode() escapes characters that could end the script element.
    $site_key = Json::encode((string) $this->configuration['site_key']);
    $output = [
      '#type' => 'html_tag',
      '#tag' => 'script',
      '#value' => AnalyticsJsMarkup::create("window.exampleAnalytics = {key: {$site_key}};"),
    ];
    return $output;
  }

  public function getCspSources(): array {
    return [
      'script-src' => ['https://cdn.example.com/analytics.js'],
      'connect-src' => ['https://collect.example.com'],
    ];
  }

}
  • getOutput() returns a render array, which the module adds to the end of the page's <body> with hook_page_bottom(), so a plain html_tag element is enough. Only scripts the service needs in the <head>, such as a tag manager's container that has to start before the page renders, go in #attached['html_head'], as the included Google Tag Manager and Matomo plugins do. Core renders html_head items on their own, after the page's cacheability is final, so #cache inside them is lost: declare what that output varies by in the plugin's getCacheContexts() and getCacheTags(), or apply it to the output array itself. Wrap inline JavaScript in AnalyticsJsMarkup, which adds the Do Not Track check when it's turned on in the module's settings, and put settings into it with Json::encode().
  • ServicePluginBase::access() decides whether the service runs on a request, for the track operation: not on admin routes, and not for users with the "bypass all analytics services" permission. Override it, and call the parent for operations you don't handle, to change that. Sites change it with hook_analytics_service_access() (see Working with the data layer).
  • Give each settings field that takes a value from the service, such as an ID or URL, a #description saying where to find it, with a link to the service's docs.

Configuration schema

The module's configuration is fully validatable, so each plugin needs a schema for its settings, with constraints on every key, named analytics.service_configuration.<plugin ID>:

analytics.service_configuration.example_analytics:
  type: analytics.service_configuration
  label: 'Example Analytics service settings'
  mapping:
    site_key:
      type: string
      label: 'Site key'
      constraints:
        NotBlank: {}
        Regex:
          pattern: '/^[A-Za-z0-9]+$/'
          message: "The %value site key is not valid."

Content Security Policy

Plugins list the URLs their script loads from and sends data to in getCspSources(), keyed by Content Security Policy directive. When the Content-Security-Policy module is installed, the module reduces them to origins and adds them to the policy with Helper's RenderElement::attachCsp(). Services that load more from hosts set up in the service itself, such as a tag manager's tags, set the attribute's additionalSources property, so the service form reminds site builders to add those hosts.

Attribute properties

  • multiple: whether a site can add more than one service with the plugin, such as several Google Tag Manager containers.
  • additionalSources: see Content Security Policy.
  • deprecated: to deprecate a plugin, set the attribute's deprecated property to a deprecation message: the plugin is no longer offered for new services, and services that use it are listed on the status report.

Data layer

Plugins for services with a data layer, such as tag managers, use Drupal\analytics\Plugin\ServiceDataTrait. See Working with the data layer.