Assets::__construct()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
crap 2
1
<?php
2
/**
3
 * Date: 11.11.18
4
 * Time: 19:34
5
 */
6
7
namespace AlecRabbit\Assets;
8
9
use AlecRabbit\Currency\Currency;
10
11
class Assets
12
{
13
    /** @var Asset[] */
14
    private $assets = [];
15
16
    /**
17
     * Assets constructor.
18
     * @param Asset ...$assets
19
     */
20 16
    public function __construct(Asset ...$assets)
21
    {
22 16
        foreach ($assets as $newAsset) {
23 16
            $this->add($newAsset);
24
        }
25 16
    }
26
27
    /**
28
     * @param Asset $money
29
     * @return Asset
30
     */
31 16
    public function add(Asset $money): Asset
32
    {
33
        return
34 16
            ($asset = $this->assetOf($money))->isZero() ?
35 16
                $this->setAsset($money) :
36 16
                $this->setAsset($asset->add($money));
37
    }
38
39
    /**
40
     * @param Asset $money
41
     * @return Asset
42
     */
43 16
    private function assetOf(Asset $money): Asset
44
    {
45 16
        return $this->getAsset($money->getCurrency());
46
    }
47
48
    /**
49
     * @param \AlecRabbit\Currency\Currency $currency
50
     * @return Asset
51
     */
52 16
    public function getAsset(Currency $currency): Asset
53
    {
54
        return
55 16
            $this->assets[(string)$currency] ?? $this->setAsset(new Asset(0, $currency));
56
    }
57
58
    /**
59
     * @param Asset $money
60
     * @return Asset
61
     */
62 16
    private function setAsset(Asset $money): Asset
63
    {
64
        return
65 16
            $this->assets[(string)$money->getCurrency()] = $money;
66
    }
67
68
    /**
69
     * @param Asset $money
70
     * @return bool
71
     */
72 11
    public function have(Asset $money): bool
73
    {
74
        return
75 11
            $money->subtract($this->assetOf($money))->isNotPositive();
76
    }
77
78
    /**
79
     * @param Asset $money
80
     * @return Asset
81
     */
82 1
    public function take(Asset $money): Asset
83
    {
84 1
        $asset = $this->subtract($money);
85 1
        if ($asset->isNegative()) {
86 1
            throw new \RuntimeException('You can\'t take more than there is.');
87
        }
88 1
        return $asset;
89
    }
90
91
    /**
92
     * @param Asset $money
93
     * @return Asset
94
     */
95 2
    public function subtract(Asset $money): Asset
96
    {
97
        return
98 2
            $this->add($money->negative());
99
    }
100
101
    /**
102
     * @return iterable
103
     */
104 1
    public function getCurrencies(): iterable
105
    {
106
        return
107 1
            array_keys($this->assets);
108
    }
109
}
110