Getopt.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. <?php
  2. /* vim: set expandtab tabstop=4 shiftwidth=4: */
  3. /**
  4. * PHP Version 5
  5. *
  6. * Copyright (c) 2001-2015, The PEAR developers
  7. *
  8. * This source file is subject to the BSD-2-Clause license,
  9. * that is bundled with this package in the file LICENSE, and is
  10. * available through the world-wide-web at the following url:
  11. * http://opensource.org/licenses/bsd-license.php.
  12. *
  13. * @category Console
  14. * @package Console_Getopt
  15. * @author Andrei Zmievski <andrei@php.net>
  16. * @license http://opensource.org/licenses/bsd-license.php BSD-2-Clause
  17. * @version CVS: $Id$
  18. * @link http://pear.php.net/package/Console_Getopt
  19. */
  20. require_once 'PEAR.php';
  21. /**
  22. * Command-line options parsing class.
  23. *
  24. * @category Console
  25. * @package Console_Getopt
  26. * @author Andrei Zmievski <andrei@php.net>
  27. * @license http://opensource.org/licenses/bsd-license.php BSD-2-Clause
  28. * @link http://pear.php.net/package/Console_Getopt
  29. */
  30. class Console_Getopt
  31. {
  32. /**
  33. * Parses the command-line options.
  34. *
  35. * The first parameter to this function should be the list of command-line
  36. * arguments without the leading reference to the running program.
  37. *
  38. * The second parameter is a string of allowed short options. Each of the
  39. * option letters can be followed by a colon ':' to specify that the option
  40. * requires an argument, or a double colon '::' to specify that the option
  41. * takes an optional argument.
  42. *
  43. * The third argument is an optional array of allowed long options. The
  44. * leading '--' should not be included in the option name. Options that
  45. * require an argument should be followed by '=', and options that take an
  46. * option argument should be followed by '=='.
  47. *
  48. * The return value is an array of two elements: the list of parsed
  49. * options and the list of non-option command-line arguments. Each entry in
  50. * the list of parsed options is a pair of elements - the first one
  51. * specifies the option, and the second one specifies the option argument,
  52. * if there was one.
  53. *
  54. * Long and short options can be mixed.
  55. *
  56. * Most of the semantics of this function are based on GNU getopt_long().
  57. *
  58. * @param array $args an array of command-line arguments
  59. * @param string $short_options specifies the list of allowed short options
  60. * @param array $long_options specifies the list of allowed long options
  61. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  62. *
  63. * @return array two-element array containing the list of parsed options and
  64. * the non-option arguments
  65. */
  66. public static function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
  67. {
  68. return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
  69. }
  70. /**
  71. * This function expects $args to start with the script name (POSIX-style).
  72. * Preserved for backwards compatibility.
  73. *
  74. * @param array $args an array of command-line arguments
  75. * @param string $short_options specifies the list of allowed short options
  76. * @param array $long_options specifies the list of allowed long options
  77. *
  78. * @see getopt2()
  79. * @return array two-element array containing the list of parsed options and
  80. * the non-option arguments
  81. */
  82. public static function getopt($args, $short_options, $long_options = null, $skip_unknown = false)
  83. {
  84. return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown);
  85. }
  86. /**
  87. * The actual implementation of the argument parsing code.
  88. *
  89. * @param int $version Version to use
  90. * @param array $args an array of command-line arguments
  91. * @param string $short_options specifies the list of allowed short options
  92. * @param array $long_options specifies the list of allowed long options
  93. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  94. *
  95. * @return array
  96. */
  97. public static function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
  98. {
  99. // in case you pass directly readPHPArgv() as the first arg
  100. if (PEAR::isError($args)) {
  101. return $args;
  102. }
  103. if (empty($args)) {
  104. return array(array(), array());
  105. }
  106. $non_opts = $opts = array();
  107. settype($args, 'array');
  108. if ($long_options) {
  109. sort($long_options);
  110. }
  111. /*
  112. * Preserve backwards compatibility with callers that relied on
  113. * erroneous POSIX fix.
  114. */
  115. if ($version < 2) {
  116. if (isset($args[0]{0}) && $args[0]{0} != '-') {
  117. array_shift($args);
  118. }
  119. }
  120. for ($i = 0; $i < count($args); $i++) {
  121. $arg = $args[$i];
  122. /* The special element '--' means explicit end of
  123. options. Treat the rest of the arguments as non-options
  124. and end the loop. */
  125. if ($arg == '--') {
  126. $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
  127. break;
  128. }
  129. if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
  130. $non_opts = array_merge($non_opts, array_slice($args, $i));
  131. break;
  132. } elseif (strlen($arg) > 1 && $arg{1} == '-') {
  133. $error = Console_Getopt::_parseLongOption(substr($arg, 2),
  134. $long_options,
  135. $opts,
  136. $i,
  137. $args,
  138. $skip_unknown);
  139. if (PEAR::isError($error)) {
  140. return $error;
  141. }
  142. } elseif ($arg == '-') {
  143. // - is stdin
  144. $non_opts = array_merge($non_opts, array_slice($args, $i));
  145. break;
  146. } else {
  147. $error = Console_Getopt::_parseShortOption(substr($arg, 1),
  148. $short_options,
  149. $opts,
  150. $i,
  151. $args,
  152. $skip_unknown);
  153. if (PEAR::isError($error)) {
  154. return $error;
  155. }
  156. }
  157. }
  158. return array($opts, $non_opts);
  159. }
  160. /**
  161. * Parse short option
  162. *
  163. * @param string $arg Argument
  164. * @param string[] $short_options Available short options
  165. * @param string[][] &$opts
  166. * @param int &$argIdx
  167. * @param string[] $args
  168. * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option
  169. *
  170. * @return void
  171. */
  172. protected static function _parseShortOption($arg, $short_options, &$opts, &$argIdx, $args, $skip_unknown)
  173. {
  174. for ($i = 0; $i < strlen($arg); $i++) {
  175. $opt = $arg{$i};
  176. $opt_arg = null;
  177. /* Try to find the short option in the specifier string. */
  178. if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') {
  179. if ($skip_unknown === true) {
  180. break;
  181. }
  182. $msg = "Console_Getopt: unrecognized option -- $opt";
  183. return PEAR::raiseError($msg);
  184. }
  185. if (strlen($spec) > 1 && $spec{1} == ':') {
  186. if (strlen($spec) > 2 && $spec{2} == ':') {
  187. if ($i + 1 < strlen($arg)) {
  188. /* Option takes an optional argument. Use the remainder of
  189. the arg string if there is anything left. */
  190. $opts[] = array($opt, substr($arg, $i + 1));
  191. break;
  192. }
  193. } else {
  194. /* Option requires an argument. Use the remainder of the arg
  195. string if there is anything left. */
  196. if ($i + 1 < strlen($arg)) {
  197. $opts[] = array($opt, substr($arg, $i + 1));
  198. break;
  199. } else if (isset($args[++$argIdx])) {
  200. $opt_arg = $args[$argIdx];
  201. /* Else use the next argument. */;
  202. if (Console_Getopt::_isShortOpt($opt_arg)
  203. || Console_Getopt::_isLongOpt($opt_arg)) {
  204. $msg = "option requires an argument --$opt";
  205. return PEAR::raiseError("Console_Getopt: " . $msg);
  206. }
  207. } else {
  208. $msg = "option requires an argument --$opt";
  209. return PEAR::raiseError("Console_Getopt: " . $msg);
  210. }
  211. }
  212. }
  213. $opts[] = array($opt, $opt_arg);
  214. }
  215. }
  216. /**
  217. * Checks if an argument is a short option
  218. *
  219. * @param string $arg Argument to check
  220. *
  221. * @return bool
  222. */
  223. protected static function _isShortOpt($arg)
  224. {
  225. return strlen($arg) == 2 && $arg[0] == '-'
  226. && preg_match('/[a-zA-Z]/', $arg[1]);
  227. }
  228. /**
  229. * Checks if an argument is a long option
  230. *
  231. * @param string $arg Argument to check
  232. *
  233. * @return bool
  234. */
  235. protected static function _isLongOpt($arg)
  236. {
  237. return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' &&
  238. preg_match('/[a-zA-Z]+$/', substr($arg, 2));
  239. }
  240. /**
  241. * Parse long option
  242. *
  243. * @param string $arg Argument
  244. * @param string[] $long_options Available long options
  245. * @param string[][] &$opts
  246. * @param int &$argIdx
  247. * @param string[] $args
  248. *
  249. * @return void|PEAR_Error
  250. */
  251. protected static function _parseLongOption($arg, $long_options, &$opts, &$argIdx, $args, $skip_unknown)
  252. {
  253. @list($opt, $opt_arg) = explode('=', $arg, 2);
  254. $opt_len = strlen($opt);
  255. for ($i = 0; $i < count($long_options); $i++) {
  256. $long_opt = $long_options[$i];
  257. $opt_start = substr($long_opt, 0, $opt_len);
  258. $long_opt_name = str_replace('=', '', $long_opt);
  259. /* Option doesn't match. Go on to the next one. */
  260. if ($long_opt_name != $opt) {
  261. continue;
  262. }
  263. $opt_rest = substr($long_opt, $opt_len);
  264. /* Check that the options uniquely matches one of the allowed
  265. options. */
  266. if ($i + 1 < count($long_options)) {
  267. $next_option_rest = substr($long_options[$i + 1], $opt_len);
  268. } else {
  269. $next_option_rest = '';
  270. }
  271. if ($opt_rest != '' && $opt{0} != '=' &&
  272. $i + 1 < count($long_options) &&
  273. $opt == substr($long_options[$i+1], 0, $opt_len) &&
  274. $next_option_rest != '' &&
  275. $next_option_rest{0} != '=') {
  276. $msg = "Console_Getopt: option --$opt is ambiguous";
  277. return PEAR::raiseError($msg);
  278. }
  279. if (substr($long_opt, -1) == '=') {
  280. if (substr($long_opt, -2) != '==') {
  281. /* Long option requires an argument.
  282. Take the next argument if one wasn't specified. */;
  283. if (!strlen($opt_arg)) {
  284. if (!isset($args[++$argIdx])) {
  285. $msg = "Console_Getopt: option requires an argument --$opt";
  286. return PEAR::raiseError($msg);
  287. }
  288. $opt_arg = $args[$argIdx];
  289. }
  290. if (Console_Getopt::_isShortOpt($opt_arg)
  291. || Console_Getopt::_isLongOpt($opt_arg)) {
  292. $msg = "Console_Getopt: option requires an argument --$opt";
  293. return PEAR::raiseError($msg);
  294. }
  295. }
  296. } else if ($opt_arg) {
  297. $msg = "Console_Getopt: option --$opt doesn't allow an argument";
  298. return PEAR::raiseError($msg);
  299. }
  300. $opts[] = array('--' . $opt, $opt_arg);
  301. return;
  302. }
  303. if ($skip_unknown === true) {
  304. return;
  305. }
  306. return PEAR::raiseError("Console_Getopt: unrecognized option --$opt");
  307. }
  308. /**
  309. * Safely read the $argv PHP array across different PHP configurations.
  310. * Will take care on register_globals and register_argc_argv ini directives
  311. *
  312. * @return mixed the $argv PHP array or PEAR error if not registered
  313. */
  314. public static function readPHPArgv()
  315. {
  316. global $argv;
  317. if (!is_array($argv)) {
  318. if (!@is_array($_SERVER['argv'])) {
  319. if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) {
  320. $msg = "Could not read cmd args (register_argc_argv=Off?)";
  321. return PEAR::raiseError("Console_Getopt: " . $msg);
  322. }
  323. return $GLOBALS['HTTP_SERVER_VARS']['argv'];
  324. }
  325. return $_SERVER['argv'];
  326. }
  327. return $argv;
  328. }
  329. }