1. <?php
  2. /**
  3. * Loads resources from CLI arguments with retry logic.
  4. *
  5. * @param array $expectedArgs An array of expected command-line arguments and their types.
  6. * @param int $maxRetries The maximum number of retry attempts.
  7. * @return array|null An array containing the parsed arguments, or null on failure.
  8. */
  9. function loadResourcesFromArgs(array $expectedArgs, int $maxRetries = 3): ?array
  10. {
  11. $args = getopt(":", array_keys($expectedArgs)); // Parse command-line arguments
  12. $retries = 0;
  13. while ($retries < $maxRetries) {
  14. $validArgs = [];
  15. $success = true;
  16. foreach ($expectedArgs as $key => $type) {
  17. if (isset($args[$key])) {
  18. $value = $args[$key];
  19. if (is_numeric($type)) {
  20. $value = (int)$value; // Cast to integer if specified
  21. } elseif (is_bool($type)) {
  22. $value = (bool)$value; // Cast to boolean if specified
  23. }
  24. $validArgs[$key] = $value;
  25. } else {
  26. $success = false;
  27. error_log("Missing argument: " . $key);
  28. }
  29. }
  30. if ($success) {
  31. return $validArgs; // Successfully parsed arguments
  32. } else {
  33. $retries++;
  34. if ($retries < $maxRetries) {
  35. echo "Failed to parse arguments. Retrying... (" . $retries . "/" . $maxRetries . ")\n";
  36. // Add a delay before retrying (optional)
  37. sleep(1);
  38. } else {
  39. error_log("Failed to parse arguments after multiple retries.");
  40. return null; // Return null on failure after max retries
  41. }
  42. }
  43. }
  44. return null; // Should not reach here if retries are configured correctly.
  45. }
  46. // Example usage:
  47. // Define expected arguments and their types
  48. $expectedArgs = [
  49. 'input' => 'string',
  50. 'count' => 'int',
  51. 'debug' => 'bool',
  52. ];
  53. $args = loadResourcesFromArgs($expectedArgs);
  54. if ($args !== null) {
  55. echo "Arguments loaded successfully:\n";
  56. print_r($args);
  57. // Use the loaded arguments
  58. if (isset($args['input'])) {
  59. echo "Input file: " . $args['input'] . "\n";
  60. }
  61. if (isset($args['count'])) {
  62. echo "Count: " . $args['count'] . "\n";
  63. }
  64. if (isset($args['debug']) && $args['debug']) {
  65. echo "Debug mode is enabled.\n";
  66. }
  67. } else {
  68. echo "Failed to load arguments.\n";
  69. }
  70. ?>

Add your comment