Money::getCurrency()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
crap 1
1
<?php
2
3
namespace Assimtech\Money;
4
5
use Locale;
6
use NumberFormatter;
7
8
class Money
9
{
10
    /**
11
     * @var float $amount
12
     */
13
    private $amount;
14
15
    /**
16
     * @var Currency $currency
17
     */
18
    private $currency;
19
20
    /**
21
     * @param float|integer $amount
22
     * @param Currency|string $currency iso4217 currency
23
     */
24 10
    public function __construct($amount, Currency $currency)
25
    {
26 10
        $this->currency = $currency;
27 10
        $this->setAmount($amount);
28 10
    }
29
30
    /**
31
     * @return string
32
     */
33 1
    public function __toString()
34
    {
35 1
        return sprintf(
36 1
            '%s %s',
37 1
            $this->getFormattedAmount(),
38 1
            $this->currency
39 1
        );
40
    }
41
42
    /**
43
     * @param float $amount
44
     * @return self
45
     */
46 10
    public function setAmount($amount)
47
    {
48 10
        $this->amount = round($amount, $this->currency->getFractionDigits());
49
50 10
        return $this;
51
    }
52
53
    /**
54
     * @return float
55
     */
56 2
    public function getAmount()
57
    {
58 2
        return $this->amount;
59
    }
60
61
    /**
62
     * @param string|null $locale if null, defaults to Locale::getDefault
63
     * @return string
64
     */
65 2
    public function getFormattedAmount($locale = null)
66
    {
67 2
        if ($locale === null) {
68 1
            $locale = Locale::getDefault();
69 1
        }
70
71 2
        $numberFormatter = new NumberFormatter($locale, NumberFormatter::DECIMAL);
72 2
        $fractionDigits = $this->currency->getFractionDigits();
73 2
        $numberFormatter->setAttribute(NumberFormatter::MIN_FRACTION_DIGITS, $fractionDigits);
74 2
        $numberFormatter->setAttribute(NumberFormatter::MAX_FRACTION_DIGITS, $fractionDigits);
75
76 2
        return $numberFormatter->format($this->amount);
77
    }
78
79
    /**
80
     * @return Currency
81
     */
82 2
    public function getCurrency()
83
    {
84 2
        return $this->currency;
85
    }
86
}
87