1. <?php
  2. /**
  3. * Parses user input arguments with retry logic.
  4. *
  5. * @param array $expected_args An array of expected arguments and their types.
  6. * Example: ['param1' => 'string', 'param2' => 'int']
  7. * @param int $max_retries The maximum number of retry attempts.
  8. * @param int $retry_interval The interval in seconds between retries.
  9. * @param callable $function The function to call with the parsed arguments.
  10. * @return bool True on success, false on failure after all retries.
  11. */
  12. function parseAndRetry(array $expected_args, int $max_retries, int $retry_interval, callable $function): bool
  13. {
  14. $args = [];
  15. $errors = [];
  16. // Get user input arguments
  17. $input_args = getopt(":", array_keys($expected_args));
  18. // Validate arguments and retry if necessary
  19. for ($i = 0; $i < $max_retries; $i++) {
  20. $valid = true;
  21. foreach ($expected_args as $param => $type) {
  22. if (!isset($input_args[$param])) {
  23. $valid = false;
  24. $errors[] = "Missing argument: $param";
  25. break;
  26. }
  27. $value = $input_args[$param];
  28. if (is_string($type) && !is_string($value)) {
  29. $valid = false;
  30. $errors[] = "Argument $param should be a string.";
  31. break;
  32. }
  33. if (is_int($type) && !is_int($value)) {
  34. $valid = false;
  35. $errors[] = "Argument $param should be an integer.";
  36. break;
  37. }
  38. }
  39. if ($valid) {
  40. // Arguments are valid, call the function
  41. $args = $input_args;
  42. if ($function($args)) {
  43. return true; // Success
  44. } else {
  45. // Function failed, retry
  46. if ($i < $max_retries - 1) {
  47. echo "Retry attempt $i+1 of $max_retries in $retry_interval seconds...\n";
  48. sleep($retry_interval);
  49. } else {
  50. echo "Failed after $max_retries retries.\n";
  51. return false; // Failure after all retries
  52. }
  53. }
  54. } else {
  55. // Arguments are invalid, retry
  56. if ($i < $max_retries - 1) {
  57. echo "Invalid arguments. Retry attempt $i+1 of $max_retries in $retry_interval seconds...\n";
  58. sleep($retry_interval);
  59. } else {
  60. echo "Failed after $max_retries retries with invalid arguments.\n";
  61. return false; // Failure after all retries
  62. }
  63. }
  64. }
  65. return false; // Should not reach here, but added for completeness
  66. }
  67. // Example usage:
  68. /*
  69. function my_function(array $args) {
  70. echo "Processing with arguments: " . implode(", ", $args) . "\n";
  71. return true;
  72. }
  73. $expected_args = ['name' => 'string', 'age' => 'int'];
  74. $max_retries = 3;
  75. $retry_interval = 2;
  76. if (parseAndRetry($expected_args, $max_retries, $retry_interval, 'my_function')) {
  77. echo "Operation successful!\n";
  78. } else {
  79. echo "Operation failed.\n";
  80. }
  81. */
  82. ?>

Add your comment