3 * This file is part of PHPUnit.
5 * (c) Sebastian Bergmann <sebastian@phpunit.de>
7 * For the full copyright and license information, please view the LICENSE
8 * file that was distributed with this source code.
12 * Command-line options parsing class.
14 * @since Class available since Release 3.0.0
16 class PHPUnit_Util_Getopt
18 public static function getopt(array $args, $short_options, $long_options = null)
21 return array(array(), array());
31 if (isset($args[0][0]) && $args[0][0] != '-') {
36 array_map('trim', $args);
38 while (list($i, $arg) = each($args)) {
44 $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
49 (strlen($arg) > 1 && $arg[1] == '-' && !$long_options)) {
50 $non_opts[] = $args[$i];
52 } elseif (strlen($arg) > 1 && $arg[1] == '-') {
53 self::parseLongOption(
60 self::parseShortOption(
69 return array($opts, $non_opts);
72 protected static function parseShortOption($arg, $short_options, &$opts, &$args)
74 $argLen = strlen($arg);
76 for ($i = 0; $i < $argLen; $i++) {
80 if (($spec = strstr($short_options, $opt)) === false ||
82 throw new PHPUnit_Framework_Exception(
83 "unrecognized option -- $opt"
87 if (strlen($spec) > 1 && $spec[1] == ':') {
88 if (strlen($spec) > 2 && $spec[2] == ':') {
89 if ($i + 1 < $argLen) {
90 $opts[] = array($opt, substr($arg, $i + 1));
94 if ($i + 1 < $argLen) {
95 $opts[] = array($opt, substr($arg, $i + 1));
97 } elseif (list(, $opt_arg) = each($args)) {
99 throw new PHPUnit_Framework_Exception(
100 "option requires an argument -- $opt"
106 $opts[] = array($opt, $opt_arg);
110 protected static function parseLongOption($arg, $long_options, &$opts, &$args)
112 $count = count($long_options);
113 $list = explode('=', $arg);
117 if (count($list) > 1) {
121 $opt_len = strlen($opt);
123 for ($i = 0; $i < $count; $i++) {
124 $long_opt = $long_options[$i];
125 $opt_start = substr($long_opt, 0, $opt_len);
127 if ($opt_start != $opt) {
131 $opt_rest = substr($long_opt, $opt_len);
133 if ($opt_rest != '' && $opt[0] != '=' && $i + 1 < $count &&
134 $opt == substr($long_options[$i+1], 0, $opt_len)) {
135 throw new PHPUnit_Framework_Exception(
136 "option --$opt is ambiguous"
140 if (substr($long_opt, -1) == '=') {
141 if (substr($long_opt, -2) != '==') {
142 if (!strlen($opt_arg) &&
143 !(list(, $opt_arg) = each($args))) {
144 throw new PHPUnit_Framework_Exception(
145 "option --$opt requires an argument"
149 } elseif ($opt_arg) {
150 throw new PHPUnit_Framework_Exception(
151 "option --$opt doesn't allow an argument"
155 $full_option = '--' . preg_replace('/={1,2}$/', '', $long_opt);
156 $opts[] = array($full_option, $opt_arg);
161 throw new PHPUnit_Framework_Exception("unrecognized option --$opt");