You are here

class ServicePluginBase in Analytics 8

Defines a base implementation for analytics service plugins will extend.

Hierarchy

Expanded class hierarchy of ServicePluginBase

5 files declare their use of ServicePluginBase
AmpAnalytics.php in analytics_amp/src/Plugin/AnalyticsService/AmpAnalytics.php
AmpTrackingPixel.php in analytics_amp/src/Plugin/AnalyticsService/AmpTrackingPixel.php
GoogleAnalyticsGa.php in analytics_google/src/Plugin/AnalyticsService/GoogleAnalyticsGa.php
GoogleTagManager.php in src/Plugin/AnalyticsService/GoogleTagManager.php
Piwik.php in analytics_piwik/src/Plugin/AnalyticsService/Piwik.php

File

src/Plugin/ServicePluginBase.php, line 17

Namespace

Drupal\analytics\Plugin
View source
class ServicePluginBase extends PluginBase implements ServicePluginInterface {
  use StringTranslationTrait;
  use PluginDependencyTrait;
  protected $hasMultiple;

  /**
   * The ID of the service config entity using this plugin.
   *
   * @var string
   */
  protected $serviceId;

  /**
   * {@inheritdoc}
   */
  public function setServiceId($service_id) {
    $this->serviceId = $service_id;
  }

  /**
   * {@inheritdoc}
   */
  public function getServiceId() {
    return $this->serviceId;
  }

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);

    // Merge the default config.
    $this
      ->setConfiguration($configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function getLabel() {
    return $this->pluginDefinition['label'];
  }

  /**
   * {@inheritdoc}
   */
  public function canTrack() {

    // @todo Move this to an entity operation on AnalyticsService?
    $access = AccessResult::allowedIf(!\Drupal::service('router.admin_context')
      ->isAdminRoute());
    $access
      ->addCacheContexts([
      'url.path',
    ]);
    $access = $access
      ->andIf(AccessResult::allowedIf(!\Drupal::currentUser()
      ->hasPermission('bypass all analytics services')));
    $access
      ->cachePerPermissions();
    \Drupal::moduleHandler()
      ->alter('analytics_service_can_track_access', $access, $this);
    return $access
      ->isAllowed();
  }
  public function hasMultipleInstances() {
    if (!isset($this->hasMultiple)) {
      $services = \Drupal::service('entity_type.manager')
        ->getStorage('analytics_service')
        ->loadMultiple();
      $count = 0;
      foreach ($services as $service) {
        if ($service->service == $this
          ->getPluginId()) {
          $count++;
        }
      }
      $this->hasMultiple = $count >= 2;
    }
    return $this->hasMultiple;
  }

  /**
   * {@inheritdoc}
   */
  public function getOutput() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheableUrls() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
    $this->configuration = NestedArray::mergeDeep($this
      ->defaultConfiguration(), $configuration);
  }

  /**
   * {@inheritdoc}
   */
  public function getConfiguration() {
    return $this->configuration;
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {

    // Do nothing.
  }

  /**
   * {@inheritdoc}
   */
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
    foreach (array_intersect_key($form_state
      ->getValues(), $this->configuration) as $config_key => $config_value) {
      $this->configuration[$config_key] = $config_value;
    }
  }

  /**
   * Build an <amp-analytics> tag for output on an amp-enabled page request.
   *
   * @param array $settings
   *   The settings of the amp-analytics tag.
   *   - type
   *   - config_json
   *   - config_url
   *
   * @return array
   *   A structured, renderable array.
   */
  public function getAmpOutput(array $settings) {
    $output = [];
    $element = [
      '#type' => 'html_tag',
      '#tag' => 'amp-analytics',
      '#attached' => [
        'library' => 'amp/amp.analytics',
      ],
    ];
    if (!empty($settings['config_json'])) {
      $json_element = [
        '#type' => 'html_tag',
        '#tag' => 'script',
        '#attributes' => [
          'type' => 'application/ld+json',
        ],
        '#value' => $settings['config_json'],
      ];
      $element['#value'] = \Drupal::service('renderer')
        ->renderPlain($json_element);
    }
    if (!empty($settings['type'])) {
      $element['#attributes']['type'] = $settings['type'];
    }
    if (!empty($settings['config_url'])) {
      $element['#attributes']['config'] = $settings['config_url'];
    }
    $output['analytics_' . $this
      ->getServiceId()] = $element;
    return $output;
  }

  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return [];
  }

  /**
   * Form element validation callback for a JSON textarea field.
   *
   * Note that #required is validated by _form_validate() already.
   */
  public static function validateJson(&$element, FormStateInterface $form_state) {
    $value = $element['#value'];
    if ($value === '') {
      return;
    }
    if (is_string($value)) {
      $name = empty($element['#title']) ? $element['#parents'][0] : $element['#title'];
      $json = json_decode($value, TRUE);
      if ($error = json_last_error()) {
        $form_state
          ->setError($element, t('%name is not valid JSON: @error.', [
          '%name' => $name,
          '@error' => json_last_error_msg(),
        ]));
        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.
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::moduleHandler protected function Wraps the module handler. 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. 1
ServicePluginBase::$hasMultiple protected property
ServicePluginBase::$serviceId protected property The ID of the service config entity using this plugin.
ServicePluginBase::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm 5
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::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurableInterface::defaultConfiguration 5
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::getOutput public function Returns the output of the analytics service. Overrides ServicePluginInterface::getOutput 5
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.