|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Jarobe\HistoricalMoney; |
|
4
|
|
|
|
|
5
|
|
|
use Money\Currencies; |
|
6
|
|
|
use Money\Currency; |
|
7
|
|
|
use Money\Money; |
|
8
|
|
|
|
|
9
|
|
|
/** |
|
10
|
|
|
* Provides a way to convert Money to Money in another Currency using a historical exchange rate. |
|
11
|
|
|
*/ |
|
12
|
|
|
final class HistoricalConverter |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var Currencies |
|
16
|
|
|
*/ |
|
17
|
|
|
private $currencies; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var HistoricalExchange |
|
21
|
|
|
*/ |
|
22
|
|
|
private $exchange; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @param Currencies $currencies |
|
26
|
|
|
* @param HistoricalExchange $exchange |
|
27
|
|
|
*/ |
|
28
|
|
|
public function __construct(Currencies $currencies, HistoricalExchange $exchange) |
|
29
|
|
|
{ |
|
30
|
|
|
$this->currencies = $currencies; |
|
31
|
|
|
$this->exchange = $exchange; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
/** |
|
35
|
|
|
* @param \DateTimeInterface $dateTime |
|
36
|
|
|
* @param Money $money |
|
37
|
|
|
* @param Currency $counterCurrency |
|
38
|
|
|
* @param int $roundingMode |
|
39
|
|
|
* |
|
40
|
|
|
* @return Money |
|
41
|
|
|
*/ |
|
42
|
|
|
public function convertHistorical( |
|
43
|
|
|
\DateTimeInterface $dateTime, |
|
44
|
|
|
Money $money, |
|
45
|
|
|
Currency $counterCurrency, |
|
46
|
|
|
$roundingMode = Money::ROUND_HALF_UP |
|
47
|
|
|
) { |
|
48
|
|
|
$baseCurrency = $money->getCurrency(); |
|
49
|
|
|
$ratio = $this->exchange->quoteHistorical($dateTime, $baseCurrency, $counterCurrency)->getConversionRatio(); |
|
50
|
|
|
|
|
51
|
|
|
$baseCurrencySubunit = $this->currencies->subunitFor($baseCurrency); |
|
52
|
|
|
$counterCurrencySubunit = $this->currencies->subunitFor($counterCurrency); |
|
53
|
|
|
$subunitDifference = $baseCurrencySubunit - $counterCurrencySubunit; |
|
54
|
|
|
|
|
55
|
|
|
$ratio = $ratio / pow(10, $subunitDifference); |
|
56
|
|
|
|
|
57
|
|
|
$counterValue = $money->multiply($ratio, $roundingMode); |
|
58
|
|
|
|
|
59
|
|
|
return new Money($counterValue->getAmount(), $counterCurrency); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|