| Current Path : /home/seto/indexator.pm/src/Settings/ |
| Current File : /home/seto/indexator.pm/src/Settings/ConfigWriter.php |
<?php
namespace App\Settings;
class ConfigWriter
{
public function __construct(private string $configPath) {}
/**
* Update specific keys in config.php by rewriting the matching lines.
* Only handles scalar string/int values in the flat return array format.
*
* @param array<string, string|int> $values
*/
public function update(array $values): void
{
if (!is_writable($this->configPath)) {
throw new \RuntimeException('config/config.php is not writable by the web server.');
}
$content = file_get_contents($this->configPath);
if ($content === false) {
throw new \RuntimeException('Cannot read config/config.php.');
}
foreach ($values as $key => $value) {
$quotedKey = preg_quote($key, '/');
$newValue = (string) $value;
// Use callback to avoid $ in replacement being treated as backreference
$content = preg_replace_callback(
"/('$quotedKey'\s*=>\s*)('[^']*'|\d+)(,.*)/",
static function (array $m) use ($newValue): string {
// Escape single quotes and backslashes inside the value
$safe = str_replace(['\\', "'"], ['\\\\', "\\'"], $newValue);
return $m[1] . "'" . $safe . "'" . $m[3];
},
$content
);
}
if (file_put_contents($this->configPath, $content) === false) {
throw new \RuntimeException('Failed to write config/config.php.');
}
// Invalidate opcache if available
if (function_exists('opcache_invalidate')) {
opcache_invalidate($this->configPath, true);
}
}
}