CallbackDataCast.php 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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 CallbackDataCast 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 [];
  17. }
  18. if (is_string($value)) {
  19. $decoded = json_decode($value, true);
  20. return is_array($decoded) ? $decoded : [];
  21. }
  22. return is_array($value) ? $value : [];
  23. }
  24. /**
  25. * 转换成将要进行存储的值
  26. */
  27. public function set(Model $model, string $key, mixed $value, array $attributes): mixed
  28. {
  29. if (is_null($value)) {
  30. return null;
  31. }
  32. if (is_array($value)) {
  33. return json_encode($value, JSON_UNESCAPED_UNICODE);
  34. }
  35. if (is_string($value)) {
  36. // 验证是否为有效的JSON
  37. $decoded = json_decode($value, true);
  38. if (json_last_error() === JSON_ERROR_NONE) {
  39. return $value;
  40. }
  41. }
  42. // 其他类型转换为JSON
  43. return json_encode($value, JSON_UNESCAPED_UNICODE);
  44. }
  45. }