Files
nl-admin-api/app/Service/SystemConfigService.php

93 lines
2.5 KiB
PHP
Raw Normal View History

2026-08-10 15:51:00 +08:00
<?php
namespace App\Service;
use App\BaseApp\BaseService;
use App\Models\SystemConfigModel;
/**
* 系统配置 Service key 读写 kv AI 运行时等模块复用
*/
class SystemConfigService extends BaseService
{
public function __construct()
{
// 配置读写不依赖登录态(工厂解析时可能被其他 Service 调用)
$this->isAuth = false;
parent::__construct();
$this->model = SystemConfigModel::class;
}
/**
* 读取配置值;不存在时返回默认值
* 为什么:业务侧只关心 value不关心行结构
*/
public function getValue(string $key, mixed $default = null): mixed
{
$key = trim($key);
if ($key === '') {
return $default;
}
$row = SystemConfigModel::where('key', $key)
->where('deleted_at', 0)
->first();
if (!$row) {
return $default;
}
$value = $row->value;
if ($value === null) {
return $default;
}
return $value;
}
/**
* 写入/更新配置;存在则更新,不存在则插入
* 为什么用 upsert配置项数量少 key 幂等更稳
*/
public function setValue(string $key, mixed $value, string $remark = ''): bool
{
$key = trim($key);
if ($key === '') {
$this->utils->errorThrow('配置键不能为空');
}
if (is_array($value) || is_object($value)) {
$value = json_encode($value, JSON_UNESCAPED_UNICODE);
}
$value = (string) $value;
$now = time();
$row = SystemConfigModel::where('key', $key)
->where('deleted_at', 0)
->first();
if ($row) {
$row->value = $value;
if ($remark !== '') {
$row->remark = $remark;
}
$row->updated_at = $now;
return (bool) $row->save();
}
return (bool) SystemConfigModel::insert([
'key' => $key,
'value' => $value,
'remark' => $remark,
'created_at' => $now,
'updated_at' => 0,
'deleted_at' => 0,
]);
}
/**
* 批量写入配置
*
* @param array<string, mixed> $pairs key => value
*/
public function setValues(array $pairs): bool
{
foreach ($pairs as $key => $value) {
$this->setValue((string) $key, $value);
}
return true;
}
}