AbstractExchangerCalculator.php in Commerce Exchanger 8
File
src/AbstractExchangerCalculator.php
View source
<?php
namespace Drupal\commerce_exchanger;
use Drupal\commerce_exchanger\Exception\ExchangeRatesDataMismatchException;
use Drupal\commerce_price\Price;
use Drupal\commerce_price\RounderInterface;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
abstract class AbstractExchangerCalculator implements ExchangerCalculatorInterface {
protected $entityTypeManager;
protected $providers;
protected $configFactory;
protected $rounder;
public function __construct(EntityTypeManagerInterface $entity_type_manager, ConfigFactory $config_factory, RounderInterface $rounder) {
$this->configFactory = $config_factory;
$this->providers = $entity_type_manager
->getStorage('commerce_exchange_rates')
->loadMultiple();
$this->rounder = $rounder;
}
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
->getCurrencyCode();
if ($price_currency == $target_currency) {
return $price;
}
$exchange_rates = $this
->getExchangeRates();
$rate = $exchange_rates[$price_currency][$target_currency]['value'] ?? 0;
if (empty($rate)) {
throw new ExchangeRatesDataMismatchException('There are no exchange rates set for ' . $price_currency . ' and ' . $target_currency);
}
$price = $price
->convert($target_currency, (string) $rate);
$price = $this->rounder
->round($price);
return $price;
}
public function getExchangeRates() {
return $this->configFactory
->get($this
->getExchangerId())
->get('rates') ?? [];
}
}