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.

TransactionAmountCast.php 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. namespace App\Casts;
  3. use App\Utilities\Currency\CurrencyAccessor;
  4. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  5. use Illuminate\Database\Eloquent\Model;
  6. use UnexpectedValueException;
  7. class TransactionAmountCast implements CastsAttributes
  8. {
  9. public function get(Model $model, string $key, mixed $value, array $attributes): string
  10. {
  11. // Attempt to retrieve the currency code from the related bankAccount->account model
  12. $currency_code = $model->bankAccount?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  13. if ($value !== null) {
  14. return money($value, $currency_code)->formatSimple();
  15. }
  16. return '';
  17. }
  18. /**
  19. * @throws UnexpectedValueException
  20. */
  21. public function set(Model $model, string $key, mixed $value, array $attributes): int
  22. {
  23. $currency_code = $model->bankAccount?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  24. if (! $currency_code) {
  25. throw new UnexpectedValueException('Currency code is not set');
  26. }
  27. if (is_numeric($value)) {
  28. $value = (string) $value;
  29. } elseif (! is_string($value)) {
  30. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  31. }
  32. return money($value, $currency_code, true)->getAmount();
  33. }
  34. }