Created
March 25, 2024 09:27
-
-
Save faparicior/458b49b3cc135b6bb18e1a8e0adaad7a to your computer and use it in GitHub Desktop.
workshop-value-object-or-not-quiz-5
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
readonly class Money | |
{ | |
private function __construct(private string $amount, private Currency $currency) | |
{} | |
public static function eur(string $amount): self | |
{ | |
return new static($amount, Currency::eur()); | |
} | |
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); | |
return new self($sum, $this->currency); | |
} | |
public function equals(Money $other): bool | |
{ | |
if (get_class($this) != get_class($other)) { | |
return false; | |
} | |
return $this->amount === $other->amount() && | |
$this->currency === $other->currency(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment