mmp /lib/GetOpt.class.php

Language PHP Lines 171
MD5 Hash 9cd7918efd71e3194933655db44a74cc Estimated Cost $2,967 (why?)
Repository https://bitbucket.org/idler/mmp/ View Raw File View Project SPDX
  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
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
<?php

class GetOpt {
  static protected $default_config = array(
    'optVal'
  );
  private static $errors = array();
  
  /**
   * Parse and extract left-most options up to the first non-option argument
   *
   * @param array $args List of arguments to search through
   * @param array $opts Option templates. Defines rules for the options we need to parse
   * @return array Extracted options
   */
  static function extractLeft(&$args, $opts)
  {
    $result = array();
    self::$errors = array();
    $opts = self::normalizeTpl($opts);
    $short_opts = self::mapShortOpts($opts);
    
    while(!empty($args))
    {
      $arg = array_shift($args);
      if(preg_match('/^--([a-z][a-z\-]*)/i', $arg, $matches)) //long options start with "--"
      {
        $matches[1] = strtolower($matches[1]);
        if(isset($opts[$matches[1]]))
        {
          try
          {
            $result[$matches[1]] = self::parseValue($args, $arg, $opts[$matches[1]]);
          }
          catch(Exception $e)
          {
            self::$errors[] = $e->getMessage();
            return false;
          }
        }
        else
        {
          self::$errors[] = 'Invalid option \'' . $matches[1] . '\'';
          return false;
        }
      }
      elseif(preg_match('/^-([a-z])/', $arg, $matches)) //short options start with '-', are case-sensitive
      {
        foreach(str_split($matches[1]) as $o)
        {
          if(isset($short_opts[$o]))
          {
            try
            {
              $result[$short_opts[$o]] = self::parseValue($args, $arg, $opts[$short_opts[$o]]);
            }
            catch(Exception $e)
            {
              self::$errors[] = $e->getMessage();
              return false;
            }
          }
          else
          {
            self::$errors[] = 'Invalid option \'' . $matches[1] . '\'';
            return false;
          }
        }
      }
      else
      {
        array_unshift($args, $arg);
        break;
      }
    }
    
    return $result;
  }
  
  /**
   * Return list errors encountered while parsing the arguments
   *
   * @return array List of errors
   */
  static function errors()
  {
    return self::$errors;
  }
  
  /**
   * Expand array values without custom keys into "'value' => true" pairs
   *
   * @param array $opts Array to process
   * @return array Processed array
   */
  private static function normalizeTpl($opts)
  {
    foreach($opts as &$tpl)
    {
      $ntpl = array();
      foreach($tpl as $k => $t)
      {
        if(is_string($k))
          $ntpl[$k] = $t;
        elseif(is_int($k) && is_string($t))
          $ntpl[$t] = true;
      }
      $tpl = $ntpl;
    }
    
    return $opts;
  }
  
  /**
   * Get the associations between short and long options, if any exist
   *
   * @param array $opts Options to parse
   * @return array List of mappings between short_options => long_options
   */
  private static function mapShortOpts($opts)
  {
    $result = array();
    
    foreach($opts as $k => $o)
    {
      if(!empty($o['short']))
        $result[$o['short']] = $k;
    }
    
    return $result;
  }
  
  /**
   * Get "value" part of the long, if any, from the arguments list.
   *
   * Note: $args might be modified depending on the given option template
   *
   * @param array $args List of command-line arguments
   * @param string $arg Argument being parsed
   * @param array $tpl Template for the argument being parsed
   * @return mixed Parsed option value, null if no value required
   */
  private static function parseValue(&$args, $arg, $tpl)
  {
    foreach($tpl as $t => $v)
    {
      switch($t)
      {
        case 'req_val':
          if(strpos($arg, '=') === false)
          {
            if(!empty($args))
              return array_shift($args);
            else
              throw new Exception('Missing option value');
          }
          else
            return substr(strstr($arg, '='), 1);
          break;
        case 'opt_val':
          if(strpos($arg, '=') !== false)
            return substr(strstr($arg, '='), 1);
          break;
      }
    }
    
    return null;
  }
}

?>
Back to Top