TransactionDetailsCast.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Module\GameItems\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. class TransactionDetailsCast 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. return json_encode($value, JSON_UNESCAPED_UNICODE);
  40. }
  41. if (is_string($value) && $this->isJson($value)) {
  42. return $value;
  43. }
  44. return json_encode([], JSON_UNESCAPED_UNICODE);
  45. }
  46. /**
  47. * 判断字符串是否为有效的JSON
  48. *
  49. * @param string $value
  50. * @return bool
  51. */
  52. protected function isJson($value)
  53. {
  54. if (!is_string($value)) {
  55. return false;
  56. }
  57. json_decode($value);
  58. return json_last_error() === JSON_ERROR_NONE;
  59. }
  60. }