summaryrefslogtreecommitdiff
path: root/scripts/dev/generate-phpt/src/setup/gtCommandLineOptions.php
blob: b1068e46004cbe4662e9cb76eb9f61e7597f0358 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<?php

/**
 * Parse command line options
 *
 */
class gtCommandLineOptions {

  protected $shortOptions = array(
    'b',
    'e',
    'v',
    'h',
  );

  protected $shortOptionsWithArgs = array(
    'c',
    'm',
    'f',
    'i',
    's',
    'x',
    'k',
  );

  protected $options;

  protected function isShortOption($arg)
  {
    return (substr($arg, 0, 1) == '-') && (substr($arg, 1, 1) != '-');
  }

  public function isValidOptionArg($array, $index) {
    if (!isset($array[$index]))
    {
      return false;
    }
    return substr($array[$index], 0, 1) != '-';
  }


  public function parse($argv)
  {
    if(count($argv) < 2) {
      throw new gtMissingOptionsException('Command line options are required');
    }

    for ($i=1; $i<count($argv); $i++) {

      if ($this->isShortOption($argv[$i])) {
        $option = substr($argv[$i], 1);
      } else {
        throw new gtUnknownOptionException('Unrecognised command line option ' . $argv[$i]);
      }

      if (!in_array($option, array_merge($this->shortOptions, $this->shortOptionsWithArgs)))
      {
        throw new gtUnknownOptionException('Unknown option ' . $argv[$i]);
      }

      if (in_array($option, $this->shortOptions)) {
        $this->options[$option] = true;
        continue;
      }

      if (!$this->isValidOptionArg($argv, $i + 1))
      {
        throw new gtMissingArgumentException('Missing argument for command line option ' . $argv[$i]);
      }

      $i++;
      $this->options[$option] = $argv[$i];
    }
  }

 /**
   *
   */
  public function getOption($option)
  {
    if (!isset($this->options[$option])) {
      return false;
    }
    return $this->options[$option];
  }


  /**
   * Check whether an option exists
   */
  public function hasOption($option)
  {
    return isset($this->options[$option]);
  }


}
?>