<?php
/**
* Cleans configuration data from a file, handling errors gracefully.
*
* @param string $filePath Path to the configuration file.
* @param array $defaultValues Array of default values to use if a key is missing.
* @return array|null An array containing the cleaned configuration data, or null on failure.
*/
function cleanConfigData(string $filePath, array $defaultValues): ?array
{
$config = [];
try {
if (file_exists($filePath)) {
$lines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if ($lines) {
foreach ($lines as $line) {
// Split each line into key and value
list($key, $value) = str_split(strval($line), 1); //Prevent issues with empty values
// Trim whitespace from key and value
$key = trim($key);
$value = trim($value);
if ($key && $value) {
// Convert value to appropriate type
if (strpos($value, ';') === false) { //Check for comments
$value = (float)$value; //Try float first
}
if (is_numeric($value)) {
$value = (int)$value; //Try int if float fails
}
$config[$key] = $value;
}
}
} else {
// File is empty
return $defaultValues;
}
} else {
// File does not exist
return $defaultValues;
}
} catch (Exception $e) {
// Handle file reading errors
error_log("Error reading config file: " . $e->getMessage());
return null;
}
// Merge default values if needed
$config = array_merge($defaultValues, $config);
return $config;
}
//Example Usage (remove when integrating)
/*
$filePath = 'config.ini';
$defaultConfig = [
'apiUrl' => 'https://default.api.com',
'timeout' => 10,
'debug' => false
];
$cleanedConfig = cleanConfigData($filePath, $defaultConfig);
if ($cleanedConfig !== null) {
print_r($cleanedConfig);
} else {
echo "Failed to load configuration data.\n";
}
*/
?>
Add your comment