Price::getCurrency()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace AppBundle\Price;
4
5
/**
6
 * Price value object
7
 */
8
class Price
9
{
10
    const AMOUNT_FORMAT = '/^\d+(\.\d+)?$/';
11
    /**
12
     * @var string
13
     */
14
    private $amount;
15
16
    /**
17
     * @var string
18
     */
19
    private $currency;
20
21
    public function __construct($amount, $currency = 'EUR')
22
    {
23
        if (!is_string($amount) && !preg_match(self::AMOUNT_FORMAT, $amount)) {
24
            throw new \InvalidArgumentException(sprintf(
25
                'Malformed amount: "%s".',
26
                $amount
27
            ));
28
        }
29
        $this->amount = $amount;
30
        $this->currency = $currency;
31
    }
32
33
    public function add(Price $price)
34
    {
35
        $scale = max($this->getScale(), $price->getScale());
36
37
        return new Price(bcadd($this->amount, $price->getAmount(), $scale));
38
    }
39
40
    public function mul($factor)
41
    {
42
        return new Price(bcmul($this->amount, $factor, $this->getScale()));
43
    }
44
45
    public function getAmount()
46
    {
47
        return $this->amount;
48
    }
49
50
    public function getCurrency()
51
    {
52
        return $this->currency;
53
    }
54
55
    public function getScale()
56
    {
57
        $pos = strrpos($this->amount, '.');
58
59
        if (false === $pos) {
60
            return 0;
61
        }
62
63
        return strlen($this->amount) - $pos - 1;
64
    }
65
66
    public function toArray()
67
    {
68
        return array($this->amount, $this->currency);
69
    }
70
}
71