/** * Parse command line into config options and commands with its parameters * * $param array $args List of arguments provided from command line */ static function parseCommandLineArgs($args) { $parsed_args = array('options' => array(), 'command' => array('name' => null, 'args' => array())); array_shift($args); $opts = GetOpt::extractLeft($args, self::$config_tpl); if ($opts === false) { Output::error('mmp: ' . reset(GetOpt::errors())); exit(1); } else { $parsed_args['options'] = $opts; } //if we didn't traverse the full array just now, move on to command parsing if (!empty($args)) { $parsed_args['command']['name'] = array_shift($args); } //consider any remaining arguments as command arguments $parsed_args['command']['args'] = $args; return $parsed_args; }
/** * 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)) { $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)) { 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; }