Defines the main handler for commands that uses the HTTP client.

@return callable
343339
private function createCommandHandler()
    {
        return function (CommandInterface $command) {
            return Promise\coroutine(function () use ($command) {
                // Prepare the HTTP options.
                $opts = $command['@http'] ?: [];
                unset($command['@http']);

                try {
                    // Prepare the request from the command and send it.
                    $request = $this->transformCommandToRequest($command);
                    $promise = $this->httpClient->sendAsync($request, $opts);

                    // Create a result from the response.
                    $response = (yield $promise);
                    yield $this->transformResponseToResult($response, $request, $command);
                } catch (\Exception $e) {
                    throw CommandException::fromPrevious($command, $e);
                }
            });
        };
    }
393233
protected function handleRequest()
    {
        $this->call('received', array($this->input));
        
        if ($this->input->get('MsgType') && $this->input->get('MsgType') === 'event') {
            return $this->handleEvent($this->input);
        } elseif ($this->input->get('MsgId')) {
            return $this->handleMessage($this->input);
        }

        return false;
    }
205082
public function exec()
    {
        /** reset temp attributes */
        if (!($this->_form_flag & self::FROM_REDIRECT)) {
            $this->clear();
        }

        /** interceptor after request */
        $ret = $this->callInterceptor('request', $this);
        if ($ret !== null) {
            return $ret;
        }

        /** get connection info */
        list($host, $port, $ssl) = array_values($this->getConnectionTarget());
        if ($this->client && ($this->client->host !== $host || $this->client->port !== $port)) {
            // target maybe changed
            $this->tryToRevertClientToPool();
        }
        if (!$this->client) {
            /** create a new coroutine client */
            $client_pool = ClientPool::getInstance();
            if ($this->use_pool && $client = $client_pool->getEx($host, $port)) {
                $this->client = $client;
            } else {
                $options = [
                    'host' => $host,
                    'port' => $port,
                    'ssl' => $ssl
                ];
                $this->client = $client_pool->createEx($options, !$this->use_pool);
            }
        }

        /** Clear useless cookies property */
        $this->client->cookies = null;

        /** Set request headers */
        $cookie = $this->cookies->toRequestString($this->uri);

        // Ensure Host is the first header.
        // See: http://tools.ietf.org/html/rfc7230#section-5.4
        $headers = ['Host' => $this->getHeaderLine('Host') ?: $this->uri->getHost()] +
            $this->getHeaders(true, true);
        if (!empty($cookie) && empty($headers['Cookie'])) {
            $headers['Cookie'] = $cookie;
        }
        $this->client->setHeaders($headers);

        /** Set method */
        $this->client->setMethod($this->getMethod());
        /** Set Upload file */
        $files = $this->getUploadedFiles();
        if (!empty($files)) {
            /** @var $file SwUploadFile */
            foreach ($files as $key => $file) {
                $file_options = [
                    $file->getFilePath(),
                    $key
                ];
                if ($file_type = $file->getClientMediaType()) {
                    $file_options[] = $file_type;
                }
                if ($filename = $file->getClientFilename()) {
                    $file_options[] = $filename;
                }
                if ($file_offset = $file->getOffset()) {
                    $file_options[] = $file_offset;
                }
                if ($file_size = $file->getSize()) {
                    $file_options[] = $file_size;
                }
                $this->client->addFile(...$file_options);
            }
        }
        /** 设置请求主体 */
        $body = (string)($this->getBody() ?? '');
        if ($body !== '') {
            $this->client->setData($body);
        }

        parse_str($this->uri->getQuery(), $query);
        $query = $this->getQueryParams() + $query; //attribute value first
        $query = http_build_query($query);

        $path = $this->uri->getPath() ?: '/';
        $path = empty($query) ? $path : $path . '?' . $query;

        /** calc timeout value */
        if ($this->_redirect_times > 0) {
            $timeout = $this->getTimeout() - (microtime(true) - $this->_start_time);
            //TODO timeout exception
        } else {
            $this->_start_time = microtime(true);
            $timeout = $this->getTimeout();
        }
        $this->_timeout = max($timeout, 0.001); //swoole support min 1ms

        /** 设定配置项 */
        $settings = [
            'timeout' => (($this->_form_flag & self::FROM_REDIRECT) && $this->_timeout) ? $this->_timeout : $this->getTimeout(),
            'keep_alive' => $this->getKeepAlive(),
        ];
        $settings += $this->getProxy();

        if (!empty($ca_file = $this->getCAFile())) {
            $settings += $this->getSSLConf();
        }
        $this->client->set($settings);

        /** Set defer and timeout */
        $this->client->setDefer(); //总是延迟回包以使用timeout定时器特性

        if (empty($this->download_dir)) {
            $this->client->execute($path);
        } else {
            $this->client->download($path, $this->download_dir, $this->download_offset);
            // reset: download mode only once
            $this->download_dir = '';
            $this->download_offset = 0;
        }
        $this->_status = self::STATUS_WAITING;

        return $this;
    }
603769
public function call()
    {
        $ch = curl_init();
        curl_setopt_array($ch, [
            CURLOPT_URL            => $this->getApiUrl().'?'.http_build_query($this->getOptions()),
            CURLOPT_HEADER         => 0,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT        => $this->timeout,
        ]);
        $this->response = curl_exec($ch);
        curl_close($ch);

        return $this;
    }
1370066
public function run()
    {
        header('HTTP/1.1 200 OK');
        header('Content-Type: text/event-stream;charset=UTF-8');
        header('Cache-Control: no-cache, no-store, max-age=0, must-revalidate');
        header('Pragma: no-cache');

        while (1) {
            $stats = $this->metricsPoller->getStatsForCommandsRunning();

            if (empty($stats)) {
                echo "ping: \n\n";
            } else {
                foreach ($stats as $commandStats) {
                    echo "data: " . json_encode($commandStats) . "\n\n";
                }
            }

            ob_flush();
            flush();
            usleep($this->delay * 1000);
        }
    }
472531
public function main()
    {
        $ec2 = $this->getService();

        $instance = $ec2->describeInstances([
            'InstanceIds' => [$this->getInstanceId()]
        ]);

        $tag = array_filter(
            $instance['Reservations'][0]['Instances'][0]['Tags'],
            function ($tag) {
                return $tag['Key'] == 'aws:autoscaling:groupName';
            }
        );
        
        $this->project->setProperty($this->getProperty(), array_shift($tag)['Value']);
    }
1188063
public function handle()
    {
        Base::getLog()->debug(__METHOD__ . ' handle main flow - start');

        if ( ! Route::exists('default'))
        {
            Base::getLog()->debug(__METHOD__ . ' set default route');
            Route::set('default', '(<controller>(/<action>(/<id>)))')
                ->defaults([
                    'controller' => 'Site',
                    'action'     => 'index',
                ]);
        }

        $this->flow->contexts['uri'] = Url::detectUri();

        Base::getLog()->debug(__METHOD__ . ' handle main flow - end');
    }
114824
public function exec() {

            // First we'll be looping through the headers to see if there's anything we reconize

            foreach($this->getRequestHeaders() as $header) {

                switch($header['name']) {

                    // We found a credentials headers, calling the authenticate method
                    case 'Credentials' :
                        $this->authenticate($header['data']['userid'],$header['data']['password']);
                        break;

                }

            }

            foreach($this->getRequests() as $request) {

                // Default AMFVersion
                $AMFVersion = 0;

                $response = null;

                try {

                    if (is_array($request['data']) && isset($request['data'][0]) && $request['data'][0] instanceof SabreAMF_AMF3_AbstractMessage) {
                        $request['data'] = $request['data'][0];
                    }

                    // See if we are dealing with the AMF3 messaging system
                    if (is_object($request['data']) && $request['data'] instanceof SabreAMF_AMF3_AbstractMessage) {
            
                        $AMFVersion = 3;
                       
                        // See if we are dealing with a CommandMessage
                        if ($request['data'] instanceof SabreAMF_AMF3_CommandMessage) {

                            // Handle the command message 
                            $response = $this->handleCommandMessage($request['data']);
                        }

                        // Is this maybe a RemotingMessage ?
                        if ($request['data'] instanceof SabreAMF_AMF3_RemotingMessage) {

                            // Yes
                            $response = new SabreAMF_AMF3_AcknowledgeMessage($request['data']);
                            $response->body = $this->invokeService($request['data']->source,$request['data']->operation,$request['data']->body);

                        }

                    } else {

                        // We are dealing with AMF0
                        $service = substr($request['target'],0,strrpos($request['target'],'.'));
                        $method  = substr(strrchr($request['target'],'.'),1);
                        
                        $response = $this->invokeService($service,$method,$request['data']);

                    }

                    $status = SabreAMF_Const::R_RESULT;

                } catch (Exception $e) {

                    // We got an exception somewhere, ignore anything that has happened and send back
                    // exception information

                    if ($e instanceof SabreAMF_DetailException) {
                        $detail = $e->getDetail();
                    } else {
                        $detail = '';
                    }

                    switch($AMFVersion) {
                        case SabreAMF_Const::AMF0 :
                            $response = array(
                                'description' => $e->getMessage(),
                                'detail'      => $detail,
                                'line'        => $e->getLine(), 
                                'code'        => $e->getCode()?$e->getCode():get_class($e),
                            );
                            break;
                        case SabreAMF_Const::AMF3 :
                            $response = new SabreAMF_AMF3_ErrorMessage($request['data']);
                            $response->faultString = $e->getMessage();
                            $response->faultCode   = $e->getCode();
                            $response->faultDetail = $detail;
                            break;

                    }
                    $status = SabreAMF_Const::R_STATUS;
                }

                $this->setResponse($request['response'],$status,$response);

            }
            $this->sendResponse();

        }
275353
public function start()
    {
        $__scope = $this->_runHooks($this->_startHooks);
        extract($__scope);
        
        $this->_write($this->_socket, self::READY);
        
        /* Note the naming of the local variables due to shared scope with the user here */
        for (;;) {
            declare (ticks = 1);
            // don't exit on ctrl-c
            pcntl_signal(SIGINT, SIG_IGN, true);
            
            $this->_cancelled = false;
            
            $__input = $this->_transform($this->_read($this->_socket));
            
            if ($__input === null) {
                continue;
            }
            
            $__response = self::DONE;
            
            $this->_ppid = posix_getpid();
            $this->_pid  = pcntl_fork();
            
            if ($this->_pid < 0) {
                throw new \RuntimeException('Failed to fork child labourer');
            } elseif ($this->_pid > 0) {
                // kill the child on ctrl-c
                pcntl_signal(SIGINT, array(
                    $this,
                    'cancelOperation'
                ), true);
                pcntl_waitpid($this->_pid, $__status);
                
                if (!$this->_cancelled && $__status != (self::ABNORMAL_EXIT << 8)) {
                    $__response = self::EXITED;
                } else {
                    $this->_runHooks($this->_failureHooks);
                    $__response = self::FAILED;
                }
            } else {
                // if the user has installed a custom exception handler, install a new
                // one which calls it and then (if the custom handler didn't already exit)
                // exits with the correct status.
                // If not, leave the exception handler unset; we'll display
                // an uncaught exception error and carry on.
                $__oldexh = set_exception_handler(array(
                    $this,
                    'delegateExceptionHandler'
                ));
                if ($__oldexh && !$this->_userExceptionHandler) {
                    $this->_userExceptionHandler = $__oldexh; // save the old handler (once)
                } else {
                    restore_exception_handler();
                }
                
                // undo ctrl-c signal handling ready for user code execution
                pcntl_signal(SIGINT, SIG_DFL, true);
                $__pid = posix_getpid();
                
                $__result = eval($__input);
                
                if (posix_getpid() != $__pid) {
                    // whatever the user entered caused a forked child
                    // (totally valid, but we don't want that child to loop and wait for input)
                    exit(0);
                }
                
                if (preg_match('/\s*return\b/i', $__input)) {
                    fwrite(STDOUT, sprintf("%s\n", $this->_inspector->inspect($__result)));
                }
                $this->_expungeOldWorker();
            }
            
            $this->_write($this->_socket, $__response);
            
            if ($__response == self::EXITED) {
                exit(0);
            }
        }
    }
214148
public function execute() {

		// Register all handles and monitor that
		// all requests are executed
		$handleExecutionCounter = array();

		foreach( $this->httpRequests as $httpRequest ) {
			$httpRequest->setOption( CURLOPT_RETURNTRANSFER, true );
			$handleExecutionCounter[(int)  $httpRequest() ] = true;
			curl_multi_add_handle( $this->handle, $httpRequest() );
		}

		$response = $this->doMakeMultiRequest( $handleExecutionCounter );

		return $response;
	}
770648
public static function getHttpClient()
    {
        if(self::$httpClient) {
            return self::$httpClient;
        }
        $client = new Client();
        return self::$httpClient = $client;
    }
113037
public function handleRequest()
    {
        $sequence = $this->bootstrap->buildRuntimeSequence();
        $sequence->invoke($this->bootstrap);

        $objectManager = $this->bootstrap->getObjectManager();
        /** @var LoggerInterface $logger */
        $logger = $objectManager->get(PsrLoggerFactoryInterface::class)->get('systemLogger');

        $logger->debug('Running sub process loop.');
        echo "\nREADY\n";

        try {
            while (true) {
                $commandLine = trim(fgets(STDIN));
                $trimmedCommandLine = trim($commandLine);
                $logger->info(sprintf('Received command "%s".', $trimmedCommandLine), LogEnvironment::fromMethodName(__METHOD__));
                if ($commandLine === "QUIT\n") {
                    break;
                }
                /** @var Request $request */
                $request = $objectManager->get(RequestBuilder::class)->build($trimmedCommandLine);
                $response = new Response();
                if ($this->bootstrap->isCompiletimeCommand($request->getCommand()->getCommandIdentifier())) {
                    echo "This command must be executed during compiletime.\n";
                } else {
                    $objectManager->get(Dispatcher::class)->dispatch($request, $response);
                    $response->send();

                    $this->emitDispatchedCommandLineSlaveRequest();
                }
                echo "\nREADY\n";
            }

            $logger->debug('Exiting sub process loop.');
            $this->bootstrap->shutdown(Bootstrap::RUNLEVEL_RUNTIME);
            exit($response->getExitCode());
        } catch (\Exception $exception) {
            $this->handleException($exception);
        }
    }
955027
protected function constructHttpClient()
    {
        $hasHttpClient = (null !== $this->httpClient);

        $this->httpClient = new HttpClient($this->getOptions());

        if (!$hasHttpClient) {
            $this->httpClient->registerDefaults();
        }
    }
1310914
protected function getHttpClient()
    {
        if (is_null($this->httpClient)) {

            $handlerStack = $this->createHandlerStack();

            return new Guzzle([
                'base_uri' => rtrim($this->api['href'],'/').'/',
                'handler' => $handlerStack,
            ]);
        }

        return $this->httpClient;
    }
836366
public static function current () {
      if ( php_sapi_name() == 'cli' )
        throw new Exception ( 'Cannot generate an HTTP request from CLI.' );
      
      // collect headers from _SERVER
      $headers = array();
      foreach ( Request::$phpHeaderMap as $phpName => $httpName )
        if ( isset( $_SERVER[$phpName] ) )
          $headers[$httpName] = $_SERVER[$phpName];
        
      return new Request (
        $_SERVER['REQUEST_URI'],
        $_REQUEST,
        $_POST,
        $_FILES,
        strtoupper( $_SERVER['REQUEST_METHOD'] ),
        $headers,
        $_SERVER['REMOTE_ADDR'],
        isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' ? TRUE : FALSE
      );
    }
646558
protected function executeCommand()
    {
        static $methods = [
            'HEAD',
            'GET',
            'POST',
            'PUT',
            'DELETE'
        ];

        \Akamai\Open\EdgeGrid\Client::setDebug(true);
        \Akamai\Open\EdgeGrid\Client::setVerbose(true);

        $args = $this->climate->arguments->all();
        $client = new Client();

        if ($this->climate->arguments->defined('auth-type')) {
            $auth = $this->climate->arguments->get('auth');
            if ($this->climate->arguments->get('auth-type') === 'edgegrid' ||
                (!$this->climate->arguments->defined('auth-type'))) {
                $section = 'default';
                if ($this->climate->arguments->defined('auth')) {
                    $section = (substr($auth, -1) === ':') ? substr($auth, 0, -1) : $auth;
                }
                $client = Client::createFromEdgeRcFile($section);
            }

            if (in_array($this->climate->arguments->get('auth-type'), ['basic', 'digest'])) {
                if (!$this->climate->arguments->defined('auth') || $this->climate->arguments->get('auth') === null) {
                    $this->help();
                    return;
                }

                $auth = [
                    $auth,
                    null,
                    $this->climate->arguments->get('auth-type')
                ];

                if (strpos(':', $auth[0]) !== false) {
                    list($auth[0], $auth[1]) = explode(':', $auth[0]);
                }

                $client = new Client(['auth' => $auth]);
            }
        }

        $method = 'GET';
        $options = [];
        $body = [];

        foreach ($args as $arg) {
            $value = $arg->value();
            if (empty($value) || is_bool($value) || $arg->longPrefix()) {
                continue;
            }

            if (in_array(strtoupper($value), $methods)) {
                $method = $arg->value();
                continue;
            }

            if (!isset($url) && preg_match('@^(http(s?)://|:).*$@', trim($value))) {
                $url = $value;

                if ($url{0} === ':') {
                    $url = substr($url, 1);
                }

                continue;
            }

            $matches = [];
            if (preg_match('/^(?<key>.*?):=(?<file>@?)(?<value>.*?)$/', $value, $matches)) {
                if (!$value = $this->getArgValue($matches)) {
                    return false;
                }

                $body[$matches['key']] = json_decode($value);
                continue;
            }

            if (preg_match('/^(?<header>.*?):(?<value>.*?)$/', $value, $matches)
                && !preg_match('@^http(s?)://@', $value)) {
                $options['headers'][$matches['header']] = $matches['value'];
                continue;
            }

            if (preg_match('/^(?<key>.*?)=(?<file>@?)(?<value>.*?)$/', $value, $matches)) {
                if (!$value = $this->getArgValue($matches)) {
                    return false;
                }

                $body[$matches['key']] = $matches['value'];
                continue;
            }

            if (!isset($url)) {
                $url = $value;
                continue;
            }

            $this->help();
            $this->climate->error('Unknown argument: ' . $value);

            return false;
        }

        $stdin = '';
        $fp = fopen('php://stdin', 'rb');
        if ($fp) {
            stream_set_blocking($fp, false);
            $stdin = fgets($fp);
            if (!empty(trim($stdin))) {
                while (!feof($fp)) {
                    $stdin .= fgets($fp);
                }
                fclose($fp);
            }
            $stdin = rtrim($stdin);
        }

        if (!empty($stdin) && !empty($body)) {
            $this->help();
            $this->climate->error(
                'error: Request body (from stdin or a file) and request data (key=value) cannot be mixed.'
            );
            return;
        }

        if (!empty($stdin)) {
            $body = $stdin;
        }

        if (count($body) && !$this->climate->arguments->defined('form')) {
            if (!isset($options['headers']['Content-Type'])) {
                $options['headers']['Content-Type'] = 'application/json';
            }
            if (!isset($options['headers']['Accept'])) {
                $options['headers']['Accept'] = 'application/json';
            }
            $options['body'] = (!is_string($body)) ? json_encode($body) : $body;
        }

        if (count($body) && $this->climate->arguments->defined('form')) {
            if (!isset($options['headers']['Content-Type'])) {
                $options['headers']['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
            }

            $options['body'] = (!is_string($body)) ? http_build_query($body, null, null, PHP_QUERY_RFC1738) : $body;
        }

        $options['allow_redirects'] = false;
        if ($this->climate->arguments->defined('follow')) {
            $options['allow_redirects'] = true;
        }

        return $client->request($method, $url, $options);
    }
790417
protected function command()
    {
        $api = $this->option('api') ? ' --api '  : '';
        $action = $this->argument('action') ? ' ' . $this->argument('action') . ' ' : '';
        return 'php artisan make:route ' . $this->argument('link') . $action . ' --type=' . $this->option('type') .
            ' --method=' . $this->option('method') .
            $api .
            ' -a --menu';
    }