CastsAttributes.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace UCore\Model;
  3. use Illuminate\Contracts\Support\Arrayable;
  4. use Illuminate\Database\Eloquent\Model;
  5. abstract class CastsAttributes implements \Illuminate\Contracts\Database\Eloquent\CastsAttributes,Arrayable
  6. {
  7. public function toArray()
  8. {
  9. $data = [];
  10. foreach (get_object_vars($this) as $key => $value) {
  11. if ($key === 'model' || $key === 'key' || $key === 'value' || $key === 'attributes') {
  12. continue;
  13. }
  14. if ($value instanceof Arrayable) {
  15. $data[$key] = $value->toArray();
  16. } else {
  17. $data[$key] = $value;
  18. }
  19. }
  20. return $data;
  21. }
  22. /**
  23. * 将取出的数据转换为对应的类型
  24. *
  25. * @param Model $model
  26. * @param string $key
  27. * @param mixed $value
  28. * @param array $attributes
  29. * @return array
  30. */
  31. public function get($model, string $key, $value, array $attributes): static
  32. {
  33. $ob = json_decode($value, true);
  34. if (empty($ob)) {
  35. $ob = json_decode('{}',true);
  36. }
  37. $res = new static();
  38. $res->setData($ob);
  39. return $res;
  40. }
  41. public function setData(array $data)
  42. {
  43. foreach ($data as $key => $value) {
  44. $this->{$key} = $value;
  45. }
  46. return $this;
  47. }
  48. /**
  49. * 将给定的值转换为存储格式
  50. *
  51. * @param Model $model
  52. * @param string $key
  53. * @param mixed $value
  54. * @param array $attributes
  55. * @return string|null
  56. */
  57. public function set($model, string $key, $value, array $attributes)
  58. {
  59. if (is_null($value)) {
  60. return json_encode([], JSON_UNESCAPED_UNICODE);
  61. }
  62. return json_encode($value, JSON_UNESCAPED_UNICODE);
  63. }
  64. /**
  65. * 判断字符串是否为有效的JSON
  66. *
  67. * @param string $value
  68. * @return bool
  69. */
  70. protected function isJson($value)
  71. {
  72. if (!is_string($value)) {
  73. return false;
  74. }
  75. json_decode($value);
  76. return json_last_error() === JSON_ERROR_NONE;
  77. }
  78. }