52 lines
1.7 KiB
PHP
52 lines
1.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
final class BackendRuntimeConfig
|
|
{
|
|
public static function sync(Settings $settings, string $backendScript, string $statePath = Settings::CONFIG_DIR . '/backend-state.json', string $errorLog = ''): void
|
|
{
|
|
$desired = $settings->backendMode();
|
|
$current = self::currentBackend($statePath);
|
|
if ($current === $desired) {
|
|
return;
|
|
}
|
|
|
|
if (!is_file($backendScript) || !is_executable($backendScript)) {
|
|
self::log($errorLog, 'Backend script not executable: ' . $backendScript);
|
|
return;
|
|
}
|
|
|
|
$process = proc_open([$backendScript, $desired], [['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']], $pipes);
|
|
if (!is_resource($process)) {
|
|
self::log($errorLog, 'Could not start backend script.');
|
|
return;
|
|
}
|
|
fclose($pipes[0]);
|
|
stream_get_contents($pipes[1]);
|
|
$stderr = stream_get_contents($pipes[2]);
|
|
fclose($pipes[1]);
|
|
fclose($pipes[2]);
|
|
$code = proc_close($process);
|
|
if ($code !== 0) {
|
|
self::log($errorLog, 'Backend script failed with code ' . $code . ': ' . trim($stderr));
|
|
}
|
|
}
|
|
|
|
private static function currentBackend(string $statePath): string
|
|
{
|
|
if (!is_file($statePath)) {
|
|
return '';
|
|
}
|
|
$data = json_decode((string)file_get_contents($statePath), true);
|
|
return is_array($data) ? (string)($data['active_backend'] ?? '') : '';
|
|
}
|
|
|
|
private static function log(string $errorLog, string $message): void
|
|
{
|
|
if ($errorLog === '') {
|
|
return;
|
|
}
|
|
@error_log('[' . date('c') . '] BACKEND_SYNC ' . $message . "\n", 3, $errorLog);
|
|
}
|
|
}
|