1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
/** |
3
|
|
|
* This file is part of the ngutech/bitcoin-interop project. |
4
|
|
|
* |
5
|
|
|
* For the full copyright and license information, please view the LICENSE |
6
|
|
|
* file that was distributed with this source code. |
7
|
|
|
*/ |
8
|
|
|
|
9
|
|
|
namespace NGUtech\Bitcoin\Service; |
10
|
|
|
|
11
|
|
|
use Money\Currencies; |
12
|
|
|
use Money\Exception\FormatterException; |
13
|
|
|
use Money\Money; |
14
|
|
|
use Money\MoneyFormatter; |
15
|
|
|
|
16
|
|
|
final class BitcoinMoneyFormatter implements MoneyFormatter |
17
|
|
|
{ |
18
|
|
|
private Currencies $currencies; |
19
|
|
|
|
20
|
|
|
public function __construct(Currencies $currencies) |
21
|
|
|
{ |
22
|
|
|
$this->currencies = $currencies; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
public function format(Money $money): string |
26
|
|
|
{ |
27
|
|
|
$currency = $money->getCurrency(); |
28
|
|
|
if (!$this->currencies->contains($currency)) { |
29
|
|
|
throw new FormatterException('Bitcoin formatter can only format Bitcoin currencies.'); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
$valueBase = $money->getAmount(); |
33
|
|
|
$negative = false; |
34
|
|
|
|
35
|
|
|
if ('-' === $valueBase[0]) { |
36
|
|
|
$negative = true; |
37
|
|
|
$valueBase = substr($valueBase, 1); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$subunit = $this->currencies->subunitFor($currency); |
41
|
|
|
$valueLength = strlen($valueBase); |
42
|
|
|
|
43
|
|
|
if ($valueLength > $subunit) { |
44
|
|
|
$formatted = substr($valueBase, 0, $valueLength - $subunit); |
45
|
|
|
if ($subunit) { |
46
|
|
|
$formatted .= '.'; |
47
|
|
|
$formatted .= substr($valueBase, $valueLength - $subunit); |
48
|
|
|
} |
49
|
|
|
} else { |
50
|
|
|
$formatted = '0.'.str_pad('', $subunit - $valueLength, '0').$valueBase; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$formatted = BitcoinCurrencies::SYMBOL.$formatted; |
54
|
|
|
$formatted = $negative === true ? '-'.$formatted : $formatted; |
55
|
|
|
|
56
|
|
|
return $formatted; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|