You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Money.php 1.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\ValueObjects;
  3. use App\Utilities\Currency\CurrencyAccessor;
  4. use App\Utilities\Currency\CurrencyConverter;
  5. class Money
  6. {
  7. private ?int $convertedAmount = null;
  8. public function __construct(
  9. private readonly int $amount,
  10. private readonly string $currencyCode
  11. ) {
  12. }
  13. public function getAmount(): int
  14. {
  15. return $this->amount;
  16. }
  17. public function getCurrencyCode(): string
  18. {
  19. return $this->currencyCode;
  20. }
  21. public function getEffectiveAmount(): int
  22. {
  23. return $this->convertedAmount ?? $this->amount;
  24. }
  25. public function getConvertedAmount(): ?int
  26. {
  27. return $this->convertedAmount;
  28. }
  29. public function getValue(): float
  30. {
  31. return money($this->amount, $this->currencyCode)->getValue();
  32. }
  33. public function format(): string
  34. {
  35. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->format();
  36. }
  37. public function formatSimple(): string
  38. {
  39. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->formatSimple();
  40. }
  41. public function formatWithCode(bool $codeBefore = false): string
  42. {
  43. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->formatWithCode($codeBefore);
  44. }
  45. public function convert(): self
  46. {
  47. // The journal entry sums are stored in the default currency not the account currency (transaction amounts are stored in the account currency)
  48. $fromCurrency = CurrencyAccessor::getDefaultCurrency();
  49. $toCurrency = $this->currencyCode;
  50. if ($fromCurrency !== $toCurrency) {
  51. $this->convertedAmount = CurrencyConverter::convertBalance($this->amount, $fromCurrency, $toCurrency);
  52. }
  53. return $this;
  54. }
  55. public function __toString(): string
  56. {
  57. return $this->formatSimple();
  58. }
  59. }