TransferAppCast.php 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\Module\Transfer\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. /**
  6. * 划转应用转换器
  7. */
  8. class TransferAppCast implements CastsAttributes
  9. {
  10. /**
  11. * 将取出的数据进行转换
  12. */
  13. public function get(Model $model, string $key, mixed $value, array $attributes): mixed
  14. {
  15. if (is_null($value)) {
  16. return null;
  17. }
  18. // 根据字段类型进行转换
  19. return match ($key) {
  20. 'exchange_rate' => (float) $value,
  21. 'is_enabled' => (bool) $value,
  22. default => $value,
  23. };
  24. }
  25. /**
  26. * 转换成将要进行存储的值
  27. */
  28. public function set(Model $model, string $key, mixed $value, array $attributes): mixed
  29. {
  30. if (is_null($value)) {
  31. return null;
  32. }
  33. // 根据字段类型进行转换
  34. return match ($key) {
  35. 'exchange_rate' => number_format((float) $value, 4, '.', ''),
  36. 'is_enabled' => (bool) $value,
  37. default => $value,
  38. };
  39. }
  40. }