Passed
Push — master ( dc8a95...3f9dc5 )
by Svaťa
02:20
created

Price::fromMoney()   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 0
Metric Value
cc 1
eloc 3
nc 1
nop 1
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 1
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Simara\Cart\Domain;
4
5
use Money\Money;
6
use Money\Number;
7
8
class Price
9
{
10
    private const EURO_TO_CENTS_CONVERTING_BASE = -2;
11
    private const CENTS_TO_EURO_CONVERTING_BASE = 2;
12
13
    /**
14
     * @var Money
15
     */
16
    private $withVat;
17
18 40
    public function __construct(string $withVat)
19
    {
20 40
        $cents = $this->eurToCents($withVat);
21 40
        $this->withVat = Money::EUR($cents);
22 40
    }
23
24
    /**
25
     * @param self[] $prices
26
     * @return self
27
     */
28 17
    public static function sum(array $prices): self
29
    {
30
        return array_reduce($prices, function (self $carry, self $price) {
31 14
            return $carry->add($price);
32 17
        }, new self('0'));
33
    }
34
35 13
    public function getWithVat(): string
36
    {
37 13
        return $this->centsToEurs($this->withVat->getAmount());
38
    }
39
40 15
    public function add(self $adder): self
41
    {
42 15
        $withVat = $this->withVat->add($adder->withVat);
43 15
        return self::fromMoney($withVat);
44
    }
45
46 15
    public function multiply(int $multiplier): self
47
    {
48 15
        $withVat = $this->withVat->multiply($multiplier);
49 15
        return self::fromMoney($withVat);
50
    }
51
52 17
    private static function fromMoney(Money $withVat): self
53
    {
54 17
        $price = new self('0');
55 17
        $price->withVat = $withVat;
56 17
        return $price;
57
    }
58
59 40
    private function eurToCents(string $euros): string
60
    {
61 40
        $number = Number::fromString($euros);
62 40
        return $number->base10(self::EURO_TO_CENTS_CONVERTING_BASE)->getIntegerPart();
63
    }
64
65 13
    private function centsToEurs(string $cents): string
66
    {
67 13
        $number = new Number($cents);
68 13
        $inEuro = $number->base10(self::CENTS_TO_EURO_CONVERTING_BASE);
69 13
        if ($inEuro->isInteger()) {
70 10
            return $inEuro->getIntegerPart();
71
        } else {
72 3
            return $inEuro->getIntegerPart() . '.' . $inEuro->getFractionalPart();
73
        }
74
    }
75
}
76