1. <?php
  2. /**
  3. * Validates environment variables for hypothesis validation, allowing manual overrides.
  4. *
  5. * @param array $expectedVariables An array of expected environment variable names and their expected values.
  6. * @param array $manualOverrides An array of manually overridden environment variable names and their values.
  7. * @return bool True if all validated environment variables are valid, false otherwise.
  8. */
  9. function validateEnvironmentVariables(array $expectedVariables, array $manualOverrides = []): bool
  10. {
  11. foreach ($expectedVariables as $variableName => $expectedValue) {
  12. // Get the environment variable value, using the manual override if available.
  13. $value = getenv($variableName);
  14. //If no environment variable exists, we'll skip this validation.
  15. if ($value === null) {
  16. continue;
  17. }
  18. // Apply manual override if present.
  19. if (isset($manualOverrides[$variableName])) {
  20. $value = $manualOverrides[$variableName];
  21. }
  22. // Check if the environment variable value matches the expected value.
  23. if ($value !== $expectedValue) {
  24. error_log("Environment variable '$variableName' is invalid. Expected: '$expectedValue', Actual: '$value'");
  25. return false; // Validation failed.
  26. }
  27. }
  28. return true; // All validation checks passed.
  29. }
  30. // Example Usage
  31. /*
  32. $expectedVars = [
  33. 'API_KEY' => 'your_api_key',
  34. 'DATABASE_URL' => 'mysql://user:password@host:port/database',
  35. 'DEBUG_MODE' => 'true',
  36. ];
  37. $manualOverrides = [
  38. 'DEBUG_MODE' => 'false', // Example of manual override
  39. ];
  40. if (validateEnvironmentVariables($expectedVars, $manualOverrides)) {
  41. echo "Environment variables are valid.\n";
  42. } else {
  43. echo "Environment variables are invalid.\n";
  44. }
  45. */
  46. ?>

Add your comment