Passed
Push — master ( 365cfc...8e997c )
by Mr
04:36
created

BitcoinMoneyFormatter::format()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 32
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 42

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 20
c 1
b 0
f 0
nc 13
nop 1
dl 0
loc 32
ccs 0
cts 26
cp 0
crap 42
rs 8.9777
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