| 1 |
<?php |
| 2 |
|
| 3 |
namespace Money\Formatter; |
| 4 |
|
| 5 |
use Money\Currencies; |
| 6 |
use Money\Currencies\BitcoinCurrencies; |
| 7 |
use Money\Exception\FormatterException; |
| 8 |
use Money\Money; |
| 9 |
use Money\MoneyFormatter; |
| 10 |
use Money\Number; |
| 11 |
|
| 12 |
/** |
| 13 |
* Formats Money to Bitcoin currency. |
| 14 |
* |
| 15 |
* @author Frederik Bosch <f.bosch@genkgo.nl> |
| 16 |
*/ |
| 17 |
final class BitcoinMoneyFormatter implements MoneyFormatter |
| 18 |
{ |
| 19 |
/** |
| 20 |
* @var int |
| 21 |
*/ |
| 22 |
private $fractionDigits; |
| 23 |
|
| 24 |
/** |
| 25 |
* @var Currencies |
| 26 |
*/ |
| 27 |
private $currencies; |
| 28 |
|
| 29 |
/** |
| 30 |
* @param int $fractionDigits |
| 31 |
*/ |
| 32 |
public function __construct($fractionDigits, Currencies $currencies) |
| 33 |
{ |
| 34 |
$this->fractionDigits = $fractionDigits; |
| 35 |
$this->currencies = $currencies; |
| 36 |
} |
| 37 |
|
| 38 |
/** |
| 39 |
* {@inheritdoc} |
| 40 |
*/ |
| 41 |
public function format(Money $money) |
| 42 |
{ |
| 43 |
if (BitcoinCurrencies::CODE !== $money->getCurrency()->getCode()) { |
| 44 |
throw new FormatterException('Bitcoin Formatter can only format Bitcoin currency'); |
| 45 |
} |
| 46 |
|
| 47 |
$valueBase = $money->getAmount(); |
| 48 |
$negative = false; |
| 49 |
|
| 50 |
if ('-' === $valueBase[0]) { |
| 51 |
$negative = true; |
| 52 |
$valueBase = substr($valueBase, 1); |
| 53 |
} |
| 54 |
|
| 55 |
$subunit = $this->currencies->subunitFor($money->getCurrency()); |
| 56 |
$valueBase = Number::roundMoneyValue($valueBase, $this->fractionDigits, $subunit); |
| 57 |
$valueLength = strlen($valueBase); |
| 58 |
|
| 59 |
if ($valueLength > $subunit) { |
| 60 |
$formatted = substr($valueBase, 0, $valueLength - $subunit); |
| 61 |
|
| 62 |
if ($subunit) { |
| 63 |
$formatted .= '.'; |
| 64 |
$formatted .= substr($valueBase, $valueLength - $subunit); |
| 65 |
} |
| 66 |
} else { |
| 67 |
$formatted = '0.'.str_pad('', $subunit - $valueLength, '0').$valueBase; |
| 68 |
} |
| 69 |
|
| 70 |
if ($this->fractionDigits === 0) { |
| 71 |
$formatted = substr($formatted, 0, strpos($formatted, '.')); |
| 72 |
} elseif ($this->fractionDigits > $subunit) { |
| 73 |
$formatted .= str_pad('', $this->fractionDigits - $subunit, '0'); |
| 74 |
} elseif ($this->fractionDigits < $subunit) { |
| 75 |
$lastDigit = strpos($formatted, '.') + $this->fractionDigits + 1; |
| 76 |
$formatted = substr($formatted, 0, $lastDigit); |
| 77 |
} |
| 78 |
|
| 79 |
$formatted = BitcoinCurrencies::SYMBOL.$formatted; |
| 80 |
|
| 81 |
if (true === $negative) { |
| 82 |
$formatted = '-'.$formatted; |
| 83 |
} |
| 84 |
|
| 85 |
return $formatted; |
| 86 |
} |
| 87 |
} |
| 88 |
|