tracardi-1.0.x-dev/src/Form/ConfigurationForm.php

src/Form/ConfigurationForm.php
<?php

namespace Drupal\tracardi\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Messenger\MessengerInterface;
use Drupal\tracardi\PersonalizationInterface;
use Drupal\tracardi\PersonalizationManager;
use Drupal\tracardi\Services\AccessToken\Storage\AccessTokenStorageInterface;
use Drupal\tracardi\Services\TracardiApi;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Configure integration with Tracardi.
 */
class ConfigurationForm extends ConfigFormBase {

  /**
   * @var \Drupal\Core\Config\Config|\Drupal\Core\Config\ImmutableConfig
   *
   */
  protected $configuration;

  /**
   * @var \Drupal\tracardi\PersonalizationManager
   */
  protected $personalizationManager;

  /**
   * @var \Drupal\tracardi\Services\AccessToken\Storage\AccessTokenStorageInterface
   */
  private AccessTokenStorageInterface $accessTokenStorage;

  /**
   * @var \Drupal\tracardi\Services\TracardiApi
   */
  private TracardiApi $tracardiApi;

  /**
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   * @param \Drupal\tracardi\PersonalizationManager $personalizationManager
   * @param \Drupal\Core\Messenger\MessengerInterface $messenger
   * @param \Drupal\tracardi\Services\AccessToken\Storage\AccessTokenStorageInterface $accessTokenStorage
   * @param \Drupal\tracardi\Services\TracardiApi $tracardiApi
   */
  public function __construct(ConfigFactoryInterface $config_factory, PersonalizationManager $personalizationManager, MessengerInterface $messenger, AccessTokenStorageInterface $accessTokenStorage, TracardiApi $tracardiApi) {
    parent::__construct($config_factory);

    $this->personalizationManager = $personalizationManager;
    $this->messenger = $messenger;
    $this->accessTokenStorage = $accessTokenStorage;
    $this->tracardiApi = $tracardiApi;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('plugin.manager.personalization'),
      $container->get('messenger'),
      $container->get('tracardi.access_token_storage.drupal_state'),
      $container->get('tracardi_api')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId(): string {
    return 'tracardi_settings';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return array_merge(
      ['tracardi.settings'],
      array_values(array_map(static function (PersonalizationInterface $personalization) {
        return $personalization->getConfigName();
    }, $this->personalizationManager->loadPlugins())));
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state): array {
    $config = $this->config('tracardi.settings');

    $form['api_url'] = [
      '#type' => 'textfield',
      '#title' => $this->t('API URL'),
      '#description' => $this->t('Base URL of the Tracardi API.'),
      '#default_value' => $config->get('api_url'),
      '#required' => TRUE,
    ];

    $form['settings'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Settings'),
    ];

    $form['fieldset_auth'] = [
      '#type' => 'details',
      '#title' => $this->t('Authentication'),
      '#description' => $this->t('For logging into the Tracardi API using OAuth2.'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'settings',
      'api_username' => [
        '#type' => 'textfield',
        '#title' => $this->t('Username'),
        '#default_value' => $config->get('api_username'),
        '#required' => TRUE,
      ],
      'api_password' => [
        '#type' => 'password',
        '#title' => $this->t('Password'),
        '#default_value' => $config->get('api_password'),
        '#required' => FALSE,
      ],
      'status' => [
        '#markup' => $this->tracardiApi->isConnected() ? $this->t('✓ Connected') : $this->t('✗ Could not connect'),
      ],
    ];

    $form['fieldset_tracking'] = [
      '#type' => 'details',
      '#title' => $this->t('Tracking script'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'settings',
      'enable_script' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Enabled'),
        '#description' => $this->t('Disable when loading via GTM.'),
        '#default_value' => $config->get('enable_script'),
        '#required' => FALSE,
      ],
      'source_id' => [
        '#type' => 'textfield',
        '#title' => $this->t('Source ID'),
        '#description' => $this->t('Can be found under %path in the Tracardi GUI.', ['%path' => '/setup/resources']),
        '#default_value' => $config->get('source_id'),
        '#required' => TRUE,
        '#states' => [
          'invisible' => [
            ':input[name="enable_script"]' => ['checked' => FALSE],
          ],
        ],
      ],
    ];

    $form['fieldset_events'] = [
      '#type' => 'details',
      '#title' => $this->t('Events'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'settings',
      'page_view' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Page view'),
        '#description' => $this->t('Send a %event event when the page finished loading. The payload is fetched from drupalSettings, properties can be added there.', ['%event' => 'page-view']),
        '#default_value' => $config->get('page_view'),
        '#required' => FALSE,
      ],
      'form_submit' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Form submit'),
        '#description' => $this->t('Send a %event event when a form gets submitted. Configure it using form element options or the Tracardi webform handler.', ['%event' => 'form-submit']),
        '#default_value' => $config->get('form_submit'),
        '#required' => FALSE,
      ],
      'updated_cookie' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Updated cookie'),
        '#description' => $this->t('Send a %event event when cookie gets updated. Only for cookies this module writes.', ['%event' => 'updated-cookie']),
        '#default_value' => $config->get('updated_cookie'),
        '#required' => FALSE,
      ],
    ];

    $form['fieldset_preview'] = [
      '#type' => 'details',
      '#title' => $this->t('Preview'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'settings',
      'preview' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Enabled'),
        '#description' => $this->t('Displays the "Preview widget (Tracardi)" block. Make sure you add the block via the <a href="@block_layout">Block lay-out</a> and check <a href="@permissions">permissions</a> for the widget.', ['@block_layout' => '/admin/structure/block', '@permissions' => '/admin/people/permissions#module-tracardi']),
        '#default_value' => $config->get('preview'),
      ],
    ];

    $form['fieldset_ab_testing'] = [
      '#type' => 'details',
      '#title' => $this->t('A/B Testing'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
      '#group' => 'settings',
      'ab_testing' => [
        '#type' => 'checkbox',
        '#title' => $this->t('Enabled'),
        '#description' => $this->t('Sets a non-personalized cookie for a subset of the visitors. It can be used to setup A\B tests.'),
        '#default_value' => $config->get('ab_testing'),
      ],
      'ab_cookie_name' => [
        '#type' => 'textfield',
        '#title' => $this->t('Cookie name'),
        '#default_value' => $config->get('ab_cookie_name'),
        '#states' => [
          'invisible' => [
            ':input[name="ab_testing"]' => ['checked' => FALSE],
          ],
        ],
      ],
      'ab_ratio' => [
        '#type' => 'number',
        '#min' => 1,
        '#max' => 100,
        '#title' => $this->t('Ratio of non-personalized visitors'),
        '#description' => $this->t('Percent'),
        '#default_value' => $config->get('ab_ratio'),
        '#states' => [
          'invisible' => [
            ':input[name="ab_testing"]' => ['checked' => FALSE],
          ],
        ],
      ],
    ];

    $form['plugins'] = [
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Plugins'),
    ] + array_map(static function (PersonalizationInterface $personalization) use ($form, $form_state) {
      return $personalization->buildConfigurationForm($form, $form_state);
    }, $this->personalizationManager->loadPlugins());

    return parent::buildForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state): void {
    $values = $form_state->cleanValues()->getValues();

    /** @var \Drupal\tracardi\PersonalizationInterface $plugin */
    foreach ($this->personalizationManager->loadPlugins() as $plugin) {
      // Save config for each enabled plugin.
      $config = $this->config($plugin->getConfigName());
      $config->setData($values[$plugin->getId()]);
      $config->save();

      // Remove plugin settings from general config.
      unset($values[$plugin->getId()]);
    }

    // Get current config and replace with new.
    $config = $this->config('tracardi.settings');

    // Check if API password remained unchanged.
    $username = $config->get('api_username');

    if ($values['api_password'] === ''
      && isset($username)
      && $values['api_username'] === $config->get('api_username')) {
      $values['api_password'] = $config->get('api_password');
    }

    // Save general config.
    $config->setData($values);
    $config->save();
    $this->messenger()->addMessage(t('Settings saved.'));

    // Clear access token storage.
    $this->accessTokenStorage->clear();
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc