<?php
/**
* Wraps configuration file loading with error logging for maintenance tasks.
*
* @param string $filePath Path to the configuration file.
* @param array $defaultValues Array of default values to use if the file fails to load.
* @param string $logFile Path to the error log file.
* @return array|null Configuration array on success, null on failure.
*/
function loadConfigWithLogging(string $filePath, array $defaultValues = [], string $logFile = 'config_errors.log'): ?array
{
try {
// Attempt to load the configuration file.
$config = require($filePath);
} catch (Exception $e) {
// Log the error.
error_log("Error loading configuration file: $filePath - " . $e->getMessage(), 3, $logFile);
// Optionally, add more context to the log message.
error_log("Original error message: " . $e->getTraceAsString(), 3, $logFile);
// Return default values if loading fails.
return $defaultValues;
}
// Check if the configuration is valid.
if (!is_array($config)) {
error_log("Configuration file $filePath returned an invalid value. Returning default values.", 3, $logFile);
return $defaultValues;
}
return $config;
}
// Example Usage (within your maintenance task):
// Define default configuration values.
$defaultConfig = [
'database_host' => 'localhost',
'database_name' => 'default_db',
'api_key' => 'default_api_key',
];
// Load the configuration file.
$config = loadConfigWithLogging('config.php', $defaultConfig, 'maintenance_errors.log');
// Check if the configuration was loaded successfully.
if ($config === null) {
// Handle the case where the configuration file failed to load.
echo "Error: Configuration file failed to load. Using default values.\n";
// Perform maintenance task using default values.
} else {
// Perform maintenance task using the loaded configuration.
echo "Configuration loaded successfully.\n";
print_r($config);
// ... your maintenance task logic here ...
}
?>
Add your comment