CommerceCurrencyResolverAmountTrait.php in Commerce Currency Resolver 8
File
src/Plugin/Commerce/CommerceCurrencyResolverAmountTrait.php
View source
<?php
namespace Drupal\commerce_currency_resolver\Plugin\Commerce;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_price\Price;
trait CommerceCurrencyResolverAmountTrait {
public function currentCurrency() {
return \Drupal::service('commerce_currency_resolver.current_currency')
->getCurrency();
}
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
$defaultCurrency = \Drupal::service('commerce_currency_resolver.currency_helper')
->fallbackCurrencyCode();
if (isset($form['amount']) && empty($form['amount']['#default_value'])) {
$form['amount']['#default_value'] = [
'number' => '',
'currency_code' => $defaultCurrency,
];
}
$form['fields'] = [
'#type' => 'details',
'#open' => FALSE,
'#description' => $this
->t('If you leave amounts per currency empty, they should be auto-calculated to avoid mismatch in currency on orders.'),
'#title' => $this
->t('Amount per currency'),
'#tree' => TRUE,
];
$enabledCurrencies = \Drupal::service('commerce_currency_resolver.currency_helper')
->getCurrencies();
foreach ($enabledCurrencies as $key => $currency) {
$amount_key = $this->configuration['fields'][$key] ?? NULL;
if (isset($amount_key) && !isset($amount_key['number'], $amount_key['currency_code'])) {
$amount_key = NULL;
}
$form['fields'][$key] = [
'#type' => 'commerce_price',
'#title' => $this
->t('Amount'),
'#default_value' => $amount_key,
'#required' => FALSE,
'#available_currencies' => [
$key,
],
];
}
return $form;
}
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
if (!$form_state
->getErrors()) {
$values = $form_state
->getValue($form['#parents']);
$this->configuration['fields'] = $values['fields'];
}
}
public function getPrice(Price $input_price) {
$target_currency = $this
->currentCurrency();
if (isset($this->configuration['fields'][$target_currency])) {
$priceField = $this->configuration['fields'][$target_currency];
if (!empty($priceField['number'])) {
return new Price($priceField['number'], $priceField['currency_code']);
}
}
return \Drupal::service('commerce_currency_resolver.calculator')
->priceConversion($input_price, $target_currency);
}
public function shouldCurrencyRefresh($currency_code) {
if (PHP_SAPI === 'cli') {
return FALSE;
}
return $this
->currentCurrency() !== $currency_code;
}
}