Completed
Push — master ( 67432b...61d761 )
by z38
04:15
created

Mixed::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.4286
cc 1
eloc 3
nc 1
nop 2
crap 1
1
<?php
2
3
namespace Z38\SwissPayment\Money;
4
5
/**
6
 * Sum of money in mixed currencies
7
 */
8
class Mixed extends Money
9
{
10
    /**
11
     * @var int
12
     */
13
    protected $decimals;
14
15
    /**
16
     * Constructor
17
     *
18
     * @param int $cents    Amount of money in cents
19
     * @param int $decimals Number of minor units
20
     */
21 2
    public function __construct($cents, $decimals = 0)
22
    {
23 2
        parent::__construct($cents);
24 2
        $this->decimals = $decimals;
25 2
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    final public function getCurrency()
31
    {
32
        return null;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38 2
    final protected function getDecimals()
39
    {
40 2
        return $this->decimals;
41
    }
42
43
    /**
44
     * Returns the sum of this and an other amount of money
45
     *
46
     * @param Money $addend The addend
47
     *
48
     * @return Money The sum
49
     */
50 3
    public function plus(Money $addend)
51
    {
52 3
        list($thisCents, $addendCents, $decimals) = self::normalizeDecimals($this, $addend);
53
54 3
        return new static($thisCents + $addendCents, $decimals);
55
    }
56
57
    /**
58
     * Returns the subtraction of this and an other amount of money
59
     *
60
     * @param Money $subtrahend The subtrahend
61
     *
62
     * @return Money The difference
63
     */
64 1
    public function minus(Money $subtrahend)
65
    {
66 1
        list($thisCents, $subtrahendCents, $decimals) = self::normalizeDecimals($this, $subtrahend);
67
68 1
        return new static($thisCents - $subtrahendCents, $decimals);
69
    }
70
71
    /**
72
     * Normalizes two amounts such that they have the same number of decimals
73
     *
74
     * @param Money $a
75
     * @param Money $b
76
     *
77
     * @return array An array containing the two amounts and number of decimals
78
     */
79 2
    protected static function normalizeDecimals(Money $a, Money $b)
80
    {
81 2
        $decimalsDiff = ($a->getDecimals() - $b->getDecimals());
82 2
        $decimalsMax = max($a->getDecimals(), $b->getDecimals());
83 2
        if ($decimalsDiff > 0) {
84
            return array($a->getAmount(), pow(10, $decimalsDiff) * $b->getAmount(), $decimalsMax);
85 2
        } elseif ($decimalsDiff < 0) {
86 2
            return array(pow(10, -$decimalsDiff) * $a->getAmount(), $b->getAmount(), $decimalsMax);
87
        } else {
88 2
            return array($a->getAmount(), $b->getAmount(), $decimalsMax);
89
        }
90
    }
91
}
92