Created
March 21, 2024 18:53
-
-
Save faparicior/057adff8b1396674baa3e695febab2d2 to your computer and use it in GitHub Desktop.
workshop-value-object-or-not-quiz-4
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class Money | |
{ | |
public function __construct(private string $amount, private Currency $currency) | |
{} | |
public function amount(): string | |
{ | |
return $this->amount; | |
} | |
public function currency(): Currency | |
{ | |
return $this->currency; | |
} | |
public function add(Money $other): Money | |
{ | |
if (!$this->currency->equals($other->currency())) { | |
throw new InvalidCurrencyException::notEquals($this->currency, $other->currency()); | |
} | |
$sum = bcadd($this->amount, $other->amount(), 2); // Change '2' to the desired scale | |
return new self($sum, $this->currency); | |
} | |
public function equals(Money $other): bool | |
{ | |
return bccomp($this->amount, $other->amount(), 2) === 0 && | |
$this->currency === $other->currency(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment