Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

TransactionAmountCast.php 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace App\Casts;
  3. use App\Models\Banking\BankAccount;
  4. use App\Utilities\Currency\CurrencyAccessor;
  5. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  6. use Illuminate\Database\Eloquent\Model;
  7. use UnexpectedValueException;
  8. class TransactionAmountCast implements CastsAttributes
  9. {
  10. /**
  11. * Static cache to persist across instances
  12. */
  13. private static array $currencyCache = [];
  14. /**
  15. * Eagerly load all required bank accounts at once if needed
  16. */
  17. private function loadMissingBankAccounts(array $ids): void
  18. {
  19. $missingIds = array_filter($ids, static fn ($id) => ! isset(self::$currencyCache[$id]) && $id !== null);
  20. if (empty($missingIds)) {
  21. return;
  22. }
  23. /** @var BankAccount[] $accounts */
  24. $accounts = BankAccount::with('account')
  25. ->whereIn('id', $missingIds)
  26. ->get();
  27. foreach ($accounts as $account) {
  28. self::$currencyCache[$account->id] = $account->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
  29. }
  30. }
  31. public function get(Model $model, string $key, mixed $value, array $attributes): int
  32. {
  33. return (int) $value;
  34. }
  35. /**
  36. * @throws UnexpectedValueException
  37. */
  38. public function set(Model $model, string $key, mixed $value, array $attributes): int
  39. {
  40. return (int) $value;
  41. }
  42. /**
  43. * Get currency code from the cache or use default
  44. */
  45. private function getCurrencyCodeFromBankAccountId(?int $bankAccountId): string
  46. {
  47. if ($bankAccountId === null) {
  48. return CurrencyAccessor::getDefaultCurrency();
  49. }
  50. return self::$currencyCache[$bankAccountId] ?? CurrencyAccessor::getDefaultCurrency();
  51. }
  52. }