1<?php
2
3/**
4 * Parse command line options
5 *
6 */
7class gtCommandLineOptions {
8
9  protected $shortOptions = array(
10    'b',
11    'e',
12    'v',
13    'h',
14  );
15
16  protected $shortOptionsWithArgs = array(
17    'c',
18    'm',
19    'f',
20    'i',
21    's',
22    'x',
23    'k',
24  );
25
26  protected $options;
27
28  protected function isShortOption($arg)
29  {
30    return (substr($arg, 0, 1) == '-') && (substr($arg, 1, 1) != '-');
31  }
32
33  public function isValidOptionArg($array, $index) {
34    if (!isset($array[$index]))
35    {
36      return false;
37    }
38    return substr($array[$index], 0, 1) != '-';
39  }
40
41
42  public function parse($argv)
43  {
44    if(count($argv) < 2) {
45      throw new gtMissingOptionsException('Command line options are required');
46    }
47
48    for ($i=1; $i<count($argv); $i++) {
49
50      if ($this->isShortOption($argv[$i])) {
51        $option = substr($argv[$i], 1);
52      } else {
53        throw new gtUnknownOptionException('Unrecognised command line option ' . $argv[$i]);
54      }
55
56      if (!in_array($option, array_merge($this->shortOptions, $this->shortOptionsWithArgs)))
57      {
58        throw new gtUnknownOptionException('Unknown option ' . $argv[$i]);
59      }
60
61      if (in_array($option, $this->shortOptions)) {
62        $this->options[$option] = true;
63        continue;
64      }
65
66      if (!$this->isValidOptionArg($argv, $i + 1))
67      {
68        throw new gtMissingArgumentException('Missing argument for command line option ' . $argv[$i]);
69      }
70
71      $i++;
72      $this->options[$option] = $argv[$i];
73    }
74  }
75
76 /**
77   *
78   */
79  public function getOption($option)
80  {
81    if (!isset($this->options[$option])) {
82      return false;
83    }
84    return $this->options[$option];
85  }
86
87
88  /**
89   * Check whether an option exists
90   */
91  public function hasOption($option)
92  {
93    return isset($this->options[$option]);
94  }
95
96
97}
98?>