You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

DocumentMoneyCast.php 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 DocumentMoneyCast implements CastsAttributes
  9. {
  10. /**
  11. * Cast the given value.
  12. *
  13. * @param array<string, mixed> $attributes
  14. */
  15. public function get(Model $model, string $key, mixed $value, array $attributes): mixed
  16. {
  17. $currency_code = $attributes['currency_code'] ?? CurrencyAccessor::getDefaultCurrency();
  18. if ($value !== null) {
  19. return CurrencyConverter::convertCentsToFloat($value, $currency_code);
  20. }
  21. return 0.0;
  22. }
  23. /**
  24. * Prepare the given value for storage.
  25. *
  26. * @param array<string, mixed> $attributes
  27. */
  28. public function set(Model $model, string $key, mixed $value, array $attributes): mixed
  29. {
  30. if (is_numeric($value)) {
  31. $value = (string) $value;
  32. } elseif (! is_string($value)) {
  33. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  34. }
  35. return CurrencyConverter::prepareForAccessor($value, 'USD');
  36. }
  37. }