Cml\Console\IO\Input::parse PHP Method

parse() public static method

解析参数
public static parse ( array $argv ) : array
$argv array
return array
    public static function parse(array $argv)
    {
        $args = [];
        $options = [];
        for ($i = 0, $num = count($argv); $i < $num; $i++) {
            $arg = $argv[$i];
            if ($arg === '--') {
                //后缀所有内容都为参数
                $args[] = implode(' ', array_slice($argv, $i + 1));
                break;
            }
            if (substr($arg, 0, 2) === '--') {
                $key = substr($arg, 2);
                $value = true;
                if (($hadValue = strpos($arg, '=')) !== false) {
                    $key = substr($arg, 2, $hadValue - 2);
                    $value = substr($arg, $hadValue + 1);
                }
                if (array_key_exists($key, $options)) {
                    if (!is_array($options[$key])) {
                        $options[$key] = [$options[$key]];
                    }
                    $options[$key][] = $value;
                } else {
                    $options[$key] = $value;
                }
            } else {
                if (substr($arg, 0, 1) === '-') {
                    foreach (str_split(substr($arg, 1)) as $key) {
                        $options[$key] = true;
                    }
                } else {
                    $args[] = $arg;
                }
            }
        }
        return [$args, $options];
    }

Usage Example

Example #1
0
 /**
  * 运行命令
  *
  * @param array|null $argv
  *
  * @return mixed
  */
 public function run(array $argv = null)
 {
     try {
         if ($argv === null) {
             $argv = isset($_SERVER['argv']) ? array_slice($_SERVER['argv'], 1) : [];
         }
         list($args, $options) = Input::parse($argv);
         $command = count($args) ? array_shift($args) : 'help';
         if (!isset($this->commands[$command])) {
             throw new \InvalidArgumentException("Command '{$command}' does not exist");
         }
         isset($options['no-ansi']) && Colour::setNoAnsi();
         if (isset($options['h']) || isset($options['help'])) {
             $help = new Help($this);
             $help->execute([$command]);
             exit(0);
         }
         $command = explode('::', $this->commands[$command]);
         return call_user_func_array([new $command[0]($this), isset($command[1]) ? $command[1] : 'execute'], [$args, $options]);
     } catch (\Exception $e) {
         Output::writeException($e);
         exit(1);
     }
 }
Input