Skip to content
Snippets Groups Projects
UwGoogleAnalyticsForm.php 4.99 KiB
<?php

namespace Drupal\uw_cfg_common\Form;

use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Google Analytics and ownership form.
 *
 * @package Drupal\uw_cfg_common\Form
 */
class UwGoogleAnalyticsForm extends ConfigFormBase implements ContainerInjectionInterface {

  /**
   * The render cache.
   *
   * @var \Drupal\Core\Plugin\CachedDiscoveryClearer
   */
  protected $cachePlugin;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $instance = parent::create($container);
    $instance->cachePlugin = $container->get('plugin.cache_clearer');
    return $instance;
  }

  /**
   * {@inheritDoc}
   */
  protected function getEditableConfigNames(): array {
    return ['uw_cfg_common.google_settings'];
  }

  /**
   * {@inheritDoc}
   */
  public function getFormId(): string {
    return 'uw_cfg_common_google_analytics_form';
  }

  /**
   * {@inheritDoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $form = parent::buildForm($form, $form_state);

    $config = $this->config('uw_cfg_common.google_settings');

    $form['uw_cfg_common_ga_account'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Tracking ID'),
      '#default_value' => $config->get('uw_cfg_common_ga_account'),
      '#description' => $this->t('Enter your Tracking ID for Google Universal Analytics in the form of UA-xxxxxxx-yy, or for Google Analytics 4 in the form G-XXXXXXXXXX. To get a Tracking ID, <a href="http://www.google.com/analytics/">register your site with Google Analytics</a>, or if you already have registered your site, sign in to your Google Analytics account to find the Tracking ID (listed in Admin &rarr; Property &rarr; Property Settings or in Admin &rarr; Tracking Info &rarr; Tracking Code).'),
      '#size' => 15,
      '#maxlength' => 20,
      '#required' => FALSE,
    ];

    $form['uw_cfg_common_google_site_ownership'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Google site ownership confirmation'),
      '#default_value' => $config->get('uw_cfg_common_google_site_ownership'),
      '#description' => $this->t('Enter the provided Google key string, which will display as the html meta tag google-site-verification.'),
      '#size' => 40,
      '#maxlength' => 256,
      '#required' => FALSE,
    ];

    return $form;
  }

  /**
   * {@inheritDoc}
   */
  public function validateForm(array &$form, FormStateInterface $form_state) {
    $ga_value = $form_state->getValue('uw_cfg_common_ga_account');
    $g_site_ownership = $form_state->getValue('uw_cfg_common_google_site_ownership');

    // Regex pattern for Google Analytics value.
    $ga_pattern = '/^(?:UA-\d{4,}-\d+|G-[A-Z\d]{9,10})$/';

    // Validate Google Analytics value, only when value is not empty and
    // fails regular expression pattern.
    if (!empty($ga_value) && !preg_match($ga_pattern, $ga_value)) {
      $first_letter = substr($ga_value, 0, 1);
      if ($first_letter === 'U') {
        $ga_error_message = $this->t('A valid Google Analytics Web Property ID is case sensitive and formatted like UA-xxxxxxx-yy.');
      }
      elseif ($first_letter === 'G') {
        $ga_error_message = $this->t('A valid Google Analytics 4 ID is case sensitive and formatted like G-XXXXXXXXXX.');
      }
      else {
        $ga_error_message = $this->t('The tracking ID entered does not match any of the required formats.');
      }

      // Set form error for the field.
      $form_state->setErrorByName('uw_cfg_common_ga_account', $ga_error_message);
    }

    // Add error message when default GA code has been used. This code is
    // no longer injected by default, but still should not be used.
    if (!empty($ga_value) && $ga_value === 'UA-51776731-1') {
      $ga_error_message = $this->t('Provided tracking ID is obsolete and should not be used.');
      $form_state->setErrorByName('uw_cfg_common_ga_account', $ga_error_message);
    }

    // Validate Google site ownership value, if provided, and make sure it
    // passes regular expression pattern.
    if (!empty($g_site_ownership) && !preg_match('/^[a-zA-Z0-9_]+$/', $g_site_ownership)) {
      $form_state->setErrorByName('uw_cfg_common_google_site_ownership', $this->t('A valid Google site ownership confirmation (the key string provided by Google) is needed and formatted like qWSaxyzBjZcP0PQTKec1tHgL_wf9n6s2noBPAXi1sc01.'));
    }
  }

  /**
   * {@inheritDoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    parent::submitForm($form, $form_state);

    $this->config('uw_cfg_common.google_settings')
      ->set('uw_cfg_common_ga_account', $form_state->getValue('uw_cfg_common_ga_account'))
      ->set('uw_cfg_common_google_site_ownership', $form_state->getValue('uw_cfg_common_google_site_ownership'))
      ->save();

    // Clear all plugin caches.
    $this->cachePlugin->clearCachedDefinitions();
  }

}