Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

DocumentMoneyCast.php 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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. $currency_code = $attributes['currency_code'] ?? CurrencyAccessor::getDefaultCurrency();
  31. if (is_numeric($value)) {
  32. $value = (string) $value;
  33. } elseif (! is_string($value)) {
  34. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  35. }
  36. return CurrencyConverter::prepareForAccessor($value, $currency_code);
  37. }
  38. }