cc-1.0.x-dev/modules/cc_cex/src/Form/ExchangeSettingsForm.php

modules/cc_cex/src/Form/ExchangeSettingsForm.php
<?php

namespace Drupal\cc_cex\Form;

use Drupal\Core\Form\ConfigFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\taxonomy\TermStorageInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\cc_cex\Service\CcxtService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * Configure exchange settings.
 */
class ExchangeSettingsForm extends ConfigFormBase {

  /**
   * The term storage.
   *
   * @var \Drupal\taxonomy\TermStorageInterface
   */
  protected $termStorage;

  /**
   * The CCXT service.
   *
   * @var \Drupal\cc_cex\Service\CcxtService
   */
  protected $ccxtService;

  /**
   * Constructs a new ExchangeSettingsForm object.
   */
  public function __construct(
    EntityTypeManagerInterface $entity_type_manager,
    CcxtService $ccxt_service
  ) {
    $this->termStorage = $entity_type_manager->getStorage('taxonomy_term');
    $this->ccxtService = $ccxt_service;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
      $container->get('cc_cex.ccxt_service')
    );
  }

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

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

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $config = $this->config('cc.settings');
    
    // Get current values
    $enabled_exchanges = $config->get('enabled_exchanges') ?: '';
    $currencies = $config->get('currencies') ?: [];
    $accepted_currencies = $currencies['accepted'] ?? [];
    $needed_currencies = $currencies['needed'] ?? [];

    // Get available exchanges from CCXT
    $available_exchanges = $this->ccxtService->getAvailableExchanges();
    
    $form['enabled_exchanges'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Enabled Exchanges'),
      '#description' => $this->t('Start typing to search for exchanges (e.g., binance, kraken).'),
      '#default_value' => $enabled_exchanges,
      '#required' => TRUE,
      '#autocomplete_route_name' => 'cc_cex.exchange_autocomplete',
      '#autocomplete_route_parameters' => [],
    ];

    // Get terms from the 'currency' vocabulary
    $currency_terms = $this->termStorage->loadTree('currency');
    $currency_options = [];
    foreach ($currency_terms as $term) {
      $currency_options[$term->tid] = $term->name;
    }
    
    $form['currencies'] = [
      '#type' => 'fieldset',
      '#title' => $this->t('Currency Settings'),
    ];

    $form['currencies']['accepted'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Accepted Currencies'),
      '#description' => $this->t('Select the currencies you want to accept.'),
      '#options' => $currency_options,
      '#default_value' => array_map(function($currency) use ($currency_options) {
        return array_search($currency, $currency_options);
      }, $accepted_currencies),
      '#parents' => ['accepted'],
    ];

    $form['currencies']['needed'] = [
      '#type' => 'checkboxes',
      '#title' => $this->t('Needed Currencies'),
      '#description' => $this->t('Select the currencies you will want to swap to.'),
      '#options' => $currency_options,
      '#default_value' => array_map(function($currency) use ($currency_options) {
        return array_search($currency, $currency_options);
      }, $needed_currencies),
      '#parents' => ['needed'],
    ];

    $form['market_pairs_info'] = [
      '#type' => 'markup',
      '#markup' => '<p>' . $this->t('After enabling exchanges and selecting currencies, visit the <a href="@pairs_url">Market Pairs</a> page to refresh the list of available trading pairs.', [
        '@pairs_url' => Url::fromRoute('cc_cex.market_pairs')->toString(),
      ]) . '</p>' .
      '<p>' . $this->t('To configure API keys for private operations like viewing balances, visit the <a href="@keys_url">API Keys</a> page.', [
        '@keys_url' => Url::fromRoute('cc_cex.exchange_api_keys')->toString(),
      ]) . '</p>',
    ];

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

  /**
   * Exchange autocomplete callback.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   *
   * @return \Symfony\Component\HttpFoundation\JsonResponse
   *   A JSON response containing matching exchanges.
   */
  public function exchangeAutocomplete(Request $request) {
    $string = $request->query->get('q');
    $matches = [];
    
    if ($string) {
      $available_exchanges = $this->ccxtService->getAvailableExchanges();
      $matches = array_filter($available_exchanges, function($exchange) use ($string) {
        return stripos($exchange, $string) !== FALSE;
      });
      
      $matches = array_map(function($exchange) {
        return [
          'value' => $exchange,
          'label' => $exchange,
        ];
      }, array_slice($matches, 0, 10));
    }
    
    return new JsonResponse($matches);
  }

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

    // Get enabled exchanges
    $enabled_exchanges = $form_state->getValue('enabled_exchanges', '');
    if (!empty($enabled_exchanges)) {
      $enabled_exchanges = array_filter(explode(',', $enabled_exchanges));
    }

    // Validate that at least one exchange is enabled
    if (empty($enabled_exchanges)) {
      $form_state->setError(
        $form['enabled_exchanges'],
        $this->t('You must enable at least one exchange.')
      );
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $config = $this->configFactory->getEditable('cc.settings');

    // Save enabled exchanges
    $enabled_exchanges = $form_state->getValue('enabled_exchanges', '');
    $config->set('enabled_exchanges', !empty($enabled_exchanges) ? $enabled_exchanges : '');

    // Get currency terms
    $currency_terms = [];
    $terms = $this->termStorage->loadTree('currency');
    foreach ($terms as $term) {
      $currency_terms[$term->tid] = $term->name;
    }

    // Save accepted currencies
    $accepted = array_filter($form_state->getValue('accepted', []));
    $accepted_currencies = array_map(function($tid) use ($currency_terms) {
      return $currency_terms[$tid];
    }, array_keys($accepted));

    // Save needed currencies
    $needed = array_filter($form_state->getValue('needed', []));
    $needed_currencies = array_map(function($tid) use ($currency_terms) {
      return $currency_terms[$tid];
    }, array_keys($needed));

    // Save currencies
    $config->set('currencies', [
      'accepted' => $accepted_currencies,
      'needed' => $needed_currencies,
    ]);

    $config->save();
    parent::submitForm($form, $form_state);
  }
}

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

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