You are here

class CommerceCurrencyResolverMapping in Commerce Currency Resolver 8

Class CommerceCurrencyResolverMapping.

@package Drupal\commerce_currency_resolver\Form

Hierarchy

Expanded class hierarchy of CommerceCurrencyResolverMapping

1 string reference to 'CommerceCurrencyResolverMapping'
commerce_currency_resolver.routing.yml in ./commerce_currency_resolver.routing.yml
commerce_currency_resolver.routing.yml

File

src/Form/CommerceCurrencyResolverMapping.php, line 17

Namespace

Drupal\commerce_currency_resolver\Form
View source
class CommerceCurrencyResolverMapping extends ConfigFormBase {

  /**
   * The country manager.
   *
   * @var \Drupal\Core\Locale\CountryManagerInterface
   */
  protected $countryManager;

  /**
   * Helper service.
   *
   * @var \Drupal\commerce_currency_resolver\CurrencyHelperInterface
   */
  protected $currencyHelper;

  /**
   * Constructs a CommerceCurrencyResolverMapping object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The factory for configuration objects.
   * @param \Drupal\Core\Locale\CountryManagerInterface $country_manager
   *   The country manager.
   * @param \Drupal\commerce_currency_resolver\CurrencyHelperInterface $currencyHelper
   *   Currency helper.
   */
  public function __construct(ConfigFactoryInterface $config_factory, CountryManagerInterface $country_manager, CurrencyHelperInterface $currencyHelper) {
    parent::__construct($config_factory);
    $this->countryManager = $country_manager;
    $this->currencyHelper = $currencyHelper;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('config.factory'), $container
      ->get('country_manager'), $container
      ->get('commerce_currency_resolver.currency_helper'));
  }

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

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

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

    // Get type of mapping for the resolver.
    $currency_mapping = $this
      ->config('commerce_currency_resolver.settings')
      ->get('currency_mapping');

    // Get default currency.
    $currency_default = $this
      ->config('commerce_currency_resolver.settings')
      ->get('currency_default');

    // Get current settings.
    $config = $this
      ->config('commerce_currency_resolver.currency_mapping');

    // Get active currencies.
    $active_currencies = $this->currencyHelper
      ->getCurrencies();

    // Get mapped currency.
    $matrix = $config
      ->get('matrix');
    switch ($currency_mapping) {
      case 'lang':
        $languages = $this->currencyHelper
          ->getLanguages();
        $form['matrix'] = [
          '#type' => 'details',
          '#open' => TRUE,
          '#title' => $this
            ->t('Currency matrix'),
          '#tree' => TRUE,
          '#weight' => 50,
        ];
        foreach ($languages as $key => $language) {
          $form['matrix'][$key] = [
            '#type' => 'radios',
            '#options' => $active_currencies,
            '#default_value' => $matrix[$key],
            '#title' => $language,
            '#description' => $this
              ->t('Select currency which should be used with @lang language', [
              '@lang' => $language,
            ]),
          ];
        }
        break;
      case 'geo':
        $domicile_currency = $config
          ->get('domicile_currency');
        $logic = !empty($config
          ->get('logic')) ? $config
          ->get('logic') : 'country';
        $form['domicile_currency'] = [
          '#type' => 'checkbox',
          '#default_value' => $domicile_currency,
          '#title' => $this
            ->t('Use domicile currency per country.'),
          '#description' => $this
            ->t('If domicile currency is enabled for specific country, it will be considered as primary currency. Otherwise currency resolver use default currency defined in settings as fallback.'),
        ];

        // Use mapping per country.
        if (empty($domicile_currency)) {
          $form['logic'] = [
            '#type' => 'select',
            '#default_value' => $logic,
            '#options' => [
              'country' => $this
                ->t('Country'),
              'currency' => $this
                ->t('Currency'),
            ],
            '#title' => $this
              ->t('Matrix logic'),
            '#description' => $this
              ->t('How you want to create matrix. You can assign currency to each country separate, or assign multiple countries to each currency'),
          ];
          $form['matrix'] = [
            '#type' => 'details',
            '#open' => FALSE,
            '#title' => $this
              ->t('Currency matrix'),
            '#tree' => TRUE,
            '#weight' => 50,
          ];

          // Country list. Get country list which is already processed with
          // alters instead of taking static list.
          $countries = $this->countryManager
            ->getList();
          switch ($logic) {
            default:
            case 'country':
              foreach ($countries as $key => $value) {
                $form['matrix'][$key] = [
                  '#type' => 'select',
                  '#options' => $active_currencies,
                  '#title' => $value
                    ->render(),
                  '#description' => $this
                    ->t('Select currency which should be used with @lang language', [
                    '@lang' => $value
                      ->render(),
                  ]),
                  '#default_value' => $matrix[$key] ?? $currency_default,
                ];
              }
              break;
            case 'currency':
              $data = [];

              // Process and reverse existing config from country->currency
              // to currency -> countries list for autocomplete fields.
              if (!empty($matrix)) {
                foreach ($matrix as $country => $currency) {
                  $data[$currency] .= $country;
                }
              }

              // Render autocomplete fields for each currency.
              foreach ($active_currencies as $key => $currency) {
                $form['matrix'][$key] = [
                  '#type' => 'textfield',
                  '#autocomplete_route_name' => 'commerce_currency_resolver.countries.autocomplete',
                  '#title' => $currency,
                  '#description' => $this
                    ->t('Select countires which should be used with @currency currency', [
                    '@currency' => $currency,
                  ]),
                  '#default_value' => isset($data[$key]) ? str_replace(' ', ', ', $data[$key]) : '',
                ];
              }
              break;
          }
        }
        break;
    }
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this
        ->t('Submit'),
      '#weight' => 100,
    ];
    return $form;
  }

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

    // Get matrix logic value.
    $logic = $form_state
      ->getValue('logic');

    // Process results in some cases.
    // We want to have same array in any type of currency matrix.
    if ($logic === 'currency') {
      $raw_data = $form_state
        ->getValue('matrix');
      $matrix = [];
      foreach ($raw_data as $currency => $list) {
        $countries = explode(',', $list);
        foreach ($countries as $country) {
          $matrix[$country] = $currency;
        }
      }
    }
    else {
      $matrix = $form_state
        ->getValue('matrix');
    }

    // Set values.
    $config
      ->set('domicile_currency', $form_state
      ->getValue('domicile_currency'))
      ->set('logic', $logic)
      ->set('matrix', $matrix)
      ->save();
    parent::submitForm($form, $form_state);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
CommerceCurrencyResolverMapping::$countryManager protected property The country manager.
CommerceCurrencyResolverMapping::$currencyHelper protected property Helper service.
CommerceCurrencyResolverMapping::buildForm public function Form constructor. Overrides ConfigFormBase::buildForm
CommerceCurrencyResolverMapping::create public static function Instantiates a new instance of this class. Overrides ConfigFormBase::create
CommerceCurrencyResolverMapping::getEditableConfigNames protected function Gets the configuration names that will be editable. Overrides ConfigFormBaseTrait::getEditableConfigNames
CommerceCurrencyResolverMapping::getFormId public function Returns a unique string identifying the form. Overrides FormInterface::getFormId
CommerceCurrencyResolverMapping::submitForm public function Form submission handler. Overrides ConfigFormBase::submitForm
CommerceCurrencyResolverMapping::__construct public function Constructs a CommerceCurrencyResolverMapping object. Overrides ConfigFormBase::__construct
ConfigFormBaseTrait::config protected function Retrieves a configuration object.
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 1
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::configFactory protected function Gets the config factory for this form. 1
FormBase::container private function Returns the service container.
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route. Overrides UrlGeneratorTrait::redirect
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
FormBase::validateForm public function Form validation handler. Overrides FormInterface::validateForm 62
LinkGeneratorTrait::$linkGenerator protected property The link generator. 1
LinkGeneratorTrait::getLinkGenerator Deprecated protected function Returns the link generator.
LinkGeneratorTrait::l Deprecated protected function Renders a link to a route given a route name and its parameters.
LinkGeneratorTrait::setLinkGenerator Deprecated public function Sets the link generator service.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.
UrlGeneratorTrait::$urlGenerator protected property The url generator.
UrlGeneratorTrait::getUrlGenerator Deprecated protected function Returns the URL generator service.
UrlGeneratorTrait::setUrlGenerator Deprecated public function Sets the URL generator service.
UrlGeneratorTrait::url Deprecated protected function Generates a URL or path for a specific route based on the given parameters.