<?php
/**
* Validates environment variables.
*
* @param array $expectedVariables An array of environment variable names to validate.
* @param callable $validator A callback function that takes the variable name and value as arguments and returns true on success, false on failure.
* @return array An array of validation results, where each element is an array containing the variable name and validation status.
*/
function validateEnvironmentVariables(array $expectedVariables, callable $validator): array
{
$results = [];
foreach ($expectedVariables as $variableName) {
$value = getenv($variableName); // Get the environment variable value
if ($value === null) {
$results[] = ["variable" => $variableName, "status" => "missing"]; // Variable is missing
continue;
}
if (!$validator($variableName, $value)) {
$results[] = ["variable" => $variableName, "status" => "invalid"]; // Validation failed
} else {
$results[] = ["variable" => $variableName, "status" => "valid"]; // Validation passed
}
}
return $results;
}
// Example validator function (customize as needed)
function validateStringLength(string $variableName, string $value, int $minLength = 1, int $maxLength = PHP_INT_MAX): bool
{
return strlen($value) >= $minLength && strlen($value) <= $maxLength;
}
// Example usage:
//$variablesToValidate = ["API_KEY", "DATABASE_URL", "DEBUG"];
//$validationResults = validateEnvironmentVariables($variablesToValidate, function (string $name, string $value) {
// return validateStringLength($name, $value, 10, 255); // Validate string length
//});
//
//print_r($validationResults);
?>
Add your comment