acquia_vwo-1.0.x-dev/modules/acquia_vwo_content/src/Form/AdminSettingsForm.php

modules/acquia_vwo_content/src/Form/AdminSettingsForm.php
<?php

namespace Drupal\acquia_vwo_content\Form;

use Drupal\acquia_vwo_content\Service\Helper\EntityHelper;
use Drupal\acquia_vwo_content\Service\Helper\Util;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\user\RoleInterface;
use Drupal\acquia_vwo_content\Service\Export\ExportQueue;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\CronInterface;
use Drupal\Core\Database\Connection;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Queue\QueueFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Defines a form that configures settings.
 */
class AdminSettingsForm extends ConfigFormBase {
  use StringTranslationTrait;


  /**
   * The config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;


  /**
   * The queue object.
   *
   * @var \Drupal\Core\Queue\QueueFactory
   */
  protected $queueFactory;

  /**
   * The database object.
   *
   * @var \Drupal\Core\Database\Connection
   */
  protected $database;

  /**
   * The CronInterface object.
   *
   * @var \Drupal\Core\CronInterface
   */
  protected $cron;

  /**
   * The Export Queue Service.
   *
   * @var \Drupal\acquia_vwo_content\Service\Export\ExportQueue
   */
  protected $exportQueue;

  /**
   * The module handler service.
   *
   * @var \Drupal\Core\Extension\ModuleHandlerInterface
   */
  protected $moduleHandler;

  /**
   * Constructor.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory service.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   Entity type manager service.
   * @param \Drupal\Core\Queue\QueueFactory $queue_factory
   *   Queue factory service to get new/existing queues for use.
   * @param \Drupal\Core\Database\Connection $database
   *   The database connection to be used.
   * @param \Drupal\Core\CronInterface $cron
   *   The cron service.
   * @param \Drupal\acquia_vwo_content\Service\Export\ExportQueue $export_queue
   *   The Export Queue service.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
   *   The module Handler Service.
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    EntityTypeManagerInterface $entity_type_manager,
    QueueFactory $queue_factory,
    Connection $database,
    CronInterface $cron,
    ExportQueue $export_queue,
    ModuleHandlerInterface $module_handler,
  ) {
    $this->configFactory = $config_factory;
    $this->entityTypeManager = $entity_type_manager;
    $this->queueFactory = $queue_factory;
    $this->database = $database;
    $this->cron = $cron;
    $this->exportQueue = $export_queue;
    $this->moduleHandler = $module_handler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $form = new static(
      $container->get('config.factory'),
      $container->get('entity_type.manager'),
      $container->get('queue'),
      $container->get('database'),
      $container->get('cron'),
      $container->get('acquia_vwo_content.export_queue'),
      $container->get('module_handler'),
    );
    $form->setMessenger($container->get('messenger'));
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'acquia_vwo_content_settings_form';
  }

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return [
      'acquia_vwo_content.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('acquia_vwo_content.settings');
    $api_key = $config->get('api.key');
    $form['vwo_api_key'] = [
      '#type' => 'textfield',
      '#title' => $this->t('VWO API Key'),
      '#description' => $this->t("Please visit <a target='_blank' href='https://app.vwo.com/#/developers/tokens'>https://app.vwo.com/#/developers/tokens</a> to generate an API token"),
      '#required' => TRUE,
      '#default_value' => $api_key,
    ];

    if ($this->moduleHandler->moduleExists('cohesion')) {
      $form['site_studio'] = $this->buildSiteStudioConfigurationForm();
    }

    // $form['export'] = $this->buildExportForm();
    return parent::buildForm($form, $form_state);
  }

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

    $messenger = $this->messenger();
    $triggered_button = $form_state->getTriggeringElement()['#parents'][0];
    if ($triggered_button === 'enqueue_content') {
      $this->exportQueue->rescanContentBulk();
      $messenger->addMessage('All content has been scanned and added to the Queue.');
    }
    elseif ($triggered_button === 'process_queue') {
      $this->exportQueue->exportBulkQueueItems();
      $messenger->addMessage('All content has been exported to VWO from the Queue.');
    }
    elseif ($triggered_button === 'purge_queue') {
      $this->exportQueue->purgeQueue();
      $messenger->addMessage('All content has been purged from the Queue.');
    }
    else {
      $settings = $this->config('acquia_vwo_content.settings');
      $values = $form_state->getValues();
      $settings->set('api.key', $values['vwo_api_key']);
      $settings->save();
      if ($this->moduleHandler->moduleExists('cohesion')) {
        $this->setSiteStudioConfiguration($values['site_studio']);
      }
      parent::submitForm($form, $form_state);

      drupal_flush_all_caches();
    }

  }

  /**
   * Build Site Studio Configuration form.
   *
   * @return array
   *   Site Studio Configuration form.
   */
  private function buildSiteStudioConfigurationForm(): array {
    $config = $this->config(EntityHelper::ENTITY_CONFIG_NAME);
    $entity_config = $config->get('entity_config');
    $enable_vwo = FALSE;
    $export_all = FALSE;
    if ((!empty($entity_config) && isset($entity_config['component_content']['component_content']))) {
      $enable_vwo = TRUE;
      $export_all = $entity_config['component_content']['component_content']['export_all'] ?? FALSE;
    }

    $form = [
      '#type' => 'details',
      '#open' => FALSE,
      '#title' => $this->t('Site Studio Configuration'),
      '#tree' => TRUE,
    ];
    $form['enable_vwo'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Make all Site Studio Component Content entities available to VWO as Custom Widget.'),
      '#default_value' => $enable_vwo,
    ];

    $form['export_all'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Export all Site Studio Component Content entities as VWO custom widgets'),
      '#description' => $this->t('By default, you must choose which entities will be exported to VWO in the entity edit form. If you prefer to always export all Site Studio Component Content entities to VWO, check this box.'),
      '#default_value' => $export_all,
      '#states' => [
        'visible' => [
          ':input[name="site_studio[enable_vwo]"]' => ['checked' => TRUE],
        ],
      ],
    ];

    $form['render_role'] = [
      '#title' => $this->t('Render role'),
      '#description' => $this->t('The role to use when exporting entities to VWO.'),
      '#type' => 'select',
      '#options' => Util::getUserRoleOptions(),
      '#default_value' => $entity_config['component_content']['component_content']['render_role'] ?? RoleInterface::ANONYMOUS_ID,
      '#states' => [
        'visible' => [
          [':input[name="site_studio[enable_vwo]"]' => ['checked' => TRUE]],
        ],
      ],
    ];

    return $form;
  }

  /**
   * Build Export Form.
   *
   * @return array
   *   Returns the build array for the Export Form.
   */
  public function buildExportForm(): array {
    $form['queue'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Export Content'),
      '#collapsible' => TRUE,
      '#collapsed' => FALSE,
    ];
    $queue_count = intval($this->exportQueue->getQueueCount());
    $form['queue']['run_export_queue']['queue-list'] = [
      '#type' => 'item',
      '#title' => $this->t('Number of items ready to Export to VWO as Custom Widget'),
      '#description' => $this->t('%num @items.', [
        '%num' => $queue_count,
        '@items' => $queue_count === 1 ? $this->t('item') : $this->t('items'),
      ]),
    ];

    $form['queue']['enqueue_content'] = [
      '#type' => 'submit',
      '#value' => $this->t('Enqueue Content'),
    ];

    $form['queue']['purge_queue'] = [
      '#type' => 'submit',
      '#value' => $this->t('Purge Queue'),
    ];

    $form['queue']['process_queue'] = [
      '#type' => 'submit',
      '#value' => $this->t('Process Queue'),
    ];

    return $form;
  }

  /**
   * Set Site Studio Configuration.
   *
   * @param array $values
   *   The values to set.
   *
   * @return void
   *   Returns nothing.
   */
  public function setSiteStudioConfiguration(array $values): void {
    $config = $this->configFactory->getEditable(EntityHelper::ENTITY_CONFIG_NAME);
    $entity_config = $config->get('entity_config');

    if ($values['enable_vwo']) {
      Util::updateEntityConfig($entity_config, 'component_content', 'component_content', 'default', $values['render_role'], $values['export_all']);
    }
    else {
      Util::updateEntityConfig($entity_config, 'component_content', 'component_content');
    }
    // Check if view modes exist and disabled in current request.
    $config->set('entity_config', $entity_config);
    $config->save();
  }

}

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

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