Calculator
4 years ago
Currencies
4 years ago
Exception
4 years ago
Exchange
4 years ago
Formatter
4 years ago
PHPUnit
4 years ago
Parser
4 years ago
Calculator.php
4 years ago
Converter.php
4 years ago
Currencies.php
4 years ago
Currency.php
4 years ago
CurrencyPair.php
4 years ago
Exception.php
4 years ago
Exchange.php
4 years ago
Money.php
4 years ago
MoneyFactory.php
4 years ago
MoneyFormatter.php
4 years ago
MoneyParser.php
4 years ago
Number.php
4 years ago
Converter.php
55 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Money; |
| 4 | |
| 5 | /** |
| 6 | * Provides a way to convert Money to Money in another Currency using an exchange rate. |
| 7 | * |
| 8 | * @author Frederik Bosch <f.bosch@genkgo.nl> |
| 9 | */ |
| 10 | final class Converter |
| 11 | { |
| 12 | /** |
| 13 | * @var Currencies |
| 14 | */ |
| 15 | private $currencies; |
| 16 | |
| 17 | /** |
| 18 | * @var Exchange |
| 19 | */ |
| 20 | private $exchange; |
| 21 | |
| 22 | /** |
| 23 | * @param Currencies $currencies |
| 24 | * @param Exchange $exchange |
| 25 | */ |
| 26 | public function __construct(Currencies $currencies, Exchange $exchange) |
| 27 | { |
| 28 | $this->currencies = $currencies; |
| 29 | $this->exchange = $exchange; |
| 30 | } |
| 31 | |
| 32 | /** |
| 33 | * @param Money $money |
| 34 | * @param Currency $counterCurrency |
| 35 | * @param int $roundingMode |
| 36 | * |
| 37 | * @return Money |
| 38 | */ |
| 39 | public function convert(Money $money, Currency $counterCurrency, $roundingMode = Money::ROUND_HALF_UP) |
| 40 | { |
| 41 | $baseCurrency = $money->getCurrency(); |
| 42 | $ratio = $this->exchange->quote($baseCurrency, $counterCurrency)->getConversionRatio(); |
| 43 | |
| 44 | $baseCurrencySubunit = $this->currencies->subunitFor($baseCurrency); |
| 45 | $counterCurrencySubunit = $this->currencies->subunitFor($counterCurrency); |
| 46 | $subunitDifference = $baseCurrencySubunit - $counterCurrencySubunit; |
| 47 | |
| 48 | $ratio = (string) Number::fromFloat($ratio)->base10($subunitDifference); |
| 49 | |
| 50 | $counterValue = $money->multiply($ratio, $roundingMode); |
| 51 | |
| 52 | return new Money($counterValue->getAmount(), $counterCurrency); |
| 53 | } |
| 54 | } |
| 55 |