1. <?php
  2. /**
  3. * Wraps environment variable access with error handling and basic validation.
  4. *
  5. * @param string $key The name of the environment variable.
  6. * @param callable $callback A callback function to execute if the environment variable is found.
  7. * @param string $defaultValue The default value to use if the environment variable is not found or invalid.
  8. * @return mixed The value of the environment variable or the default value.
  9. */
  10. function getEnvironmentVariableSafe(string $key, callable $callback, string $defaultValue = ''): mixed
  11. {
  12. // Attempt to get the environment variable.
  13. $value = getenv($key);
  14. // Check if the environment variable exists.
  15. if ($value === false) {
  16. // Log the error (replace with your logging mechanism).
  17. error_log("Environment variable '$key' not found. Using default value: '$defaultValue'");
  18. return $defaultValue;
  19. }
  20. // Validate the environment variable (basic check for empty or null).
  21. if (empty(trim($value))) {
  22. error_log("Environment variable '$key' is empty or whitespace. Using default value: '$defaultValue'");
  23. return $defaultValue;
  24. }
  25. // Call the callback function with the validated value.
  26. return call_user_func($callback, trim($value));
  27. }
  28. //Example Usage:
  29. /**
  30. * Example callback function to convert the environment variable to an integer.
  31. * Handles invalid integer values.
  32. * @param string $value The value of the environment variable.
  33. * @return int|null The integer value, or null if conversion fails.
  34. */
  35. function convertToInteger(string $value): ?int
  36. {
  37. $value = trim($value);
  38. $result = intval($value);
  39. if ($result === 0 && $value === '0') {
  40. return 0; // Handle the case where the value is '0'
  41. }
  42. if ($result === false) {
  43. error_log("Invalid integer value for environment variable. Using default value: 10");
  44. return 10;
  45. }
  46. return $result;
  47. }
  48. // Get the database host from the environment, converting to an integer if possible.
  49. $dbHost = getEnvironmentVariableSafe('DB_HOST', 'convertToInteger', 'localhost');
  50. // Get the port from the environment, converting to an integer if possible.
  51. $dbPort = getEnvironmentVariableSafe('DB_PORT', 'convertToInteger', 3306);
  52. // Get the API key from the environment, defaulting to 'default_key' if not found.
  53. $apiKey = getEnvironmentVariableSafe('API_KEY', function(string $value) {
  54. return $value;
  55. }, 'default_key');
  56. //Example of a variable that is not an integer
  57. $timeout = getEnvironmentVariableSafe('TIMEOUT', 'convertToInteger', 60);
  58. ?>

Add your comment