<?php
/**
* Normalizes environment variables for testing with retry logic.
*
* @param array $envVars An array of environment variable names and values.
* @param int $retries The number of retries for each variable.
* @return array A normalized array of environment variables.
*/
function normalizeEnvVars(array $envVars, int $retries = 3): array
{
$normalizedVars = [];
foreach ($envVars as $name => $value) {
$normalizedValue = normalizeValue($value);
$normalizedVars[$name] = $normalizedValue;
}
return $normalizedVars;
}
/**
* Normalizes a single environment variable value.
*
* @param string $value The environment variable value.
* @return string The normalized value.
*/
function normalizeValue(string $value): string
{
$value = trim($value); // Remove leading/trailing whitespace
if (empty($value)) {
return null; // or an empty string, depending on desired behavior
}
$value = str_replace(' ', '', $value); // Remove spaces
// Retry logic with a limited number of attempts
$retries = 0;
while ($retries < 3) {
if (is_numeric($value)) {
$value = (int)$value; // Convert to integer if possible
break;
}
// Attempt to convert to boolean
$boolValue = strtolower($value);
if ($boolValue === 'true') {
$value = true;
break;
} elseif ($boolValue === 'false') {
$value = false;
break;
}
$value = str_replace('-', '', $value); //Remove hyphens for numeric values
$value = str_replace('+', '', $value); //Remove plus signs for numeric values
$value = str_replace('=', '', $value); //Remove equals signs for numeric values
$retries++;
if($retries === 3){
//If it fails after 3 retries, return the original string.
break;
}
}
return $value;
}
//Example Usage
/*
$envVars = [
'DATABASE_URL' => 'mysql://user:password@host:port/database',
'PORT' => '8080',
'DEBUG' => 'true',
'API_KEY' => 'some-key=value',
'TIMEOUT' => '10s',
'EMPTY_VAR' => '',
'SPACES' => ' Lots of spaces ',
'NUMBER' => '123.45',
'BOOLEAN' => 'false',
'NEGATIVE_NUMBER' => '-123',
'HYPHEN_NUMBER' => '123-456',
];
$normalizedVars = normalizeEnvVars($envVars, 5);
print_r($normalizedVars);
*/
?>
Add your comment