| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 | <?php
namespace App\Casts;
use App\Models\Banking\BankAccount;
use App\Utilities\Currency\CurrencyAccessor;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use UnexpectedValueException;
class TransactionAmountCast implements CastsAttributes
{
    /**
     * Static cache to persist across instances
     */
    private static array $currencyCache = [];
    /**
     * Eagerly load all required bank accounts at once if needed
     */
    private function loadMissingBankAccounts(array $ids): void
    {
        $missingIds = array_filter($ids, static fn ($id) => ! isset(self::$currencyCache[$id]) && $id !== null);
        if (empty($missingIds)) {
            return;
        }
        /** @var BankAccount[] $accounts */
        $accounts = BankAccount::with('account')
            ->whereIn('id', $missingIds)
            ->get();
        foreach ($accounts as $account) {
            self::$currencyCache[$account->id] = $account->account->currency_code ?? CurrencyAccessor::getDefaultCurrency();
        }
    }
    public function get(Model $model, string $key, mixed $value, array $attributes): int
    {
        return (int) $value;
    }
    /**
     * @throws UnexpectedValueException
     */
    public function set(Model $model, string $key, mixed $value, array $attributes): int
    {
        return (int) $value;
    }
    /**
     * Get currency code from the cache or use default
     */
    private function getCurrencyCodeFromBankAccountId(?int $bankAccountId): string
    {
        if ($bankAccountId === null) {
            return CurrencyAccessor::getDefaultCurrency();
        }
        return self::$currencyCache[$bankAccountId] ?? CurrencyAccessor::getDefaultCurrency();
    }
}
 |