NumericAttributesCast.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Module\GameItems\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. class NumericAttributesCast implements CastsAttributes
  6. {
  7. /**
  8. * 将取出的数据转换为对应的类型
  9. *
  10. * @param Model $model
  11. * @param string $key
  12. * @param mixed $value
  13. * @param array $attributes
  14. * @return array
  15. */
  16. public function get($model, string $key, $value, array $attributes)
  17. {
  18. if (is_null($value)) {
  19. return [];
  20. }
  21. $decoded = json_decode($value, true);
  22. if (!is_array($decoded)) {
  23. return [];
  24. }
  25. // 确保所有值都是数值类型
  26. $result = [];
  27. foreach ($decoded as $k => $v) {
  28. $result[$k] = is_numeric($v) ? (float) $v : 0;
  29. }
  30. return $result;
  31. }
  32. /**
  33. * 将给定的值转换为存储格式
  34. *
  35. * @param Model $model
  36. * @param string $key
  37. * @param mixed $value
  38. * @param array $attributes
  39. * @return string|null
  40. */
  41. public function set($model, string $key, $value, array $attributes)
  42. {
  43. if (is_null($value)) {
  44. return json_encode([], JSON_UNESCAPED_UNICODE);
  45. }
  46. if (is_array($value)) {
  47. // 确保所有值都是数值类型
  48. $sanitized = [];
  49. foreach ($value as $k => $v) {
  50. $sanitized[$k] = is_numeric($v) ? (float) $v : 0;
  51. }
  52. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  53. }
  54. if (is_string($value) && $this->isJson($value)) {
  55. // 如果已经是JSON字符串,确保解码后的值都是数值类型
  56. $decoded = json_decode($value, true);
  57. if (is_array($decoded)) {
  58. $sanitized = [];
  59. foreach ($decoded as $k => $v) {
  60. $sanitized[$k] = is_numeric($v) ? (float) $v : 0;
  61. }
  62. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  63. }
  64. return $value;
  65. }
  66. return json_encode([], JSON_UNESCAPED_UNICODE);
  67. }
  68. /**
  69. * 判断字符串是否为有效的JSON
  70. *
  71. * @param string $value
  72. * @return bool
  73. */
  74. protected function isJson($value)
  75. {
  76. if (!is_string($value)) {
  77. return false;
  78. }
  79. json_decode($value);
  80. return json_last_error() === JSON_ERROR_NONE;
  81. }
  82. }