Price::fromDecimal()   A
last analyzed

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
final class Price
8
{
9
    private const DECIMALS = 2;
10
11
    private Decimal $withVat;
12
13 33
    public function __construct(string $withVat)
14
    {
15 33
        $withHigherPrecision = Decimal::fromString($withVat, self::DECIMALS + 1);
16 33
        $truncated = $withHigherPrecision->floor(self::DECIMALS);
17 33
        $this->withVat = $truncated;
18 33
    }
19
20
    /**
21
     * @param self[] $prices
22
     * @return self
23
     */
24 18
    public static function sum(array $prices): self
25
    {
26 18
        return array_reduce(
27 18
            $prices,
28 18
            fn(self $carry, self $price) => $carry->add($price),
29 18
            new self('0')
30
        );
31
    }
32
33 7
    public function getWithVat(): string
34
    {
35 7
        return (string) $this->withVat->floor(self::DECIMALS);
36
    }
37
38 16
    public function add(self $adder): self
39
    {
40 16
        $withVat = $this->withVat->add($adder->withVat);
41 16
        return self::fromDecimal($withVat);
42
    }
43
44 16
    public function multiply(int $multiplier): self
45
    {
46 16
        $withVat = $this->withVat->mul(Decimal::fromInteger($multiplier));
47 16
        return self::fromDecimal($withVat);
48
    }
49
50 18
    private static function fromDecimal(Decimal $withVat): self
51
    {
52 18
        return new self($withVat->floor(self::DECIMALS)->__toString());
53
    }
54
}
55