ConfigService.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | likeadmin快速开发前后端分离管理后台(PHP版)
  4. // +----------------------------------------------------------------------
  5. // | 欢迎阅读学习系统程序代码,建议反馈是我们前进的动力
  6. // | 开源版本可自由商用,可去除界面版权logo
  7. // | gitee下载:https://gitee.com/likeshop_gitee/likeadmin
  8. // | github下载:https://github.com/likeshop-github/likeadmin
  9. // | 访问官网:https://www.likeadmin.cn
  10. // | likeadmin团队 版权所有 拥有最终解释权
  11. // +----------------------------------------------------------------------
  12. // | author: likeadminTeam
  13. // +----------------------------------------------------------------------
  14. declare(strict_types=1);
  15. namespace app\common\service;
  16. use app\common\model\Config;
  17. class ConfigService
  18. {
  19. /**
  20. * @notes 设置配置值
  21. * @param $type
  22. * @param $name
  23. * @param $value
  24. * @return mixed
  25. * @author 段誉
  26. * @date 2021/12/27 15:00
  27. */
  28. public static function set(string $type, string $name, $value)
  29. {
  30. $original = $value;
  31. if (is_array($value)) {
  32. $value = json_encode($value, JSON_UNESCAPED_UNICODE);
  33. }
  34. $data = Config::where(['type' => $type, 'name' => $name])->findOrEmpty();
  35. if ($data->isEmpty()) {
  36. Config::create([
  37. 'type' => $type,
  38. 'name' => $name,
  39. 'value' => $value,
  40. ]);
  41. } else {
  42. $data->value = $value;
  43. $data->save();
  44. }
  45. // 返回原始值
  46. return $original;
  47. }
  48. /**
  49. * @notes 获取配置值
  50. * @param $type
  51. * @param string $name
  52. * @param null $default_value
  53. * @return array|int|mixed|string
  54. * @author Tab
  55. * @date 2021/7/15 15:16
  56. */
  57. public static function get(string $type, string $name = '', $default_value = null)
  58. {
  59. if (!empty($name)) {
  60. $value = Config::where(['type' => $type, 'name' => $name])->value('value');
  61. if (!is_null($value)) {
  62. $json = json_decode($value, true);
  63. $value = json_last_error() === JSON_ERROR_NONE ? $json : $value;
  64. }
  65. if ($value) {
  66. return $value;
  67. }
  68. // 返回特殊值 0 '0'
  69. if ($value === 0 || $value === '0') {
  70. return $value;
  71. }
  72. // 返回默认值
  73. if ($default_value !== null) {
  74. return $default_value;
  75. }
  76. // 返回本地配置文件中的值
  77. return config('project.' . $type . '.' . $name);
  78. }
  79. // 取某个类型下的所有name的值
  80. $data = Config::where(['type' => $type])->column('value', 'name');
  81. foreach ($data as $k => $v) {
  82. $json = json_decode($v, true);
  83. if (json_last_error() === JSON_ERROR_NONE) {
  84. $data[$k] = $json;
  85. }
  86. }
  87. if ($data) {
  88. return $data;
  89. }
  90. }
  91. }