<?php
/**
* Backs up configuration files for hypothesis validation with manual overrides.
*
* @param array $config_files An array of configuration file paths.
* @param array $overrides An array of key-value pairs to override in the backups.
* @param string $backup_dir The directory to store the backups.
* @return bool True on success, false on failure.
*/
function backupConfiguration(array $config_files, array $overrides, string $backup_dir): bool
{
// Ensure backup directory exists
if (!is_dir($backup_dir)) {
mkdir($backup_dir, 0777, true); // Create directory recursively
}
foreach ($config_files as $config_file) {
// Sanitize the filename
$filename = basename($config_file);
$backup_file = $backup_dir . '/' . $filename . '.bak';
try {
// Backup the file
copy($config_file, $backup_file);
// Apply overrides if needed
if (!empty($overrides)) {
$content = file_get_contents($backup_file);
if ($content !== false) {
foreach ($overrides as $key => $value) {
$content = str_replace($key, $value, $content);
}
file_put_contents($backup_file, $content);
} else {
error_log("Error reading file: " . $config_file);
return false;
}
}
} catch (Exception $e) {
error_log("Error backing up file " . $config_file . ": " . $e->getMessage());
return false;
}
}
return true;
}
// Example Usage (replace with your actual values)
/*
$config_files = [
'config.ini',
'settings.json',
'data/parameters.yaml',
];
$overrides = [
'database_host' => 'new_host',
'api_key' => 'new_api_key',
];
$backup_dir = 'backups';
if (backupConfiguration($config_files, $overrides, $backup_dir)) {
echo "Configuration files backed up successfully.\n";
} else {
echo "Configuration file backup failed.\n";
}
*/
?>
Add your comment