RVRNEXT-6 add ExchangeRateCalculator

This commit is contained in:
Bence Pőcze 2023-05-01 19:23:19 +02:00
parent 67114211ec
commit c7c2df89c5
Signed by: bence
GPG Key ID: DC5BD6E95A333E6D

View File

@ -0,0 +1,52 @@
<?php namespace RVR\Finance;
use DateTime;
use RVR\PersistentData\Model\Currency;
use RVR\PersistentData\Model\CurrencyExchangeRate;
use RVR\Repository\CurrencyExchangeRateRepository;
class ExchangeRateCalculator
{
private Currency $mainCurrency;
private CurrencyExchangeRateRepository $currencyExchangeRateRepository;
private array $exchangeRates = [];
public function __construct(Currency $mainCurrency)
{
$this->mainCurrency = $mainCurrency;
$this->currencyExchangeRateRepository = new CurrencyExchangeRateRepository();
}
public function calculate(float $sumInCurrency, Currency $currency, DateTime $time): float
{
if ($currency->getId() === $this->mainCurrency->getId()) {
return $sumInCurrency;
}
$currentExchangeRate = $this->getCurrentExchangeRate($currency, $time);
if ($currentExchangeRate === null) {
return 0.0;
}
return $sumInCurrency * $currentExchangeRate->getExchangeRate();
}
private function getCurrentExchangeRate(Currency $currency, DateTime $time): ?CurrencyExchangeRate
{
if (!isset($this->exchangeRates[$currency->getId()])) {
$this->exchangeRates[$currency->getId()] = iterator_to_array($this->currencyExchangeRateRepository->getAllByCurrency($currency));
}
$currentExchangeRate = null;
foreach ($this->exchangeRates[$currency->getId()] as $exchangeRate) {
if ($exchangeRate->getValidFrom() > $time) {
break;
}
$currentExchangeRate = $exchangeRate;
}
return $currentExchangeRate;
}
}