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

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