yandex_smartcaptcha-1.0.2/src/Form/YandexSmartCaptchaAttachedForms.php

src/Form/YandexSmartCaptchaAttachedForms.php
<?php

namespace Drupal\yandex_smartcaptcha\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\Config\StorageInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ExtensionPathResolver;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\yandex_smartcaptcha\YandexSmartCaptcha;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * The class implements attaching the Yandex SmartCaptcha validation to forms.
 */
class YandexSmartCaptchaAttachedForms extends ConfigFormBase implements ContainerInjectionInterface {

  use StringTranslationTrait;

  /**
   * The Yandex SmartCaptcha object.
   *
   * @var \Drupal\yandex_smartcaptcha\YandexSmartCaptcha
   */
  protected $smartCaptcha;

  /**
   * Extension path resolver.
   *
   * @var \Drupal\Core\Extension\ExtensionPathResolver
   */
  protected ExtensionPathResolver $extensionPathResolver;

  /**
   * The active configuration storage.
   *
   * @var \Drupal\Core\Config\StorageInterface
   */
  protected $activeStorage;

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

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

  /**
   * Constructs an UpdateSettingsForm object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\yandex_smartcaptcha\YandexSmartCaptcha $smartCaptcha
   *   The Yandex SmartCaptcha service object.
   * @param \Drupal\Core\Extension\ExtensionPathResolver $extensionPathResolver
   *   Extension path resolver.
   * @param \Drupal\Core\Config\StorageInterface $activeStorage
   *   The active configuration storage.
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entityTypeManager
   *   The entity type manager.
   * @param \Drupal\Core\Extension\ModuleHandlerInterface $moduleHandler
   *   The module handler service.
   */
  public function __construct(ConfigFactoryInterface $config_factory,
  YandexSmartCaptcha $smartCaptcha,
  ExtensionPathResolver $extensionPathResolver,
  StorageInterface $activeStorage,
  EntityTypeManagerInterface $entityTypeManager,
  ModuleHandlerInterface $moduleHandler) {
    parent::__construct($config_factory);
    $this->smartCaptcha = $smartCaptcha;
    $this->extensionPathResolver = $extensionPathResolver;
    $this->activeStorage = $activeStorage;
    $this->entityTypeManager = $entityTypeManager;
    $this->moduleHandler = $moduleHandler;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('yandex_smartcaptcha.service'),
      $container->get('extension.path.resolver'),
      $container->get('config.storage'),
      $container->get('entity_type.manager'),
      $container->get('module_handler'),
    );
  }

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

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames() {
    return ['yandex_smartcaptcha.attached_forms'];
  }

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

    $form['add_new'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Attach captcha to new form'),
      '#open' => TRUE,
      '#attributes' => [
        'class' => ['container-inline'],
      ],
    ];
    $form['add_new']['attached_form_id'] = [
      '#type' => 'textfield',
      '#default_value' => '',
      '#placeholder' => $this->t('Enter the form_id'),
    ];
    $form['add_new']['add'] = [
      '#type' => 'submit',
      '#value' => $this->t('Add'),
      '#submit' => ['::add'],
    ];

    // Display list of Contact form_id.
    if ($this->moduleHandler->moduleExists('contact')) {
      $contact_forms = $this->entityTypeManager->getStorage('contact_form')->loadMultiple();
      $items = array_keys($contact_forms);
      array_walk($items, function (&$value) {
        $value = new TranslatableMarkup("<a href='javascript:void(0);' onclick='document.getElementById(\"edit-attached-form-id\").value = this.innerText;'>contact_message_@form_id_form</a>",
          ['@form_id' => $value]);
      });
      $form['add_new']['contact_forms'] = [
        '#title' => $this->t('Attach Contact forms'),
        '#type' => 'details',
        '#open' => FALSE,
      ];
      $form['add_new']['contact_forms']['items'] = [
        '#theme' => 'item_list',
        '#items' => $items,
      ];
    }

    foreach ($this->smartCaptcha->getAttachedFormsIds() as $form_attach_id => $form_attach_settings) {
      $form[$form_attach_id] = [
        '#title' => $form_attach_id,
        '#type' => 'details',
        '#open' => FALSE,
        '#tree' => TRUE,
      ];

      $form[$form_attach_id]['enabled'] = [
        '#type' => 'checkbox',
        '#title' => $this->t('Enabled'),
        '#default_value' => $form_attach_settings['enabled'] ?? FALSE,
      ];

      // Add constraint settings fields.
      $form[$form_attach_id] += $this->getCaptchaElForm($form_attach_settings);

      $form[$form_attach_id]['remove'] = [
        '#type' => 'submit',
        '#name' => 'remove_' . $form_attach_id,
        '#remove_key' => $form_attach_id,
        '#value' => $this->t('Remove'),
        '#limit_validation_errors' => [],
        '#submit' => ['::remove'],
        '#button_type' => 'danger',
      ];
    }

    // Collapsible details.
    $form['#attached']['library'][] = 'core/drupal.collapse';
    $form = parent::buildForm($form, $form_state);

    $form['actions']['reset'] = [
      '#type' => 'submit',
      '#value' => $this->t('Reset configuration'),
      '#name' => 'reset',
      '#submit' => ['::reset'],
      '#button_type' => 'danger',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function getCaptchaElForm(array $settings = []) {
    $form = [];
    $form['invisible'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable invisible mode'),
      '#default_value' => $settings['invisible'] ?? NULL,
      '#description' => $this->t('Enable invisible mode of Yandex SmartCaptcha'),
    ];

    $form['test'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable test mode'),
      '#default_value' => $settings['test'] ?? NULL,
      '#description' => $this->t('Enable test mode of Yandex SmartCaptcha'),
    ];

    $form['button_hide_mode'] = [
      '#type' => 'select',
      '#title' => $this->t('Submit button hide mode'),
      '#description' => $this->t('Choose the type of submit button hiding.'),
      '#options' => ['hide' => $this->t('Hide'), 'disable' => $this->t('Disable')],
      '#default_value' => $settings['button_hide_mode'] ?? 'hide',
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $values = $form_state->getValues();
    $config = $this->configFactory->getEditable('yandex_smartcaptcha.attached_forms');
    foreach ($this->smartCaptcha->getAttachedFormsIds() as $attached_form_id => $form_settings) {
      $new_settings = array_intersect_key($values[$attached_form_id], $form_settings);
      $config->set($attached_form_id, $new_settings);
    }
    $config->save();

    parent::submitForm($form, $form_state);
  }

  /**
   * {@inheritdoc}
   */
  public function reset(array &$form, FormStateInterface $form_state) {
    // Or, import YAML config from an arbitrary file.
    $config_path = $this->extensionPathResolver->getPath('module', 'yandex_smartcaptcha') . '/config/install';
    $source = new FileStorage($config_path, StorageInterface::DEFAULT_COLLECTION);
    $file_name = 'yandex_smartcaptcha.attached_forms';
    $this->activeStorage->write($file_name, $source->read($file_name));
  }

  /**
   * {@inheritdoc}
   */
  public function add(array &$form, FormStateInterface $form_state) {
    $attached_form_id = $form_state->getValue('attached_form_id');
    $config = $this->configFactory->getEditable('yandex_smartcaptcha.attached_forms');

    $keys = array_merge(['enabled'], array_keys($this->getCaptchaElForm()));
    $default_values = array_fill_keys($keys, FALSE);
    $config->set($attached_form_id, $default_values)->save();
  }

  /**
   * {@inheritdoc}
   */
  public function remove(array &$form, FormStateInterface $form_state) {
    $attached_form_id = $form_state->getTriggeringElement()['#remove_key'];
    $config = $this->configFactory->getEditable('yandex_smartcaptcha.attached_forms');
    $config->clear($attached_form_id)->save();
  }

}

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

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