<?php
/**
* Parses user input arguments with retry logic.
*
* @param array $expected_args An array of expected arguments and their types.
* Example: ['param1' => 'string', 'param2' => 'int']
* @param int $max_retries The maximum number of retry attempts.
* @param int $retry_interval The interval in seconds between retries.
* @param callable $function The function to call with the parsed arguments.
* @return bool True on success, false on failure after all retries.
*/
function parseAndRetry(array $expected_args, int $max_retries, int $retry_interval, callable $function): bool
{
$args = [];
$errors = [];
// Get user input arguments
$input_args = getopt(":", array_keys($expected_args));
// Validate arguments and retry if necessary
for ($i = 0; $i < $max_retries; $i++) {
$valid = true;
foreach ($expected_args as $param => $type) {
if (!isset($input_args[$param])) {
$valid = false;
$errors[] = "Missing argument: $param";
break;
}
$value = $input_args[$param];
if (is_string($type) && !is_string($value)) {
$valid = false;
$errors[] = "Argument $param should be a string.";
break;
}
if (is_int($type) && !is_int($value)) {
$valid = false;
$errors[] = "Argument $param should be an integer.";
break;
}
}
if ($valid) {
// Arguments are valid, call the function
$args = $input_args;
if ($function($args)) {
return true; // Success
} else {
// Function failed, retry
if ($i < $max_retries - 1) {
echo "Retry attempt $i+1 of $max_retries in $retry_interval seconds...\n";
sleep($retry_interval);
} else {
echo "Failed after $max_retries retries.\n";
return false; // Failure after all retries
}
}
} else {
// Arguments are invalid, retry
if ($i < $max_retries - 1) {
echo "Invalid arguments. Retry attempt $i+1 of $max_retries in $retry_interval seconds...\n";
sleep($retry_interval);
} else {
echo "Failed after $max_retries retries with invalid arguments.\n";
return false; // Failure after all retries
}
}
}
return false; // Should not reach here, but added for completeness
}
// Example usage:
/*
function my_function(array $args) {
echo "Processing with arguments: " . implode(", ", $args) . "\n";
return true;
}
$expected_args = ['name' => 'string', 'age' => 'int'];
$max_retries = 3;
$retry_interval = 2;
if (parseAndRetry($expected_args, $max_retries, $retry_interval, 'my_function')) {
echo "Operation successful!\n";
} else {
echo "Operation failed.\n";
}
*/
?>
Add your comment