1. <?php
  2. /**
  3. * Normalizes environment variables for testing with retry logic.
  4. *
  5. * @param array $envVars An array of environment variable names and values.
  6. * @param int $retries The number of retries for each variable.
  7. * @return array A normalized array of environment variables.
  8. */
  9. function normalizeEnvVars(array $envVars, int $retries = 3): array
  10. {
  11. $normalizedVars = [];
  12. foreach ($envVars as $name => $value) {
  13. $normalizedValue = normalizeValue($value);
  14. $normalizedVars[$name] = $normalizedValue;
  15. }
  16. return $normalizedVars;
  17. }
  18. /**
  19. * Normalizes a single environment variable value.
  20. *
  21. * @param string $value The environment variable value.
  22. * @return string The normalized value.
  23. */
  24. function normalizeValue(string $value): string
  25. {
  26. $value = trim($value); // Remove leading/trailing whitespace
  27. if (empty($value)) {
  28. return null; // or an empty string, depending on desired behavior
  29. }
  30. $value = str_replace(' ', '', $value); // Remove spaces
  31. // Retry logic with a limited number of attempts
  32. $retries = 0;
  33. while ($retries < 3) {
  34. if (is_numeric($value)) {
  35. $value = (int)$value; // Convert to integer if possible
  36. break;
  37. }
  38. // Attempt to convert to boolean
  39. $boolValue = strtolower($value);
  40. if ($boolValue === 'true') {
  41. $value = true;
  42. break;
  43. } elseif ($boolValue === 'false') {
  44. $value = false;
  45. break;
  46. }
  47. $value = str_replace('-', '', $value); //Remove hyphens for numeric values
  48. $value = str_replace('+', '', $value); //Remove plus signs for numeric values
  49. $value = str_replace('=', '', $value); //Remove equals signs for numeric values
  50. $retries++;
  51. if($retries === 3){
  52. //If it fails after 3 retries, return the original string.
  53. break;
  54. }
  55. }
  56. return $value;
  57. }
  58. //Example Usage
  59. /*
  60. $envVars = [
  61. 'DATABASE_URL' => 'mysql://user:password@host:port/database',
  62. 'PORT' => '8080',
  63. 'DEBUG' => 'true',
  64. 'API_KEY' => 'some-key=value',
  65. 'TIMEOUT' => '10s',
  66. 'EMPTY_VAR' => '',
  67. 'SPACES' => ' Lots of spaces ',
  68. 'NUMBER' => '123.45',
  69. 'BOOLEAN' => 'false',
  70. 'NEGATIVE_NUMBER' => '-123',
  71. 'HYPHEN_NUMBER' => '123-456',
  72. ];
  73. $normalizedVars = normalizeEnvVars($envVars, 5);
  74. print_r($normalizedVars);
  75. */
  76. ?>

Add your comment