Dict.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. namespace plugin\admin\app\model;
  3. use support\exception\BusinessException;
  4. /**
  5. * 字典相关
  6. */
  7. class Dict
  8. {
  9. /**
  10. * 获取字典
  11. * @param $name
  12. * @return mixed|null
  13. */
  14. public static function get($name)
  15. {
  16. $value = Option::where('name', static::dictNameToOptionName($name))->value('value');
  17. return $value ? json_decode($value, true) : null;
  18. }
  19. /**
  20. * 保存字典
  21. * @param $name
  22. * @param $values
  23. * @return void
  24. * @throws BusinessException
  25. */
  26. public static function save($name, $values)
  27. {
  28. if (!preg_match('/[a-zA-Z]/', $name)) {
  29. throw new BusinessException('字典名只能包含字母');
  30. }
  31. $option_name = static::dictNameToOptionName($name);
  32. if (!$option = Option::where('name', $option_name)->first()) {
  33. $option = new Option;
  34. }
  35. $format_values = static::filterValue($values);
  36. $option->name = $option_name;
  37. $option->value = json_encode($format_values, JSON_UNESCAPED_UNICODE);
  38. $option->save();
  39. }
  40. /**
  41. * 删除字典
  42. * @param array $names
  43. * @return void
  44. */
  45. public static function delete(array $names)
  46. {
  47. foreach ($names as $index => $name) {
  48. $names[$index] = static::dictNameToOptionName($name);
  49. }
  50. Option::whereIn('name', $names)->delete();
  51. }
  52. /**
  53. * 字典名到option名转换
  54. * @param string $name
  55. * @return string
  56. */
  57. public static function dictNameToOptionName(string $name): string
  58. {
  59. return "dict_$name";
  60. }
  61. /**
  62. * option名到字典名转换
  63. * @param string $name
  64. * @return string
  65. */
  66. public static function optionNameToDictName(string $name): string
  67. {
  68. return substr($name, 5);
  69. }
  70. /**
  71. * 过滤值
  72. * @param array $values
  73. * @return array
  74. * @throws BusinessException
  75. */
  76. public static function filterValue(array $values): array
  77. {
  78. $format_values = [];
  79. foreach ($values as $item) {
  80. if (!isset($item['value']) || !isset($item['name'])) {
  81. throw new BusinessException('字典格式错误', 1);
  82. }
  83. $format_values[] = ['value' => $item['value'], 'name' => $item['name']];
  84. }
  85. return $format_values;
  86. }
  87. }