language(request()->lang_id) ->enabled() ->order(['sort' => 'asc', 'id' => 'desc']) ->select() ->toArray(); if (empty($groups)) { return error('配置分组不存在'); } // 根据分组获取配置项 $configs = SysConfigModel::field([ 'id', 'group_id', 'title', 'name', 'value', 'extra', 'type', 'remark' ]) ->groupId(array_column($groups, 'id')) ->order(['sort' => 'asc', 'id' => 'desc']) ->select() ->each(function($item) { // 修改字段为null的输出为空字符串 $keys = array_keys($item->toArray()); foreach ($keys as $key) { if (is_null($item[$key])) { $item[$key] = ''; } } return $item; }) ->toArray(); if (empty($configs)) { return error('配置项不存在'); } // 处理附加配置项及联动项 $config_name_map = []; foreach ($configs as $config) { unset($config['group_id']); $config_name_map[$config['name']] = $config; } $configs = $this->handleExtra($configs, $config_name_map); // 组合数据 $config_group_map = []; foreach ($configs as $config) { $group_id = $config['group_id']; unset($config['group_id']); $config_group_map[$group_id][] = $config; } // 组合分组和配置项 foreach ($groups as &$group) { $group['configs'] = $config_group_map[$group['id']] ?? []; } unset($group); return success('获取成功', $groups); } // 处理配置联动项数据 private function handleExtra($data, $map) { $ret = []; $need_delete_names = []; foreach ($data as $val) { if (!empty($val['extra'])) { $extra = explode(PHP_EOL, $val['extra']); foreach ($extra as $v) { if (preg_match('/^([^:]+):(.+)\[(.+)\]$/i', $v, $match)) { $item = [ 'name' => $match[2], 'value' => $match[1] ]; if (isset($match[3])) { $children = []; $names = explode(',', $match[3]); foreach ($names as $name) { $name = trim(trim($name), "'"); $need_delete_names[] = $name; if (!empty($map[$name])) { $children[] = $map[$name]; } } // 处理子级 if (!empty($children)) { $item['children'] = $this->handleExtra($children, $map); } } unset($val['extra']); if (!isset($val['extras'])) { $val['extras'] = []; } $val['extras'][] = $item; } } } $ret[] = $val; } // 删除多余的配置项 foreach ($ret as $k => $it) { if (in_array($it['name'], $need_delete_names)) { unset($ret[$k]); } } return $ret; } // 更新配置 public function update() { $put = request()->put(); if (empty($put)) { return error('参数错误'); } $validate = validate([ 'id' => 'require|integer', 'value' => 'max:255' ]) ->message([ 'id.require' => '配置项ID不能为空', 'id.integer' => '配置项ID必须是整数', 'value.max' => '配置值不能超过255个字符' ]); foreach ($put as $val) { if (!$validate->check($val)) { return error($validate->getError()); } } $configs = (new SysConfigModel)->saveAll($put); if ($configs->isEmpty()) { return error('操作失败'); } return success('操作成功'); } }