1. <?php
  2. class OptionParser {
  3. private $options = [];
  4. public function addOption($short, $long, $type = null, $default = null, $description = null, $options = []) {
  5. // Store option details.
  6. $this->options[$short] = [
  7. 'long' => $long,
  8. 'type' => $type,
  9. 'default' => $default,
  10. 'description' => $description,
  11. 'options' => $options, // For nested options
  12. ];
  13. }
  14. public function parse($args) {
  15. $parsed = [];
  16. $args_copy = $args; //copy to avoid modifying original args
  17. $i = 0;
  18. while ($i < count($args_copy)) {
  19. $arg = $args_copy[$i];
  20. if ($arg[0] === '-') {
  21. $short = $arg[1];
  22. if (isset($this->options[$short])) {
  23. $option = $this->options[$short];
  24. if (isset($args_copy[$i + 1])) {
  25. $value = $args_copy[$i + 1];
  26. if ($option['type'] === 'bool') {
  27. $parsed[$short] = (bool) $value; // Convert to boolean
  28. } else {
  29. $parsed[$short] = $value;
  30. }
  31. $i += 2; // Consume option and value
  32. } else {
  33. if (isset($option['default'])) {
  34. $parsed[$short] = $option['default'];
  35. } else {
  36. throw new Exception("Missing value for option: --$short");
  37. }
  38. $i++;
  39. }
  40. } else {
  41. throw new Exception("Unknown option: --$short");
  42. }
  43. } else {
  44. $parsed[] = $arg; // Non-option arguments
  45. $i++;
  46. }
  47. }
  48. return $parsed;
  49. }
  50. }
  51. // Example Usage:
  52. $parser = new OptionParser();
  53. $parser->addOption('a', 'enable-feature', 'bool', false, 'Enable a feature', []);
  54. $parser->addOption('v', 'verbose', 'bool', false, 'Enable verbose output', []);
  55. $parser->addOption('l', 'log-file', null, null, 'Specify the log file', ['path' => '']);
  56. $parser->addOption('n', 'num-iterations', 'int', 10, 'Number of iterations', []);
  57. $arguments = ['-a', '-v', '--log-file', 'my_log.txt', '-n', '20'];
  58. try {
  59. $parsed_args = $parser->parse($arguments);
  60. print_r($parsed_args);
  61. echo "enable_feature: " . ($parsed_args['a'] ? 'true' : 'false') . "\n";
  62. echo "verbose: " . ($parsed_args['v'] ? 'true' : 'false') . "\n";
  63. echo "log_file: " . $parsed_args['log-file'] . "\n";
  64. echo "num_iterations: " . $parsed_args['num-iterations'] . "\n";
  65. } catch (Exception $e) {
  66. echo "Error: " . $e->getMessage() . "\n";
  67. }
  68. ?>

Add your comment