RVRNEXT-6 add ExchangeRateCalculator
This commit is contained in:
parent
67114211ec
commit
c7c2df89c5
52
src/Finance/ExchangeRateCalculator.php
Normal file
52
src/Finance/ExchangeRateCalculator.php
Normal 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;
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user