public function AbstractExchangerCalculator::priceConversion in Commerce Exchanger 8
Preform currency conversion for prices.
Parameters
\Drupal\commerce_price\Price $price: Price object.
string $target_currency: Target currency.
Return value
\Drupal\commerce_price\Price Return updated price object with new currency.
Overrides ExchangerCalculatorInterface::priceConversion
File
- src/AbstractExchangerCalculator.php, line 65 
Class
- AbstractExchangerCalculator
- Class AbstractExchangerCalculator.
Namespace
Drupal\commerce_exchangerCode
public function priceConversion(Price $price, string $target_currency) {
  $exchange_rates_config = $this
    ->getExchangerId();
  if (empty($exchange_rates_config)) {
    throw new ExchangeRatesDataMismatchException('Not any active Exchange rates present');
  }
  // Price currency.
  $price_currency = $price
    ->getCurrencyCode();
  // If someone is trying to convert same currency.
  if ($price_currency == $target_currency) {
    return $price;
  }
  $exchange_rates = $this
    ->getExchangeRates();
  // Determine rate.
  $rate = $exchange_rates[$price_currency][$target_currency]['value'] ?? 0;
  // Don't allow multiply with zero or one.
  if (empty($rate)) {
    throw new ExchangeRatesDataMismatchException('There are no exchange rates set for ' . $price_currency . ' and ' . $target_currency);
  }
  // Convert amount to target currency.
  $price = $price
    ->convert($target_currency, (string) $rate);
  $price = $this->rounder
    ->round($price);
  return $price;
}