You are here

protected function ExchangerProviderRemoteBase::recalculateRates in Commerce Exchanger 8

Recalculate currencies from exchange rate between two other currencies.

Parameters

string $target_currency: Currency to which should be exchange rate calculated.

\Drupal\commerce_exchanger\ExchangerProviderRates $data: Currency and rate array.

Return value

\Drupal\commerce_exchanger\ExchangerProviderRates Return recalculated data.

1 call to ExchangerProviderRemoteBase::recalculateRates()
ExchangerProviderRemoteBase::crossSyncCalculate in src/Plugin/Commerce/ExchangerProvider/ExchangerProviderRemoteBase.php
Rates calculation for currencies when we use cross sync conversion.

File

src/Plugin/Commerce/ExchangerProvider/ExchangerProviderRemoteBase.php, line 227

Class

ExchangerProviderRemoteBase
Base class for Commerce exchanger provider plugins.

Namespace

Drupal\commerce_exchanger\Plugin\Commerce\ExchangerProvider

Code

protected function recalculateRates(string $target_currency, ExchangerProviderRates $data) {
  $rates = $data
    ->getRates();
  $base_currency = $data
    ->getBaseCurrency();

  // If we accidentally sent same target and base currency.
  $rate_target_currency = $rates[$target_currency] ?? 1;

  // Get rate based from base currency.
  $currency_default = round(1 / $rate_target_currency, 6);
  $recalculated = [];
  $recalculated[$base_currency] = $currency_default;

  // Recalculate all data.
  foreach ($rates as $currency => $rate) {
    if ($currency !== $target_currency) {
      $recalculated[$currency] = round($rate * $currency_default, 6);
    }
  }
  return new ExchangerProviderRates([
    'base' => $target_currency,
    'rates' => $recalculated,
  ]);
}