1. <?php
  2. /**
  3. * Cleans configuration data from a file, handling errors gracefully.
  4. *
  5. * @param string $filePath Path to the configuration file.
  6. * @param array $defaultValues Array of default values to use if a key is missing.
  7. * @return array|null An array containing the cleaned configuration data, or null on failure.
  8. */
  9. function cleanConfigData(string $filePath, array $defaultValues): ?array
  10. {
  11. $config = [];
  12. try {
  13. if (file_exists($filePath)) {
  14. $lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
  15. if ($lines) {
  16. foreach ($lines as $line) {
  17. // Split each line into key and value
  18. list($key, $value) = str_split(strval($line), 1); //Prevent issues with empty values
  19. // Trim whitespace from key and value
  20. $key = trim($key);
  21. $value = trim($value);
  22. if ($key && $value) {
  23. // Convert value to appropriate type
  24. if (strpos($value, ';') === false) { //Check for comments
  25. $value = (float)$value; //Try float first
  26. }
  27. if (is_numeric($value)) {
  28. $value = (int)$value; //Try int if float fails
  29. }
  30. $config[$key] = $value;
  31. }
  32. }
  33. } else {
  34. // File is empty
  35. return $defaultValues;
  36. }
  37. } else {
  38. // File does not exist
  39. return $defaultValues;
  40. }
  41. } catch (Exception $e) {
  42. // Handle file reading errors
  43. error_log("Error reading config file: " . $e->getMessage());
  44. return null;
  45. }
  46. // Merge default values if needed
  47. $config = array_merge($defaultValues, $config);
  48. return $config;
  49. }
  50. //Example Usage (remove when integrating)
  51. /*
  52. $filePath = 'config.ini';
  53. $defaultConfig = [
  54. 'apiUrl' => 'https://default.api.com',
  55. 'timeout' => 10,
  56. 'debug' => false
  57. ];
  58. $cleanedConfig = cleanConfigData($filePath, $defaultConfig);
  59. if ($cleanedConfig !== null) {
  60. print_r($cleanedConfig);
  61. } else {
  62. echo "Failed to load configuration data.\n";
  63. }
  64. */
  65. ?>

Add your comment