Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

MoneyCast.php 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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') ?? CurrencyAccessor::getDefaultCurrency();
  12. if ($value !== null) {
  13. return money($value, $currency_code)->formatSimple();
  14. }
  15. return '';
  16. }
  17. /**
  18. * @throws UnexpectedValueException
  19. */
  20. public function set(Model $model, string $key, mixed $value, array $attributes): int
  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. if (is_numeric($value)) {
  27. $value = (string) $value;
  28. } elseif (! is_string($value)) {
  29. throw new UnexpectedValueException('Expected string or numeric value for money cast');
  30. }
  31. return money($value, $currency_code, true)->getAmount();
  32. }
  33. }