Created
March 21, 2024 18:52
-
-
Save faparicior/4b48afefdeda4b7d54cde218dd4556ec to your computer and use it in GitHub Desktop.
workshop-value-object-or-not-quiz-3
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 | |
{ | |
private string $amount; | |
private string $currency; | |
public function __construct(private string $amount, private string $currency) | |
{ | |
if (!is_numeric($amount)) { | |
throw new InvalidAmountException::notNumeric($amount); | |
} | |
if (!in_array(strtoupper($currency), ['EUR', 'USD'])) { | |
throw new InvalidCurrencyException::notInTheAcceptedCurrencies($currency); | |
} | |
$this->amount = $amount; | |
$this->currency = $currency; | |
} | |
public function amount(): string | |
{ | |
return $this->amount; | |
} | |
public function currency(): string | |
{ | |
return $this->currency; | |
} | |
public function equals(Money $other): bool | |
{ | |
return $this->amount === $other->amount() && | |
$this->currency === $other->currency(); | |
} | |
public function add(Money $other): Money | |
{ | |
if ($this->currency !== $other->currency()) { | |
throw new InvalidCurrencyException::notEquals($this->currency, $other->currency()); | |
} | |
$sum = bcadd($this->amount, $other->amount(), 2); | |
return new self($sum, $this->currency); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment