|
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
|
|
|
|