<?php
/**
* Wraps environment variable access with error handling and basic validation.
*
* @param string $key The name of the environment variable.
* @param callable $callback A callback function to execute if the environment variable is found.
* @param string $defaultValue The default value to use if the environment variable is not found or invalid.
* @return mixed The value of the environment variable or the default value.
*/
function getEnvironmentVariableSafe(string $key, callable $callback, string $defaultValue = ''): mixed
{
// Attempt to get the environment variable.
$value = getenv($key);
// Check if the environment variable exists.
if ($value === false) {
// Log the error (replace with your logging mechanism).
error_log("Environment variable '$key' not found. Using default value: '$defaultValue'");
return $defaultValue;
}
// Validate the environment variable (basic check for empty or null).
if (empty(trim($value))) {
error_log("Environment variable '$key' is empty or whitespace. Using default value: '$defaultValue'");
return $defaultValue;
}
// Call the callback function with the validated value.
return call_user_func($callback, trim($value));
}
//Example Usage:
/**
* Example callback function to convert the environment variable to an integer.
* Handles invalid integer values.
* @param string $value The value of the environment variable.
* @return int|null The integer value, or null if conversion fails.
*/
function convertToInteger(string $value): ?int
{
$value = trim($value);
$result = intval($value);
if ($result === 0 && $value === '0') {
return 0; // Handle the case where the value is '0'
}
if ($result === false) {
error_log("Invalid integer value for environment variable. Using default value: 10");
return 10;
}
return $result;
}
// Get the database host from the environment, converting to an integer if possible.
$dbHost = getEnvironmentVariableSafe('DB_HOST', 'convertToInteger', 'localhost');
// Get the port from the environment, converting to an integer if possible.
$dbPort = getEnvironmentVariableSafe('DB_PORT', 'convertToInteger', 3306);
// Get the API key from the environment, defaulting to 'default_key' if not found.
$apiKey = getEnvironmentVariableSafe('API_KEY', function(string $value) {
return $value;
}, 'default_key');
//Example of a variable that is not an integer
$timeout = getEnvironmentVariableSafe('TIMEOUT', 'convertToInteger', 60);
?>
Add your comment