PluginProbe
GiveWP – Donation Plugin and Fundraising Platform / 3.19.2
GiveWP – Donation Plugin and Fundraising Platform v3.19.2
4.16.8 4.16.7.2 4.16.7.1 4.16.7 4.16.6.1 4.16.6 4.16.5.1 4.16.5 4.16.4 4.16.3 4.16.2 4.16.1 4.16.0 4.15.5 4.15.4 4.15.3 4.15.2 4.15.1 4.15.0 2.3.0 2.3.1 2.3.2 2.30.0 2.31.0 2.31.1 All 253 releases
give / vendor / moneyphp / money / src / Formatter / BitcoinMoneyFormatter.php
BitcoinMoneyFormatter.php
89 lines 2.4 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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 * @param Currencies $currencies
32 */
33 public function __construct($fractionDigits, Currencies $currencies)
34 {
35 $this->fractionDigits = $fractionDigits;
36 $this->currencies = $currencies;
37 }
38
39 /**
40 * {@inheritdoc}
41 */
42 public function format(Money $money)
43 {
44 if (BitcoinCurrencies::CODE !== $money->getCurrency()->getCode()) {
45 throw new FormatterException('Bitcoin Formatter can only format Bitcoin currency');
46 }
47
48 $valueBase = $money->getAmount();
49 $negative = false;
50
51 if ('-' === $valueBase[0]) {
52 $negative = true;
53 $valueBase = substr($valueBase, 1);
54 }
55
56 $subunit = $this->currencies->subunitFor($money->getCurrency());
57 $valueBase = Number::roundMoneyValue($valueBase, $this->fractionDigits, $subunit);
58 $valueLength = strlen($valueBase);
59
60 if ($valueLength > $subunit) {
61 $formatted = substr($valueBase, 0, $valueLength - $subunit);
62
63 if ($subunit) {
64 $formatted .= '.';
65 $formatted .= substr($valueBase, $valueLength - $subunit);
66 }
67 } else {
68 $formatted = '0.'.str_pad('', $subunit - $valueLength, '0').$valueBase;
69 }
70
71 if ($this->fractionDigits === 0) {
72 $formatted = substr($formatted, 0, strpos($formatted, '.'));
73 } elseif ($this->fractionDigits > $subunit) {
74 $formatted .= str_pad('', $this->fractionDigits - $subunit, '0');
75 } elseif ($this->fractionDigits < $subunit) {
76 $lastDigit = strpos($formatted, '.') + $this->fractionDigits + 1;
77 $formatted = substr($formatted, 0, $lastDigit);
78 }
79
80 $formatted = BitcoinCurrencies::SYMBOL.$formatted;
81
82 if (true === $negative) {
83 $formatted = '-'.$formatted;
84 }
85
86 return $formatted;
87 }
88 }
89