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.

MoneyCast.php 1014B

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. namespace App\Casts;
  3. use App\Utilities\Currency\CurrencyAccessor;
  4. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  5. use Illuminate\Database\Eloquent\Model;
  6. use UnexpectedValueException;
  7. class MoneyCast implements CastsAttributes
  8. {
  9. public function get(Model $model, string $key, mixed $value, array $attributes): string
  10. {
  11. $currency_code = $model->getAttribute('currency_code');
  12. return $value ? money($value, $currency_code)->formatSimple() : '';
  13. }
  14. /**
  15. * @throws UnexpectedValueException
  16. */
  17. public function set(Model $model, string $key, mixed $value, array $attributes): int
  18. {
  19. if (is_int($value)) {
  20. return $value;
  21. }
  22. $currency_code = $model->getAttribute('currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  23. if (! $currency_code) {
  24. throw new UnexpectedValueException('Currency code is not set');
  25. }
  26. return money($value, $currency_code, true)->getAmount();
  27. }
  28. }