1. <?php
  2. /**
  3. * Backs up configuration files for hypothesis validation with manual overrides.
  4. *
  5. * @param array $config_files An array of configuration file paths.
  6. * @param array $overrides An array of key-value pairs to override in the backups.
  7. * @param string $backup_dir The directory to store the backups.
  8. * @return bool True on success, false on failure.
  9. */
  10. function backupConfiguration(array $config_files, array $overrides, string $backup_dir): bool
  11. {
  12. // Ensure backup directory exists
  13. if (!is_dir($backup_dir)) {
  14. mkdir($backup_dir, 0777, true); // Create directory recursively
  15. }
  16. foreach ($config_files as $config_file) {
  17. // Sanitize the filename
  18. $filename = basename($config_file);
  19. $backup_file = $backup_dir . '/' . $filename . '.bak';
  20. try {
  21. // Backup the file
  22. copy($config_file, $backup_file);
  23. // Apply overrides if needed
  24. if (!empty($overrides)) {
  25. $content = file_get_contents($backup_file);
  26. if ($content !== false) {
  27. foreach ($overrides as $key => $value) {
  28. $content = str_replace($key, $value, $content);
  29. }
  30. file_put_contents($backup_file, $content);
  31. } else {
  32. error_log("Error reading file: " . $config_file);
  33. return false;
  34. }
  35. }
  36. } catch (Exception $e) {
  37. error_log("Error backing up file " . $config_file . ": " . $e->getMessage());
  38. return false;
  39. }
  40. }
  41. return true;
  42. }
  43. // Example Usage (replace with your actual values)
  44. /*
  45. $config_files = [
  46. 'config.ini',
  47. 'settings.json',
  48. 'data/parameters.yaml',
  49. ];
  50. $overrides = [
  51. 'database_host' => 'new_host',
  52. 'api_key' => 'new_api_key',
  53. ];
  54. $backup_dir = 'backups';
  55. if (backupConfiguration($config_files, $overrides, $backup_dir)) {
  56. echo "Configuration files backed up successfully.\n";
  57. } else {
  58. echo "Configuration file backup failed.\n";
  59. }
  60. */
  61. ?>

Add your comment