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 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. private array $currencyCache = [];
  12. public function get(Model $model, string $key, mixed $value, array $attributes): string
  13. {
  14. // Attempt to retrieve the currency code from the related bankAccount->account model
  15. $currencyCode = $this->getCurrencyCodeFromBankAccountId($attributes['bank_account_id'] ?? null);
  16. if ($value !== null) {
  17. return CurrencyConverter::prepareForMutator($value, $currencyCode);
  18. }
  19. return '';
  20. }
  21. /**
  22. * @throws UnexpectedValueException
  23. */
  24. public function set(Model $model, string $key, mixed $value, array $attributes): int
  25. {
  26. $currencyCode = $this->getCurrencyCodeFromBankAccountId($attributes['bank_account_id'] ?? null);
  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 CurrencyConverter::prepareForAccessor($value, $currencyCode);
  33. }
  34. /**
  35. * Using this is necessary because the relationship is not always loaded into memory when the cast is called
  36. * Instead of using: $model->bankAccount->account->currency_code directly, find the bank account and get the currency code
  37. */
  38. private function getCurrencyCodeFromBankAccountId(?int $bankAccountId): string
  39. {
  40. if ($bankAccountId === null) {
  41. return CurrencyAccessor::getDefaultCurrency();
  42. }
  43. if (isset($this->currencyCache[$bankAccountId])) {
  44. return $this->currencyCache[$bankAccountId];
  45. }
  46. $bankAccount = BankAccount::find($bankAccountId);
  47. $currencyCode = $bankAccount?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  48. $this->currencyCache[$bankAccountId] = $currencyCode;
  49. return $currencyCode;
  50. }
  51. }