Files
toolbox/app/Http/Controllers/Admin/ConfigController.php
2025-12-25 18:39:23 +08:00

107 lines
2.7 KiB
PHP

<?php
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Models\Config;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class ConfigController extends Controller
{
public function index(): JsonResponse
{
$configs = Config::query()
->orderBy('key')
->get();
return response()->json([
'success' => true,
'data' => [
'configs' => $configs,
],
]);
}
public function store(Request $request): JsonResponse
{
$data = $request->validate([
'key' => ['required', 'string', 'max:255', 'unique:configs,key'],
'value' => ['nullable', 'string'],
'description' => ['nullable', 'string', 'max:255'],
]);
$config = Config::query()->create([
'key' => $data['key'],
'value' => $this->decodeValue($data['value'] ?? null),
'description' => $data['description'] ?? null,
]);
return response()->json([
'success' => true,
'data' => [
'config' => $config,
],
]);
}
public function update(Request $request, Config $config): JsonResponse
{
$data = $request->validate([
'key' => [
'required',
'string',
'max:255',
Rule::unique('configs', 'key')->ignore($config->id),
],
'value' => ['nullable', 'string'],
'description' => ['nullable', 'string', 'max:255'],
]);
$config->update([
'key' => $data['key'],
'value' => $this->decodeValue($data['value'] ?? null),
'description' => $data['description'] ?? null,
]);
return response()->json([
'success' => true,
'data' => [
'config' => $config->refresh(),
],
]);
}
public function destroy(Config $config): JsonResponse
{
$config->delete();
return response()->json([
'success' => true,
]);
}
private function decodeValue(?string $raw): mixed
{
if ($raw === null) {
return null;
}
$trimmed = trim($raw);
if ($trimmed === '') {
return null;
}
$decoded = json_decode($trimmed, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw ValidationException::withMessages([
'value' => 'value 必须是合法 JSON',
]);
}
return $decoded;
}
}