<?php
/**
* Enforces limits on command-line options with manual overrides.
*
* This script provides a temporary solution for limiting command-line option values.
* It allows for manual overrides using environment variables.
*/
/**
* Function to validate and limit a command-line option.
*
* @param string $option_name The name of the option.
* @param string $option_value The value of the option from the command line.
* @param int|null $max_value The maximum allowed value. Null if no limit.
* @param string|null $override_env The environment variable to override the limit.
* @return string|false The validated option value, or false if validation fails.
*/
function validateOption(string $option_name, string $option_value, ?int $max_value, ?string $override_env): string|false
{
// Check if the override environment variable is set.
if ($override_env && getenv($override_env) !== null) {
$override_value = (int)getenv($override_env);
if ($override_value === false) {
error_log("Invalid value for override environment variable: " . $override_env);
return false;
}
$option_value = $override_value;
}
// Validate the option value based on the maximum value.
if ($max_value !== null && (int)$option_value > $max_value) {
error_log("Option '$option_name' value exceeds maximum allowed value: $max_value.");
return false;
}
return $option_value;
}
// Example usage:
$max_value = 100; // Maximum allowed value for the 'amount' option.
$override_env = 'AMOUNT_OVERRIDE'; // Environment variable to override the limit.
// Simulate command-line option parsing (replace with your actual parsing logic).
$amount = $_GET['amount'] ?? 50; // Default value if not provided.
// Validate the 'amount' option.
$validated_amount = validateOption('amount', $amount, $max_value, $override_env);
if ($validated_amount !== false) {
echo "Validated amount: " . $validated_amount . "\n";
// Use the validated amount.
} else {
echo "Invalid amount provided.\n";
}
//Another example
$filename = $_GET['filename'] ?? 'default.txt';
//Validate filename
$validated_filename = validateOption('filename', $filename, null, $override_env);
if ($validated_filename !== false) {
echo "Validated filename: " . $validated_filename . "\n";
} else {
echo "Invalid filename provided.\n";
}
?>
Add your comment