CastsAttributes.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. if(is_null($value)){
  45. continue;
  46. }
  47. $this->{$key} = $value;
  48. }
  49. return $this;
  50. }
  51. /**
  52. * 将给定的值转换为存储格式
  53. *
  54. * @param Model $model
  55. * @param string $key
  56. * @param mixed $value
  57. * @param array $attributes
  58. * @return string|null
  59. */
  60. public function set($model, string $key, $value, array $attributes)
  61. {
  62. if (is_null($value)) {
  63. return json_encode([], JSON_UNESCAPED_UNICODE);
  64. }
  65. return json_encode($value, JSON_UNESCAPED_UNICODE);
  66. }
  67. /**
  68. * 判断字符串是否为有效的JSON
  69. *
  70. * @param string $value
  71. * @return bool
  72. */
  73. protected function isJson($value)
  74. {
  75. if (!is_string($value)) {
  76. return false;
  77. }
  78. json_decode($value);
  79. return json_last_error() === JSON_ERROR_NONE;
  80. }
  81. }