Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

MoneyCast.php 887B

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