1. <?php
  2. /**
  3. * Wraps configuration file loading with error logging for maintenance tasks.
  4. *
  5. * @param string $filePath Path to the configuration file.
  6. * @param array $defaultValues Array of default values to use if the file fails to load.
  7. * @param string $logFile Path to the error log file.
  8. * @return array|null Configuration array on success, null on failure.
  9. */
  10. function loadConfigWithLogging(string $filePath, array $defaultValues = [], string $logFile = 'config_errors.log'): ?array
  11. {
  12. try {
  13. // Attempt to load the configuration file.
  14. $config = require($filePath);
  15. } catch (Exception $e) {
  16. // Log the error.
  17. error_log("Error loading configuration file: $filePath - " . $e->getMessage(), 3, $logFile);
  18. // Optionally, add more context to the log message.
  19. error_log("Original error message: " . $e->getTraceAsString(), 3, $logFile);
  20. // Return default values if loading fails.
  21. return $defaultValues;
  22. }
  23. // Check if the configuration is valid.
  24. if (!is_array($config)) {
  25. error_log("Configuration file $filePath returned an invalid value. Returning default values.", 3, $logFile);
  26. return $defaultValues;
  27. }
  28. return $config;
  29. }
  30. // Example Usage (within your maintenance task):
  31. // Define default configuration values.
  32. $defaultConfig = [
  33. 'database_host' => 'localhost',
  34. 'database_name' => 'default_db',
  35. 'api_key' => 'default_api_key',
  36. ];
  37. // Load the configuration file.
  38. $config = loadConfigWithLogging('config.php', $defaultConfig, 'maintenance_errors.log');
  39. // Check if the configuration was loaded successfully.
  40. if ($config === null) {
  41. // Handle the case where the configuration file failed to load.
  42. echo "Error: Configuration file failed to load. Using default values.\n";
  43. // Perform maintenance task using default values.
  44. } else {
  45. // Perform maintenance task using the loaded configuration.
  46. echo "Configuration loaded successfully.\n";
  47. print_r($config);
  48. // ... your maintenance task logic here ...
  49. }
  50. ?>

Add your comment