AggregateMoneyFormatter.php
4 years ago
BitcoinMoneyFormatter.php
4 years ago
DecimalMoneyFormatter.php
4 years ago
IntlLocalizedDecimalFormatter.php
4 years ago
IntlMoneyFormatter.php
4 years ago
IntlLocalizedDecimalFormatter.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Money\Formatter; |
| 4 | |
| 5 | use Money\Currencies; |
| 6 | use Money\Money; |
| 7 | use Money\MoneyFormatter; |
| 8 | |
| 9 | /** |
| 10 | * Formats a Money object using intl extension. |
| 11 | * |
| 12 | * @author Frederik Bosch <f.bosch@genkgo.nl> |
| 13 | */ |
| 14 | final class IntlLocalizedDecimalFormatter implements MoneyFormatter |
| 15 | { |
| 16 | /** |
| 17 | * @var \NumberFormatter |
| 18 | */ |
| 19 | private $formatter; |
| 20 | |
| 21 | /** |
| 22 | * @var Currencies |
| 23 | */ |
| 24 | private $currencies; |
| 25 | |
| 26 | /** |
| 27 | * @param \NumberFormatter $formatter |
| 28 | * @param Currencies $currencies |
| 29 | */ |
| 30 | public function __construct(\NumberFormatter $formatter, Currencies $currencies) |
| 31 | { |
| 32 | $this->formatter = $formatter; |
| 33 | $this->currencies = $currencies; |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * {@inheritdoc} |
| 38 | */ |
| 39 | public function format(Money $money) |
| 40 | { |
| 41 | $valueBase = $money->getAmount(); |
| 42 | $negative = false; |
| 43 | |
| 44 | if ($valueBase[0] === '-') { |
| 45 | $negative = true; |
| 46 | $valueBase = substr($valueBase, 1); |
| 47 | } |
| 48 | |
| 49 | $subunit = $this->currencies->subunitFor($money->getCurrency()); |
| 50 | $valueLength = strlen($valueBase); |
| 51 | |
| 52 | if ($valueLength > $subunit) { |
| 53 | $formatted = substr($valueBase, 0, $valueLength - $subunit); |
| 54 | $decimalDigits = substr($valueBase, $valueLength - $subunit); |
| 55 | |
| 56 | if (strlen($decimalDigits) > 0) { |
| 57 | $formatted .= '.'.$decimalDigits; |
| 58 | } |
| 59 | } else { |
| 60 | $formatted = '0.'.str_pad('', $subunit - $valueLength, '0').$valueBase; |
| 61 | } |
| 62 | |
| 63 | if ($negative === true) { |
| 64 | $formatted = '-'.$formatted; |
| 65 | } |
| 66 | |
| 67 | return $this->formatter->format($formatted); |
| 68 | } |
| 69 | } |
| 70 |