Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
8 / 8 |
|
100.00% |
6 / 6 |
CRAP | |
100.00% |
1 / 1 |
| Money | |
100.00% |
8 / 8 |
|
100.00% |
6 / 6 |
8 | |
100.00% |
1 / 1 |
| __construct | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| amount | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| currency | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| add | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
1 | |||
| equals | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| assertSameCurrency | |
100.00% |
2 / 2 |
|
100.00% |
1 / 1 |
2 | |||
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace App\Shared\Domain\ValueObject; |
| 6 | |
| 7 | use InvalidArgumentException; |
| 8 | |
| 9 | /** |
| 10 | * Monetary amount stored in minor units (e.g. cents) to avoid float rounding. |
| 11 | */ |
| 12 | final class Money |
| 13 | { |
| 14 | public function __construct( |
| 15 | private readonly int $amount, |
| 16 | private readonly Currency $currency, |
| 17 | ) { |
| 18 | } |
| 19 | |
| 20 | public function amount(): int |
| 21 | { |
| 22 | return $this->amount; |
| 23 | } |
| 24 | |
| 25 | public function currency(): Currency |
| 26 | { |
| 27 | return $this->currency; |
| 28 | } |
| 29 | |
| 30 | public function add(self $other): self |
| 31 | { |
| 32 | $this->assertSameCurrency($other); |
| 33 | |
| 34 | return new self($this->amount + $other->amount, $this->currency); |
| 35 | } |
| 36 | |
| 37 | public function equals(self $other): bool |
| 38 | { |
| 39 | return $this->amount === $other->amount && $this->currency->equals($other->currency); |
| 40 | } |
| 41 | |
| 42 | private function assertSameCurrency(self $other): void |
| 43 | { |
| 44 | if (!$this->currency->equals($other->currency)) { |
| 45 | throw new InvalidArgumentException(sprintf('Cannot operate on different currencies <%s> and <%s>.', $this->currency, $other->currency)); |
| 46 | } |
| 47 | } |
| 48 | } |