<?php
/**
* Checks command-line options against predefined constraints.
* Supports a dry-run mode.
*
* @param array $argv Command-line arguments.
* @param array $expectedOptions Array of expected options and their constraints.
* @param bool $dryRun Whether to perform a dry run (no actual actions).
* @return array An array of validation errors. Empty array if valid.
*/
function validateCommandLineOptions(array $argv, array $expectedOptions, bool $dryRun = false): array
{
$errors = [];
foreach ($expectedOptions as $optionName => $constraints) {
// Check if the option is present
if (!isset($argv[$optionName])) {
if ($constraints['required']) {
$errors[] = "Option '$optionName' is required.";
}
continue; // Skip to the next option
}
$optionValue = $argv[$optionName];
// Validate the option value based on the constraints
if (isset($constraints['type'])) {
switch ($constraints['type']) {
case 'integer':
if (!is_numeric($optionValue) || !filter_var($optionValue, FILTER_VALIDATE_INT)) {
$errors[] = "Option '$optionName' must be an integer.";
}
break;
case 'float':
if (!is_numeric($optionValue) || !filter_var($optionValue, FILTER_VALIDATE_FLOAT)) {
$errors[] = "Option '$optionName' must be a float.";
}
break;
case 'string':
//Simple string validation. Could add length constraints, etc.
if(!is_string($optionValue)){
$errors[] = "Option '$optionName' must be a string.";
}
break;
default:
$errors[] = "Unsupported type: " . $constraints['type'] . " for option '$optionName'.";
}
}
if (isset($constraints['allowedValues'])) {
if (!in_array($optionValue, $constraints['allowedValues'])) {
$errors[] = "Option '$optionName' must be one of: " . implode(', ', $constraints['allowedValues']);
}
}
if (isset($constraints['pattern'])) {
if (!preg_match($constraints['pattern'], $optionValue)) {
$errors[] = "Option '$optionName' does not match pattern: " . $constraints['pattern'];
}
}
}
return $errors;
}
// Example usage (for testing):
/*
$argv = ['--name', 'John Doe', '--age', '30', '--mode', 'debug'];
$expectedOptions = [
'--name' => ['required' => true, 'type' => 'string'],
'--age' => ['required' => true, 'type' => 'integer'],
'--mode' => ['required' => false, 'allowedValues' => ['debug', 'info', 'warning', 'error'], 'default' => 'info'],
];
$errors = validateCommandLineOptions($argv, $expectedOptions, false); // Run validation
if (empty($errors)) {
echo "Command-line options are valid.\n";
} else {
echo "Validation errors:\n";
foreach ($errors as $error) {
echo "- " . $error . "\n";
}
}
$argv2 = ['--name', 'John Doe', '--age', 'abc', '--mode', 'debug'];
$errors2 = validateCommandLineOptions($argv2, $expectedOptions, false); // Run validation
if (empty($errors2)) {
echo "Command-line options are valid.\n";
} else {
echo "Validation errors:\n";
foreach ($errors2 as $error) {
echo "- " . $error . "\n";
}
}
*/
?>
Add your comment