DisplayAttributesCast.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace App\Module\GameItems\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. use JsonMapper;
  6. class DisplayAttributesCast extends \UCore\Model\CastsAttributes
  7. {
  8. /**
  9. * 客户端图标地址
  10. * @var string $img
  11. */
  12. public string $img = ' ';
  13. /**
  14. * 将给定的值转换为存储格式
  15. *
  16. * @param Model $model
  17. * @param string $key
  18. * @param mixed $value
  19. * @param array $attributes
  20. * @return string|null
  21. */
  22. public function set($model, string $key, $value, array $attributes)
  23. {
  24. if (is_null($value)) {
  25. return json_encode([], JSON_UNESCAPED_UNICODE);
  26. }
  27. if (is_array($value)) {
  28. // 确保所有值都是字符串类型
  29. $sanitized = [];
  30. foreach ($value as $k => $v) {
  31. $sanitized[$k] = (string)$v;
  32. }
  33. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  34. }
  35. if (is_string($value) && $this->isJson($value)) {
  36. // 如果已经是JSON字符串,确保解码后的值都是字符串类型
  37. $decoded = json_decode($value, true);
  38. if (is_array($decoded)) {
  39. $sanitized = [];
  40. foreach ($decoded as $k => $v) {
  41. $sanitized[$k] = (string)$v;
  42. }
  43. return json_encode($sanitized, JSON_UNESCAPED_UNICODE);
  44. }
  45. return $value;
  46. }
  47. return json_encode([], JSON_UNESCAPED_UNICODE);
  48. }
  49. /**
  50. * 判断字符串是否为有效的JSON
  51. *
  52. * @param string $value
  53. * @return bool
  54. */
  55. protected function isJson($value)
  56. {
  57. if (!is_string($value)) {
  58. return false;
  59. }
  60. json_decode($value);
  61. return json_last_error() === JSON_ERROR_NONE;
  62. }
  63. }