PointCurrencyDisplayAttributesCast.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace App\Module\Point\Casts;
  3. use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
  4. use Illuminate\Database\Eloquent\Model;
  5. /**
  6. * 积分类型显示属性Cast类
  7. *
  8. * 用于处理积分类型表中的显示属性字段,将JSON数据转换为数组
  9. */
  10. class PointCurrencyDisplayAttributesCast implements CastsAttributes
  11. {
  12. /**
  13. * 将取出的数据进行转换
  14. *
  15. * @param Model $model
  16. * @param string $key
  17. * @param mixed $value
  18. * @param array $attributes
  19. * @return array
  20. */
  21. public function get(Model $model, string $key, mixed $value, array $attributes): array
  22. {
  23. if (is_null($value)) {
  24. return $this->getDefaultAttributes();
  25. }
  26. if (is_string($value)) {
  27. $decoded = json_decode($value, true);
  28. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  29. return array_merge($this->getDefaultAttributes(), $decoded);
  30. }
  31. }
  32. if (is_array($value)) {
  33. return array_merge($this->getDefaultAttributes(), $value);
  34. }
  35. return $this->getDefaultAttributes();
  36. }
  37. /**
  38. * 转换成将要进行存储的值
  39. *
  40. * @param Model $model
  41. * @param string $key
  42. * @param mixed $value
  43. * @param array $attributes
  44. * @return string
  45. */
  46. public function set(Model $model, string $key, mixed $value, array $attributes): string
  47. {
  48. if (is_null($value)) {
  49. return json_encode($this->getDefaultAttributes());
  50. }
  51. if (is_array($value)) {
  52. return json_encode(array_merge($this->getDefaultAttributes(), $value));
  53. }
  54. if (is_string($value)) {
  55. $decoded = json_decode($value, true);
  56. if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
  57. return json_encode(array_merge($this->getDefaultAttributes(), $decoded));
  58. }
  59. }
  60. return json_encode($this->getDefaultAttributes());
  61. }
  62. /**
  63. * 获取默认显示属性
  64. *
  65. * @return array 默认属性数组
  66. */
  67. private function getDefaultAttributes(): array
  68. {
  69. return [
  70. 'icon' => '🏆', // 默认图标
  71. 'color' => '#52c41a', // 默认颜色
  72. 'background' => '#f6ffed', // 默认背景色
  73. 'border_color' => '#b7eb8f', // 默认边框色
  74. 'text_color' => '#135200', // 默认文字颜色
  75. 'unit' => '积分', // 单位
  76. 'show_in_header' => true, // 是否在头部显示
  77. 'show_in_sidebar' => true, // 是否在侧边栏显示
  78. 'enable_transfer' => true, // 是否允许转账
  79. 'enable_exchange' => true, // 是否允许兑换
  80. 'min_transfer' => 1, // 最小转账数量
  81. 'max_transfer' => 999999, // 最大转账数量
  82. 'sort_order' => 0, // 排序顺序
  83. 'description' => '', // 描述信息
  84. ];
  85. }
  86. }