Config.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Models;
  4. use Illuminate\Database\Query\Builder;
  5. /**
  6. * @property int $id 配置ID
  7. * @property string $item 配置项
  8. * @property string $value 配置值
  9. * @property string $class 配置类别
  10. * @property string $is_public 是否为公共参数
  11. * @property string $default 默认值
  12. * @property string $mark 备注
  13. *
  14. * @mixin Builder
  15. */
  16. final class Config extends Model
  17. {
  18. protected $connection = 'default';
  19. protected $table = 'config';
  20. public static function obtain($item): bool|int|string
  21. {
  22. $config = (new Config())->where('item', $item)->first();
  23. return match ($config->type) {
  24. 'bool' => (bool) $config->value,
  25. 'int' => (int) $config->value,
  26. default => (string) $config->value,
  27. };
  28. }
  29. public static function getClass($class): array
  30. {
  31. $configs = [];
  32. $all_configs = (new Config())->where('class', $class)->get();
  33. foreach ($all_configs as $config) {
  34. if ($config->type === 'bool') {
  35. $configs[$config->item] = (bool) $config->value;
  36. } elseif ($config->type === 'int') {
  37. $configs[$config->item] = (int) $config->value;
  38. } else {
  39. $configs[$config->item] = (string) $config->value;
  40. }
  41. }
  42. return $configs;
  43. }
  44. public static function getItemListByClass($class): array
  45. {
  46. $items = [];
  47. $all_configs = (new Config())->where('class', $class)->get();
  48. foreach ($all_configs as $config) {
  49. $items[] = $config->item;
  50. }
  51. return $items;
  52. }
  53. public static function getPublicConfig(): array
  54. {
  55. $configs = [];
  56. $all_configs = (new Config())->where('is_public', '1')->get();
  57. foreach ($all_configs as $config) {
  58. if ($config->type === 'bool') {
  59. $configs[$config->item] = (bool) $config->value;
  60. } elseif ($config->type === 'int') {
  61. $configs[$config->item] = (int) $config->value;
  62. } else {
  63. $configs[$config->item] = (string) $config->value;
  64. }
  65. }
  66. return $configs;
  67. }
  68. public static function set($item, $value): bool
  69. {
  70. $config = (new Config())->where('item', $item)->first();
  71. if ($config->tpye === 'array') {
  72. $config->value = json_encode($value);
  73. } else {
  74. $config->value = $value;
  75. }
  76. return $config->save();
  77. }
  78. }