subscriptions-2.0.x-dev/subscriptions_content/src/Form/ConfigForm.php

subscriptions_content/src/Form/ConfigForm.php
<?php

namespace Drupal\subscriptions_content\Form;

use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use GuzzleHttp\ClientInterface;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;

/**
 * Defines a settings form for the Subscriptions module.
 */
class ConfigForm extends ConfigFormBase {

  /**
   * Node storage service.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected EntityStorageInterface $nodeStorage;

  /**
   * List of node types.
   *
   * @var \Drupal\node\NodeTypeInterface[]
   */
  protected array $nodeTypes;

  /**
   * An http client.
   *
   * @var \GuzzleHttp\ClientInterface
   */
  protected $httpClient;

  /**
   * Logger Factory.
   *
   * @var \Drupal\Core\Logger\LoggerChannelFactoryInterface
   */
  protected $loggerFactory;

  /**
   * {@inheritdoc}
   */
  protected function getEditableConfigNames(): array {
    return ['subscriptions_content.settings'];
  }

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

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('config.factory'),
      $container->get('entity_type.manager'),
      $container->get('http_client'),
      $container->get('logger.factory'),
    );
  }

  /**
   * {@inheritdoc}
   *
   * @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
   * @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
   */
  public function __construct(
    ConfigFactoryInterface $config_factory,
    EntityTypeManagerInterface $entity_type_manager,
    ClientInterface $http_client,
    LoggerChannelFactoryInterface $loggerFactory) {
    parent::__construct($config_factory);

    $this->nodeStorage = $entity_type_manager->getStorage('node');
    $this->nodeTypes = $entity_type_manager->getStorage('node_type')->loadMultiple();
    $this->httpClient = $http_client;
  }

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

    $form['#title'] = $this->t('Content subscriptions');

    $config = $this->config('subscriptions_content.settings');

    $content_type_options = [];
    foreach ($this->nodeTypes as $node_type) {
      $content_type_options[$node_type->id()] = $node_type->label();
    }

    $form['unlisted_content_types'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Unlisted content types'),
      '#description' => $this->t('Select the content types which should be <strong>removed from subscriptions listings</strong>. The content may still be available for subscribing via different kinds of subscriptions, but subscribing by content type will be unavailable for the selected types.'),
      '#options' => $content_type_options,
      '#default_value' => $config->get('unlisted_content_types') ?? [],
    ];

    $form['blocked_content_types'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Blocked content types'),
      '#description' => $this->t('Select the content types which should be <strong>completely unavailable for subscribing</strong>, i.e. content of the selected types will never trigger notifications for regular users.'),
      '#options' => $content_type_options,
      '#default_value' => $config->get('blocked_content_types') ?? [],
    ];

    $form['permissions_note'] = [
      '#type' => 'item',
      '#title' => $this->t('Note'),
      '#description' => $this->t('The <em>subscribe to all content types</em> permission grants normal access to unlisted and blocked content types; this is intended as an administrative function.'),
    ];

    $form['blocked_nodes'] = [
      '#type' => 'entity_autocomplete',
      '#target_type' => 'node',
      '#title' => $this->t('Blocked nodes'),
      '#description' => $this->t('Enter the node title of node(s) that should be <strong>completely unavailable for subscribing</strong>, separated by common and space.'),
      '#tags' => TRUE,
      '#default_value' => $this->nodeStorage->loadMultiple($config->get('blocked_nodes') ?? []),
    ];

    return $form;
  }

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

    // Capture the settings on the local platform.
    $values = $form_state->cleanValues()->getValues();
    $unlisted_content_types = array_filter(array_values($values['unlisted_content_types']));
    $blocked_content_types = array_filter(array_values($values['blocked_content_types']));

    // Save the config settings locally on the current local platform.
    $this->config('subscriptions_content.settings')
      ->set('unlisted_content_types', $unlisted_content_types)
      ->set('blocked_content_types', $blocked_content_types)
      ->set('blocked_nodes', array_column($values['blocked_nodes'], 'target_id'))
      ->save();

    // Sync configuration form settings to the dxp-commenting platform.
    $this->sync_config_form_settings($values);
  }

  /**
   * Sends the subscription configuration form settings to the dxp-commenting-platform.
   *
   * @param array $values
   *   These are the configuration form values that need to be sent and stored
   *   locally on the dxp-commenting platform.
   *
   * @return void
   */
  public function sync_config_form_settings($values) {
    try {
      // Get environment code
      $values['cmdb_code'] = getenv('DROP_CMDB_CODE')  ? getenv('DROP_CMDB_CODE') : 'DCP-001';

      $dxp_commenting_host = getenv('RED_HAT_DXP_COMMENTING_HOST');

      // Send Configuration to API.
      $this->httpClient->request('POST',
        $dxp_commenting_host . 'api/comments/notifications/config',
        [
          'verify' => false,
          'headers' => [
            'Accept' => 'application/json',
            'Content-Type' => 'application/json'
          ],
          'body' => json_encode($values)
        ]
      );
    }
    catch(\Exception $error) {
      $this->loggerFactory->get('subscription_content')->error(
        'Failed to sync subscription content settings with the comment platform.  Failed with %code, error: %error',
        [
          '%code' => $error->getCode(),
          '%error' => $error->getMessage()
        ]
      );
    }
  }

}

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

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