Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Money.php 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 ?string $currencyCode,
  11. ) {
  12. $this->currencyCode = $currencyCode ?: CurrencyAccessor::getDefaultCurrency();
  13. }
  14. public function getAmount(): int
  15. {
  16. return $this->amount;
  17. }
  18. public function getCurrencyCode(): string
  19. {
  20. return $this->currencyCode;
  21. }
  22. public function getEffectiveAmount(): int
  23. {
  24. return $this->convertedAmount ?? $this->amount;
  25. }
  26. public function getConvertedAmount(): ?int
  27. {
  28. return $this->convertedAmount;
  29. }
  30. public function getValue(): float
  31. {
  32. return money($this->amount, $this->currencyCode)->getValue();
  33. }
  34. public function format(): string
  35. {
  36. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->format();
  37. }
  38. public function formatInDefaultCurrency(): string
  39. {
  40. return money($this->getEffectiveAmount(), CurrencyAccessor::getDefaultCurrency())->format();
  41. }
  42. public function formatSimple(): string
  43. {
  44. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->formatSimple();
  45. }
  46. public function formatWithCode(bool $codeBefore = false): string
  47. {
  48. return money($this->getEffectiveAmount(), $this->getCurrencyCode())->formatWithCode($codeBefore);
  49. }
  50. public function convert(): self
  51. {
  52. // The journal entry sums are stored in the default currency not the account currency (transaction amounts are stored in the account currency)
  53. $fromCurrency = CurrencyAccessor::getDefaultCurrency();
  54. $toCurrency = $this->currencyCode;
  55. if ($fromCurrency !== $toCurrency) {
  56. $this->convertedAmount = CurrencyConverter::convertBalance($this->amount, $fromCurrency, $toCurrency);
  57. }
  58. return $this;
  59. }
  60. public function __toString(): string
  61. {
  62. return $this->formatSimple();
  63. }
  64. }