DisplayAttributesCast.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. namespace App\Module\GameItems\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. class DisplayAttributesCast 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. return is_array($decoded) ? $decoded : [];
  23. }
  24. /**
  25. * 将给定的值转换为存储格式
  26. *
  27. * @param Model $model
  28. * @param string $key
  29. * @param mixed $value
  30. * @param array $attributes
  31. * @return string|null
  32. */
  33. public function set($model, string $key, $value, array $attributes)
  34. {
  35. if (is_null($value)) {
  36. return json_encode([], JSON_UNESCAPED_UNICODE);
  37. }
  38. if (is_array($value)) {
  39. // 确保所有值都是字符串类型
  40. $sanitized = [];
  41. foreach ($value as $k => $v) {
  42. $sanitized[$k] = (string) $v;
  43. }
  44. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  45. }
  46. if (is_string($value) && $this->isJson($value)) {
  47. // 如果已经是JSON字符串,确保解码后的值都是字符串类型
  48. $decoded = json_decode($value, true);
  49. if (is_array($decoded)) {
  50. $sanitized = [];
  51. foreach ($decoded as $k => $v) {
  52. $sanitized[$k] = (string) $v;
  53. }
  54. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  55. }
  56. return $value;
  57. }
  58. return json_encode([], JSON_UNESCAPED_UNICODE);
  59. }
  60. /**
  61. * 判断字符串是否为有效的JSON
  62. *
  63. * @param string $value
  64. * @return bool
  65. */
  66. protected function isJson($value)
  67. {
  68. if (!is_string($value)) {
  69. return false;
  70. }
  71. json_decode($value);
  72. return json_last_error() === JSON_ERROR_NONE;
  73. }
  74. }