AI代码生成工具
This commit is contained in:
92
app/Service/SystemConfigService.php
Normal file
92
app/Service/SystemConfigService.php
Normal file
@@ -0,0 +1,92 @@
|
||||
<?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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user