Passed
Push — master ( 3f9dc5...9316b9 )
by Svaťa
03:00
created

Price::fromDecimal()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Simara\Cart\Domain;
4
5
use Litipk\BigNumbers\Decimal;
6
7
class Price
8
{
9
    private const DECIMALS = 2;
10
11
    /**
12
     * @var Decimal
13
     */
14
    private $withVat;
15
16 40
    public function __construct(string $withVat)
17
    {
18 40
        $withHigherPrecision = Decimal::fromString($withVat, self::DECIMALS + 1);
19 40
        $truncated = $withHigherPrecision->floor(self::DECIMALS);
20 40
        $this->withVat = $truncated;
21 40
    }
22
23
    /**
24
     * @param self[] $prices
25
     * @return self
26
     */
27 17
    public static function sum(array $prices): self
28
    {
29
        return array_reduce($prices, function (self $carry, self $price) {
30 14
            return $carry->add($price);
31 17
        }, new self('0'));
32
    }
33
34 13
    public function getWithVat(): string
35
    {
36 13
        return (string) $this->withVat->floor(self::DECIMALS);
37
    }
38
39 15
    public function add(self $adder): self
40
    {
41 15
        $withVat = $this->withVat->add($adder->withVat);
42 15
        return self::fromDecimal($withVat);
43
    }
44
45 15
    public function multiply(int $multiplier): self
46
    {
47 15
        $withVat = $this->withVat->mul(Decimal::fromInteger($multiplier));
48 15
        return self::fromDecimal($withVat);
49
    }
50
51 17
    private static function fromDecimal(Decimal $withVat): self
52
    {
53 17
        return new self($withVat->floor(self::DECIMALS));
54
    }
55
}
56