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.3KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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 (is_numeric($value)) {
  26. $value = (string) $value;
  27. } elseif (! is_string($value)) {
  28. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  29. }
  30. return CurrencyConverter::prepareForAccessor($value, $currency_code);
  31. }
  32. }