执行命令入口

@param array $args 参数
@param array $options 选项
502469
public function execute(array $args, array $options = [])
    {
        $this->writeln("CmlPHP Console " . Cml::VERSION . "\n", ['foregroundColors' => [Colour::GREEN, Colour::HIGHLIGHT]]);
        $format = new Format(['indent' => 2]);

        if (empty($args)) {
            $this->writeln("Usage:");
            $this->writeln($format->format("input 'command [options] [args]' to run command or input 'help command ' to display command help info"));
            $this->writeln('');

            $options = $this->formatOptions();
            $cmdList = $this->formatCommand();

            $this->writeln("Options:");
            $this->formatEcho($format, $options);
            $this->writeln('');

            $this->writeln('Available commands:');
            $this->formatEcho($format, $cmdList[0]);
            $this->formatEcho($format, $cmdList[1]);
        } else {
            $class = new \ReflectionClass($this->console->getCommand($args[0]));
            $property = $class->getDefaultProperties();
            $description = isset($property['description']) ? $property['description'] : '';
            $help = isset($property['help']) ? $property['help'] : false;
            $arguments = isset($property['arguments']) ? $property['arguments'] : [];
            $options = isset($property['options']) ? $property['options'] : [];

            $this->writeln("Usage:");
            $this->writeln($format->format("{$args[0]} [options] [args]"));
            $this->writeln('');

            count($arguments) > 0 && $arguments = $this->formatArguments($arguments);
            $options = $this->formatOptions($options, 'this');

            $this->writeln("Options:");
            $this->formatEcho($format, $options);
            $this->writeln('');

            if (count($arguments)) {
                $this->writeln("Arguments");
                $this->formatEcho($format, $arguments);
                $this->writeln('');
            }

            $this->writeln("Help:");
            $this->writeln($format->format($help ? $help : $description));
        }
        $this->write("\n");
    }
817027
protected function executeCurl(array $options)
    {
        curl_setopt_array($this->curl, $options);

        $result = curl_exec($this->curl);
        self::curlValidate($this->curl, $result);
        if ($result === false) {
            throw new HttpException(curl_error($this->curl), curl_errno($this->curl));
        }

        return $result;
    }
91147
public function run($args)
	{
		$runner=$this->getCommandRunner();
		$commands=$runner->commands;
		if(isset($args[0]))
			$name=strtolower($args[0]);
		if(!isset($args[0]) || !isset($commands[$name]))
		{
			if(!empty($commands))
			{
				echo "Yii command runner (based on Yii v".Yii::getVersion().")\n";
				echo "Usage: ".$runner->getScriptName()." <command-name> [parameters...]\n";
				echo "\nThe following commands are available:\n";
				$commandNames=array_keys($commands);
				sort($commandNames);
				echo ' - '.implode("\n - ",$commandNames);
				echo "\n\nTo see individual command help, use the following:\n";
				echo "   ".$runner->getScriptName()." help <command-name>\n";
			}
			else
			{
				echo "No available commands.\n";
				echo "Please define them under the following directory:\n";
				echo "\t".Yii::app()->getCommandPath()."\n";
			}
		}
		else
			echo $runner->createCommand($name)->getHelp();
		return 1;
	}
739856
public function executeCommand(string $cmd, array $arguments = [], array $options = [])
    {
        $options = array_replace(
            [
                'overrideExitCode'  => null,
                'exceptionMessage'  => 'There was an error while executing the command.',
                'returnString'      => false,
                'implodeSeparator'  => PHP_EOL,
                'postCommand'       => ''
            ],
            $options
        );

        foreach ($arguments as $arg) {
            $cmd .= ' '.escapeshellarg($arg);
        }

        $cmd .= $options['postCommand'];

        exec($cmd, $output, $status);

        $status = $status && $options['overrideExitCode'] ?
            $options['overrideExitCode'] :
            $status;

        $this->_lastExecutedCommand['cmd'] = $cmd;
        $this->_lastExecutedCommand['arguments'] = $arguments;
        $this->_lastExecutedCommand['options'] = $options;
        $this->_lastExecutedCommand['output'] = $output;
        $this->_lastExecutedCommand['exitCode'] = $status;

        if ($status) {
            throw CommandException::create(
                $options['exceptionMessage'],
                $options['overrideExitCode'] ? $options['overrideExitCode'] : $status,
                $output,
                $cmd,
                $arguments
            );
        }

        return $options['returnString'] ?
            implode($options['implodeSeparator'], $output) :
            $output;
    }
20284
protected static function execCommand($options, $cmd, array $args, $ifError)
    {
        if (is_array($options) && isset($options['path'])) {
            $cmd = $options['path'];
        } else {
            $executableFinder = new ExecutableFinder;
            $cmd = $executableFinder->find($cmd);
        }

        $out = '';
        $process = ProcessBuilder::create(array_merge(array($cmd), $args))->getProcess();
        if (isset($options['timeout'])) {
            $process->setTimeout($options['timeout']);
        }
        $process->run(function($type, $buffer) use (&$out) { $out .= $buffer; });

        if (!$process->isSuccessful()) {
            throw new \RuntimeException($ifError."\n\n".$out);
        }
    }
105608
public function fetch($sql, array $params, array $options = array())
    {
        $sth = $this->run($sql, $params);
        $result = $sth->fetch(PDO::FETCH_ASSOC);

        $this->prepareResult($result, $options);
        return empty($result) ? array() : (array) $result;
    }
714700
public function handle(array $args = [])
    {
        // remove source file name from argv
        $source = array_shift($args);

        /** @var ConsoleEvent $applicationEvent */
        $applicationEvent = $this->getApplicationEvent();
        $applicationEvent->setName(self::EVENT_REQUEST_RECEIVED);
        $applicationEvent->setSourceFile($source);
        $applicationEvent->setArguments($args);
        $this->emit($applicationEvent);

        // init dispatcher
        $dispatcher = new Dispatcher($this->commands, $this->container);

        $middlewareRunner = new MiddlewareRunner($this->getMiddlewares());

        $middlewareRunner->run([$applicationEvent->getArguments()], function ($args) use ($applicationEvent, $dispatcher) {
            // dispatch command with args from cli
            $dispatcher->dispatch($args);
        });
    }
984944
protected function createClients(array $servers, array $options = [])
	{
		$clients = [];
		
		foreach ($servers as $key => $server) {
			
			$redis = new \Redis;
			//长连接为pconnect,长连接要注意执行close关闭
			$func =Arr::get($server,'persistent',false) ? 'pconnect' : 'connect';
			
			$redis->connect(Arr::get($server, 'host',''), Arr::get($server, 'port'), $this->timeOut);
			//有配置密码的，进行auth操作
			if ($pwd = Arr::get($server, 'password', '')) {
				$redis->auth($pwd);
			}
			
			$redis->select(Arr::get($server,'database'));
			//设置redis的option,如Redis::OPT_SERIALIZER, Redis::SERIALIZER_NONE
			foreach ($options as $key => $val) {
				$redis->setOption($key, $val);
			}
			
			$clients[$key] = $redis;
		}
		
		return $clients;
	}
608230
protected function exec($options)
    {  
        $method = key($options);
        $requestPath = reset($options);
        $verb = self::$verbArray[$method];
        
        $headers = $this->getArrayValue($options, 'headers');
        $url_query = $this->getArrayValue($options, 'url_query');
        $formData = $this->getArrayValue($options, 'form_data');
        $jsonData = $this->getArrayValue($options, 'json_data');
        

        $defaultHttpParams = self::$defaultParams;
        $connectionParams = array_merge($defaultHttpParams, $this->customParams);
        $query = '';

        if ($url_query > 0) {
            $query = http_build_query($url_query);
        }
        
        $address = $this->getArrayValue($connectionParams, 'address');
        $uri = $address . $requestPath;
        if ($query != '') {
            if (parse_url($uri, PHP_URL_QUERY)) {
                $uri .= '&' . $query;
            } else {
                $uri .= '?' . $query;
            }
        }

        $connect = $this->getHttpRequest();
        $connect->setOption(CURLOPT_URL, $uri);
        if ($userAgent = $this->getArrayValue($connectionParams, 'user_agent')) {
            $connect->setOption(CURLOPT_USERAGENT, $userAgent);
        }
        $connect->setOption(CURLOPT_RETURNTRANSFER, true);
        $connect->setOption(CURLOPT_CUSTOMREQUEST, $verb);
        
        $this->setHeaders($connect, $headers);
        $proxyAddress = $this->getArrayValue($connectionParams, 'proxy_addr');
        $proxyPort = $this->getArrayValue($connectionParams, 'proxy_port');
        if (!empty($proxyAddress)) {
            $connect->setOption(CURLOPT_PROXY, $proxyAddress);
            $connect->setOption(CURLOPT_PROXYPORT, $proxyPort);
        }
        if ($useSsl = $this->getArrayValue($connectionParams, 'use_ssl')) {
            $connect->setOption(CURLOPT_SSL_VERIFYPEER, $useSsl);
        }
        if ($sslVersion = $this->getArrayValue($connectionParams, 'ssl_version')) {
            $connect->setOption(CURLOPT_SSLVERSION, $sslVersion);
        }
        if ($verifyMode = $this->getArrayValue($connectionParams, 'verify_mode')) {
            $connect->setOption(CURLOPT_SSL_VERIFYHOST, $verifyMode);
        }
        if ($caFile = $this->getArrayValue($connectionParams, 'ca_file')) {
            $connect->setOption(CURLOPT_CAPATH, $caFile);
        }
        
        $connect->setOption(CURLOPT_FOLLOWLOCATION, true);

        if ($formData) {
            $this->setData($connect, $formData);
        }
        if ($jsonData) {
            $this->setData($connect, $jsonData, "application/json");
        }
 
        $apiResult = $connect->execute();
        $apiHttpCode = $connect->getInfo(CURLINFO_HTTP_CODE);
        
        if ($apiResult === false) {
            throw new Exception ($connect->error());
        }
        
        $response['response'] = [];
        
        if ($apiHttpCode != "200" && $apiHttpCode != "201") {
            error_log($apiResult);
        }
        
        $response['response'] = json_decode($apiResult, true);
        $response['code'] = $apiHttpCode;

        $connect->error();
        
        return ['code' => $response['code'], 'body' => $response['response']];
    }
347324
public function post($resource, array $args = [], array $options = [])
    {
        if (!empty($options)) {
            $this->setOptions($options, $resource);
        }
        $result = $this->_call('POST', $resource[0], $resource[1], $args);

        if (!empty($this->changed)) {
            $this->setSettings();
        }
        return $result;
    }
456367
public function daemon(ListenerOptions $options)
    {
        $this->listenForSignals();

        $lastRestart = $this->getTimestampOfLastQueueRestart();

        $this->getEventsManager()->fire('listener:beforeDaemonLoop', $this);

        while (true) {
            // Before reserving any jobs, we will make sure this queue is not paused and
            // if it is we will just pause this worker for a given amount of time and
            // make sure we do not need to kill this worker process off completely.
            if (!$this->daemonShouldRun($options)) {
                $this->pauseWorker($options, $lastRestart);
                continue;
            }

            // 尝试使用长轮询的方式获取消息，如果当前没有，则休眠sleep时间。
            $job = $this->getNextJob($options);

            // 如果成功取到一个消息，则进入处理，并且设置超时时间
            if ($job) {
                $this->registerTimeoutHandler($job, $options);

                $this->runJob($job, $options);

                $this->clearTimeoutAlarm($options);
            }

            // Finally, we will check to see if we have exceeded our memory limits or if
            // the queue should restart based on other indications. If so, we'll stop
            // this worker and let whatever is "monitoring" it restart the process.
            $this->stopIfNecessary($options, $lastRestart);
        }

        $this->getEventsManager()->fire('listener:afterDaemonLoop', $this);
    }
789591
public function sendRequest(array $options = [])
    {
        $this->autoInitialize();

        if ( ! empty($options))
        {
            if ( ! $this->setOptions($options))
            {
                return false;
            }
        }

        $this->response = curl_exec($this->curl);

        return $this->response;
    }
1043481
public function get($url, $params = array(), $options = array())
    {
        $client = new \GuzzleHttp\Client($options);
        $query = $this->getQueryParam4AccessToken();
        $params = array_merge($params, $query);
        $response = $client->get($url, array(
            'query' => $params
        ));
        if ($this->isSuccessful($response)) {
            return $this->getJson($response); // $response->json();
        } else {
            throw new Exception("微信服务器未有效的响应请求");
        }
    }
1107918
public function init($options = [])
    {
        $auth = new Authentication();

        if (!$auth->check()) {
            $url = (isset($options['auth_login_url']))
            ? $options['auth_login_url']
            : '/auth/login';

            $this->redirect = $url;
        }
    }
286386
public function execute(array $args, array $options = [])
    {
        if (empty($args) || strpos($args[0], '/') < 1) {
            throw new \InvalidArgumentException('please input action');
        }
        Route::setPathInfo(explode('/', trim(trim($args[0], '/\\'))));
        return 'don_not_exit';
    }
1168191
protected function request($uri, array $params = [], array $options = [])
    {
        if ($options) {
            $params = array_merge($params, $options);
        }
        // 没有参数, 设置一个默认参数
        if (!$params) {
            $params['php-etcd-client'] = 1;
        }
        $data = [
            'json' => $params,
        ];
        if ($this->token) {
            $data['headers'] = ['Grpc-Metadata-Token' => $this->token];
        }

        $response = $this->getHttpClient()->request('post', $uri, $data);
        $content = $response->getBody()->getContents();

        $body = json_decode($content, true);
        if ($this->pretty && isset($body['header'])) {
            unset($body['header']);
        }

        return $body;
    }
841911
public function execute($args)
    {
        self::$definedProps = new Properties();
        $this->searchForThis = null;

        // 1) First handle any options which should always
        // Note: The order in which these are executed is important (if multiple of these options are specified)

        if (in_array('-help', $args) || in_array('-h', $args)) {
            static::printUsage();

            return;
        }

        if (in_array('-version', $args) || in_array('-v', $args)) {
            static::printVersion();

            return;
        }

        if (in_array('-init', $args) || in_array('-i', $args)) {
            $key = array_search('-init', $args) ?: array_search('-i', $args);
            $path = isset($args[$key + 1]) ? $args[$key + 1] : null;

            self::init($path);

            return;
        }

        if (in_array('-diagnostics', $args)) {
            Diagnostics::doReport(new PrintStream(self::$out));

            return;
        }

        // 2) Next pull out stand-alone args.
        // Note: The order in which these are executed is important (if multiple of these options are specified)

        if (false !== ($key = array_search('-quiet', $args, true)) || false !== ($key = array_search(
            '-q',
            $args,
            true
        ))
        ) {
            self::$msgOutputLevel = Project::MSG_WARN;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-emacs', $args, true))
            || false !== ($key = array_search('-e', $args, true))
        ) {
            $this->emacsMode = true;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-verbose', $args, true))) {
            self::$msgOutputLevel = Project::MSG_VERBOSE;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-debug', $args, true))) {
            self::$msgOutputLevel = Project::MSG_DEBUG;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-silent', $args, true))
            || false !== ($key = array_search('-S', $args, true))
        ) {
            $this->silent = true;
            unset($args[$key]);
        }

        if (false !== ($key = array_search('-propertyfileoverride', $args, true))) {
            $this->propertyFileOverride = true;
            unset($args[$key]);
        }

        // 3) Finally, cycle through to parse remaining args
        //
        $keys = array_keys($args); // Use keys and iterate to max(keys) since there may be some gaps
        $max = $keys ? max($keys) : -1;
        for ($i = 0; $i <= $max; $i++) {
            if (!array_key_exists($i, $args)) {
                // skip this argument, since it must have been removed above.
                continue;
            }

            $arg = $args[$i];

            if ($arg == "-logfile") {
                try {
                    // see: http://phing.info/trac/ticket/65
                    if (!isset($args[$i + 1])) {
                        $msg = "You must specify a log file when using the -logfile argument\n";
                        throw new ConfigurationException($msg);
                    }

                    $logFile = new PhingFile($args[++$i]);
                    $out = new FileOutputStream($logFile); // overwrite
                    self::setOutputStream($out);
                    self::setErrorStream($out);
                    self::$isLogFileUsed = true;
                } catch (IOException $ioe) {
                    $msg = "Cannot write on the specified log file. Make sure the path exists and you have write permissions.";
                    throw new ConfigurationException($msg, $ioe);
                }
            } elseif ($arg == "-buildfile" || $arg == "-file" || $arg == "-f") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a buildfile when using the -buildfile argument.";
                    throw new ConfigurationException($msg);
                }

                $this->buildFile = new PhingFile($args[++$i]);
            } elseif ($arg == "-listener") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a listener class when using the -listener argument";
                    throw new ConfigurationException($msg);
                }

                $this->listeners[] = $args[++$i];
            } elseif (StringHelper::startsWith("-D", $arg)) {
                // Evaluating the property information //
                // Checking whether arg. is not just a switch, and next arg. does not starts with switch identifier
                if (('-D' == $arg) && (!StringHelper::startsWith('-', $args[$i + 1]))) {
                    $name = $args[++$i];
                } else {
                    $name = substr($arg, 2);
                }

                $value = null;
                $posEq = strpos($name, "=");
                if ($posEq !== false) {
                    $value = substr($name, $posEq + 1);
                    $name = substr($name, 0, $posEq);
                } elseif ($i < count($args) - 1 && !StringHelper::startsWith("-D", $args[$i + 1])) {
                    $value = $args[++$i];
                }
                self::$definedProps->setProperty($name, $value);
            } elseif ($arg == "-logger") {
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a classname when using the -logger argument";
                    throw new ConfigurationException($msg);
                }

                $this->loggerClassname = $args[++$i];
            } elseif ($arg == "-no-strict") {
                $this->strictMode = false;
            } elseif ($arg == "-strict") {
                $this->strictMode = true;
            } elseif ($arg == "-inputhandler") {
                if ($this->inputHandlerClassname !== null) {
                    throw new ConfigurationException("Only one input handler class may be specified.");
                }
                if (!isset($args[$i + 1])) {
                    $msg = "You must specify a classname when using the -inputhandler argument";
                    throw new ConfigurationException($msg);
                }

                $this->inputHandlerClassname = $args[++$i];
            } elseif ($arg === "-propertyfile") {
                $i = $this->handleArgPropertyFile($args, $i);
            } elseif ($arg === "-keep-going" || $arg === "-k") {
                $this->keepGoingMode = true;
            } elseif ($arg == "-longtargets") {
                self::$definedProps->setProperty('phing.showlongtargets', 1);
            } elseif ($arg == "-projecthelp" || $arg == "-targets" || $arg == "-list" || $arg == "-l" || $arg == "-p") {
                // set the flag to display the targets and quit
                $this->projectHelp = true;
            } elseif ($arg == "-find") {
                // eat up next arg if present, default to build.xml
                if ($i < count($args) - 1) {
                    $this->searchForThis = $args[++$i];
                } else {
                    $this->searchForThis = self::DEFAULT_BUILD_FILENAME;
                }
            } elseif (substr($arg, 0, 1) == "-") {
                // we don't have any more args
                self::printUsage();
                self::$err->write(PHP_EOL);
                throw new ConfigurationException("Unknown argument: " . $arg);
            } else {
                // if it's no other arg, it may be the target
                $this->targets[] = $arg;
            }
        }

        // if buildFile was not specified on the command line,
        if ($this->buildFile === null) {
            // but -find then search for it
            if ($this->searchForThis !== null) {
                $this->buildFile = $this->_findBuildFile(self::getProperty("user.dir"), $this->searchForThis);
            } else {
                $this->buildFile = new PhingFile(self::DEFAULT_BUILD_FILENAME);
            }
        }

        try {
            // make sure buildfile (or buildfile.dist) exists
            if (!$this->buildFile->exists()) {
                $distFile = new PhingFile($this->buildFile->getAbsolutePath() . ".dist");
                if (!$distFile->exists()) {
                    throw new ConfigurationException(
                        "Buildfile: " . $this->buildFile->__toString() . " does not exist!"
                    );
                }
                $this->buildFile = $distFile;
            }

            // make sure it's not a directory
            if ($this->buildFile->isDirectory()) {
                throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " is a dir!");
            }
        } catch (IOException $e) {
            // something else happened, buildfile probably not readable
            throw new ConfigurationException("Buildfile: " . $this->buildFile->__toString() . " is not readable!");
        }

        $this->loadPropertyFiles();

        $this->readyToRun = true;
    }