Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

TransactionAmountCast.php 1.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. namespace App\Casts;
  3. use App\Models\Banking\BankAccount;
  4. use App\Utilities\Currency\CurrencyAccessor;
  5. use App\Utilities\Currency\CurrencyConverter;
  6. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  7. use Illuminate\Database\Eloquent\Model;
  8. use UnexpectedValueException;
  9. class TransactionAmountCast implements CastsAttributes
  10. {
  11. public function get(Model $model, string $key, mixed $value, array $attributes): string
  12. {
  13. // Attempt to retrieve the currency code from the related bankAccount->account model
  14. $currency_code = $this->getCurrencyCodeFromBankAccountId($attributes['bank_account_id'] ?? null);
  15. if ($value !== null) {
  16. return CurrencyConverter::prepareForMutator($value, $currency_code);
  17. }
  18. return '';
  19. }
  20. /**
  21. * @throws UnexpectedValueException
  22. */
  23. public function set(Model $model, string $key, mixed $value, array $attributes): int
  24. {
  25. $currency_code = $this->getCurrencyCodeFromBankAccountId($attributes['bank_account_id'] ?? null);
  26. if (is_numeric($value)) {
  27. $value = (string) $value;
  28. } elseif (! is_string($value)) {
  29. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  30. }
  31. return CurrencyConverter::prepareForAccessor($value, $currency_code);
  32. }
  33. /**
  34. * Using this is necessary because the relationship is not always loaded into memory when the cast is called
  35. * Instead of using: $model->bankAccount->account->currency_code directly, find the bank account and get the currency code
  36. */
  37. private function getCurrencyCodeFromBankAccountId(?int $bankAccountId): string
  38. {
  39. if ($bankAccountId === null) {
  40. return CurrencyAccessor::getDefaultCurrency();
  41. }
  42. $bankAccount = BankAccount::find($bankAccountId);
  43. return $bankAccount?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  44. }
  45. }