1. <?php
  2. /**
  3. * Validates environment variables.
  4. *
  5. * @param array $expectedVariables An array of environment variable names to validate.
  6. * @param callable $validator A callback function that takes the variable name and value as arguments and returns true on success, false on failure.
  7. * @return array An array of validation results, where each element is an array containing the variable name and validation status.
  8. */
  9. function validateEnvironmentVariables(array $expectedVariables, callable $validator): array
  10. {
  11. $results = [];
  12. foreach ($expectedVariables as $variableName) {
  13. $value = getenv($variableName); // Get the environment variable value
  14. if ($value === null) {
  15. $results[] = ["variable" => $variableName, "status" => "missing"]; // Variable is missing
  16. continue;
  17. }
  18. if (!$validator($variableName, $value)) {
  19. $results[] = ["variable" => $variableName, "status" => "invalid"]; // Validation failed
  20. } else {
  21. $results[] = ["variable" => $variableName, "status" => "valid"]; // Validation passed
  22. }
  23. }
  24. return $results;
  25. }
  26. // Example validator function (customize as needed)
  27. function validateStringLength(string $variableName, string $value, int $minLength = 1, int $maxLength = PHP_INT_MAX): bool
  28. {
  29. return strlen($value) >= $minLength && strlen($value) <= $maxLength;
  30. }
  31. // Example usage:
  32. //$variablesToValidate = ["API_KEY", "DATABASE_URL", "DEBUG"];
  33. //$validationResults = validateEnvironmentVariables($variablesToValidate, function (string $name, string $value) {
  34. // return validateStringLength($name, $value, 10, 255); // Validate string length
  35. //});
  36. //
  37. //print_r($validationResults);
  38. ?>

Add your comment