Completed
Pull Request — master (#43)
by Toni
12:42 queued 02:31
created

MixedMoney::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Z38\SwissPayment\Money;
4
5
/**
6
 * Sum of money in mixed currencies
7
 */
8
class MixedMoney 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
    public function __construct($cents, $decimals = 0)
22
    {
23
        parent::__construct($cents);
24
        $this->decimals = $decimals;
25
    }
26
27
    /**
28
     * {@inheritdoc}
29
     */
30
    final public function getCurrency()
31
    {
32
        return null;
33
    }
34
35
    /**
36
     * {@inheritdoc}
37
     */
38
    final protected function getDecimals()
39
    {
40
        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
    public function plus(Money $addend)
51
    {
52
        list($thisCents, $addendCents, $decimals) = self::normalizeDecimals($this, $addend);
53
54
        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
    public function minus(Money $subtrahend)
65
    {
66
        list($thisCents, $subtrahendCents, $decimals) = self::normalizeDecimals($this, $subtrahend);
67
68
        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
    protected static function normalizeDecimals(Money $a, Money $b)
80
    {
81
        $decimalsDiff = ($a->getDecimals() - $b->getDecimals());
82
        $decimalsMax = max($a->getDecimals(), $b->getDecimals());
83
        if ($decimalsDiff > 0) {
84
            return [$a->getAmount(), pow(10, $decimalsDiff) * $b->getAmount(), $decimalsMax];
85
        } elseif ($decimalsDiff < 0) {
86
            return [pow(10, -$decimalsDiff) * $a->getAmount(), $b->getAmount(), $decimalsMax];
87
        } else {
88
            return [$a->getAmount(), $b->getAmount(), $decimalsMax];
89
        }
90
    }
91
}
92