Files
justice/www/html/Admin/api/sound-settings.php
T
2026-07-31 03:36:58 +00:00

92 lines
2.9 KiB
PHP

<?php
declare(strict_types=1);
/**
* ระดับเสียง Master / Music / SFX — อ่าน/เขียน Game/data/sound-settings.json
* ใช้ session Admin หลัก (ไม่ต้องล็อกอิน game_ai_admin แยก)
*
* GET -> { masterVol, musicVol, sfxVol } ค่า 0..1
* PUT -> body JSON เดียวกัน → บันทึก
*/
require __DIR__ . '/_common.php';
require_login();
require_tab('sound');
define('SOUND_SETTINGS_FILE', dirname(__DIR__, 2) . '/Game/data/sound-settings.json');
function sound_defaults(): array
{
return ['masterVol' => 1.0, 'musicVol' => 0.35, 'sfxVol' => 0.75];
}
function sound_clamp($v, float $default): float
{
$n = is_numeric($v) ? (float) $v : $default;
if (!is_finite($n)) {
return $default;
}
return max(0.0, min(1.0, $n));
}
function sound_read(): array
{
$base = sound_defaults();
if (!is_file(SOUND_SETTINGS_FILE)) {
return $base;
}
$raw = @file_get_contents(SOUND_SETTINGS_FILE);
$j = json_decode($raw ?: '{}', true);
if (!is_array($j)) {
return $base;
}
return [
'masterVol' => sound_clamp($j['masterVol'] ?? null, $base['masterVol']),
'musicVol' => sound_clamp($j['musicVol'] ?? null, $base['musicVol']),
'sfxVol' => sound_clamp($j['sfxVol'] ?? null, $base['sfxVol']),
];
}
function sound_write(array $s): bool
{
$dir = dirname(SOUND_SETTINGS_FILE);
if (!is_dir($dir) && !@mkdir($dir, 0755, true)) {
return false;
}
$json = json_encode($s, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
if ($json === false) {
return false;
}
$tmp = SOUND_SETTINGS_FILE . '.tmp.' . bin2hex(random_bytes(4));
if (file_put_contents($tmp, $json, LOCK_EX) === false) {
return false;
}
if (!rename($tmp, SOUND_SETTINGS_FILE)) {
@unlink($tmp);
return false;
}
return true;
}
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if ($method === 'GET') {
json_response(sound_read());
}
if ($method === 'PUT' || $method === 'POST') {
$body = require_json_body();
$cur = sound_read();
$next = [
'masterVol' => array_key_exists('masterVol', $body) ? sound_clamp($body['masterVol'], $cur['masterVol']) : $cur['masterVol'],
'musicVol' => array_key_exists('musicVol', $body) ? sound_clamp($body['musicVol'], $cur['musicVol']) : $cur['musicVol'],
'sfxVol' => array_key_exists('sfxVol', $body) ? sound_clamp($body['sfxVol'], $cur['sfxVol']) : $cur['sfxVol'],
];
if (!sound_write($next)) {
json_response(['ok' => false, 'error' => 'บันทึก sound-settings.json ไม่สำเร็จ'], 500);
}
json_response(['ok' => true, 'settings' => $next]);
}
json_response(['ok' => false, 'error' => 'Method not allowed'], 405);