Execute an HTTP Request

@param Request $request the http request to be executed
@return array containing response headers, body, and http code
@throws Exception on curl or IO error
184558
public function executeRequest(Request $request)
  {
    $curl = curl_init();

    if ($request->getPostBody()) {
      curl_setopt($curl, CURLOPT_POSTFIELDS, $request->getPostBody());
    }

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $curlHeaders = array();
      foreach ($requestHeaders as $k => $v) {
        $curlHeaders[] = "$k: $v";
      }
      curl_setopt($curl, CURLOPT_HTTPHEADER, $curlHeaders);
    }
    curl_setopt($curl, CURLOPT_URL, $request->getUrl());

    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $request->getRequestMethod());
    curl_setopt($curl, CURLOPT_USERAGENT, $request->getUserAgent());

    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);

    // The SSL version will be determined by the underlying library
    // @see https://github.com/google/google-api-php-client/pull/644
    //curl_setopt($curl, CURLOPT_SSLVERSION, 1);

    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, true);

    if ($request->canGzip()) {
      curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
    }
    
    $options = $this->client->getClassConfig('Curl', 'options');
    if (is_array($options)) {
      $this->setOptions($options);
    }
    
    foreach ($this->options as $key => $var) {
      curl_setopt($curl, $key, $var);
    }

    if (!isset($this->options[CURLOPT_CAINFO])) {
      curl_setopt($curl, CURLOPT_CAINFO, dirname(__FILE__) . '/cacerts.pem');
    }

    $this->client->getLogger()->debug(
        'cURL request',
        array(
            'url' => $request->getUrl(),
            'method' => $request->getRequestMethod(),
            'headers' => $requestHeaders,
            'body' => $request->getPostBody()
        )
    );

    $response = curl_exec($curl);
    if ($response === false) {
      $error = curl_error($curl);
      $code = curl_errno($curl);
      $map = $this->client->getClassConfig('Exception', 'retry_map');

      $this->client->getLogger()->error('cURL ' . $error);
      throw new Exception($error, $code, null, $map);
    }
    $headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);

    list($responseHeaders, $responseBody) = $this->parseHttpResponse($response, $headerSize);
    $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    $this->client->getLogger()->debug(
        'cURL response',
        array(
            'code' => $responseCode,
            'headers' => $responseHeaders,
            'body' => $responseBody,
        )
    );

    return array($responseBody, $responseHeaders, $responseCode);
  }
461169
public function matchRequest(Request $request)
    {
        try {
            $parameters = parent::matchRequest($request);
            $this->matchedRouteRequest = $request;
            return $parameters;
        } catch (\Exception $e) {
            throw $e;
        }


    }
478546
public function parseRequest(Request $request)
    {
        try {
            $this->setPath($request->get('_route'));

            $this->setQuery($request->query->all());

            $this->setRouteParams($request->attributes->get('_route_params'));

            if ($request->get('page')) {
                $this->setCurrentPage((int)$request->get('page'));
            }

            if ($request->get('maxItems')) {
                $this->setNumberOfElementsPerPage((int)$request->get('maxItems'));
            }

        } catch (\Exception $e) {
            throw new \Exception ('The request provided is not a valid Request Object');
        }

        return $this;
    }
461891
public function postRequest( Request $request ) {
		$response = $this->getClient()->request(
			'POST',
			$this->apiUrl,
			$this->getClientRequestOptions( $request, $this->getPostRequestEncoding( $request ) )
		);

		return $this->decodeResponse( $response );
	}
116616
public function route(Request $request)
    {
        if ($request instanceof Request\Web) {
            $server = $request->getServer();
            if (!isset($server['REQUEST_URI'])) {
                throw new Exception('REQUEST_URI is not set');
            }
            $this->logger->debug('Routing of web request', ['REQUEST_URI' => $server['REQUEST_URI']]);
            $urlComponents = explode('?', $server['REQUEST_URI']);
            $destination = reset($urlComponents);
            if (strpos($destination, $this->entryPoint) === 0) {
                $destination = substr($destination, strlen($server['SCRIPT_NAME']));
            }
        } elseif ($request instanceof Request\Cli) {
            $argv = $request->getArgv();
            $destination = isset($argv[1]) ? $argv[1] : '/';
            $this->logger->debug('Routing of CLI request', ['argv' => $argv]);
        } elseif ($request instanceof Request\Virtual) {
            $this->logger->debug(
                'Routing of virtual request',
                ['controller' => $request->getController(), 'action' => $request->getAction()]
            );
            return new Route($request->getController(), $request->getAction());
        } else {
            throw new Exception('Request type not supported');
        }

        $destination = trim($destination, '/');
        $destination = empty($destination) ? '/' : $destination;

        $this->logger->debug('Searching for corresponding route', ['destination' => $destination]);

        return $this->getRoute($destination);
    }
945405
public function execute(Request $request)
    {

        $phases = ['prepare', 'respond', 'close'];
        $response = null;

        foreach ($phases as $phase) {

            $key = 0;

            if ($phase === 'respond' && is_null($response)) {
                throw new StackException;
            } else if ($phase === 'close' && $key === 0) {
                $response->send();
            }

            if ($phase === 'prepare' && count($this->{$phase . 'ableMiddlewares'}) === 0) {
                throw new StackException('You must at least add one prepareableMiddleware that generates a Response.');
            } else if (count($this->{$phase . 'ableMiddlewares'}) === 0) {
                continue;
            }

            $next_middleware_spec = $this->{$phase . 'ableMiddlewares'}[$key];

            //Use a while so that middlewares can add other middlewares to execute
            while ($next_middleware_spec) {
                //Get the middleware
                $middleware = array_shift($next_middleware_spec);

                if (!is_null($response)) {
                    array_unshift($next_middleware_spec, $response);
                }

                //Put request as first parameter for the middleware
                array_unshift($next_middleware_spec, $request);

                $return = call_user_func_array([$middleware, $phase], $next_middleware_spec);

                if ($phase === 'prepare' && $return instanceof Response) {
                    $response = $return;
                    break;
                } else if ($phase === 'respond') {
                    //Reassign response in case it was recreated during that phase
                    $response = $return;
                }
                $key++;
                $next_middleware_spec = isset($this->{$phase . 'ableMiddlewares'}[$key]) ? $this->{$phase . 'ableMiddlewares'}[$key] : false;
            }
        }
    }
1207018
public function sendRequest(Request $request)
	{
		$this->prepareRequest($request);

		$result = curl_exec($this->ch);

		if ($result === false) {
			$errno = curl_errno($this->ch);
			$errmsg = curl_error($this->ch);
			$msg = "cURL request failed with error [$errno]: $errmsg";
			curl_close($this->ch);
			throw new cURLException($request, $msg, $errno);
		}

		$response = $this->createResponseObject($result);

		curl_close($this->ch);

		return $response;
	}
1231363
public function execute($request)
	{
		$router = $request->getRouter();
		$builder = new \Ergo\Http\ResponseBuilder();

		// these parameters are interpolated into the redirected url
		$params = $request->getRouteMatch()->getParameters();

		// TODO: return a full RFC compliant url
		return $builder
			->found($router->buildUrl($this->_route, $params))
			->build()
			;
	}
110595
public function handle(Request $request)
	{
		$response = $this->next($request);

		$arguments = $this->app['arguments'];
		$output    = $this->app['output'];

		// Check for interactivity flag and set on output accordingly
		if ($arguments->getOpt('non-interactive'))
		{
			$output->makeNonInteractive();
		}

		// Check for color flag and set on output accordingly
		if ($arguments->getOpt('no-colors'))
		{
			$output->makeUnColored();
		}

		// If task is help, set the output to our output class with extra methods for rendering help doc
		if ($arguments->get('task') == 'help')
		{
			$output = $output->getHelpOutput();
		}

		// If the format opt is present, try to use the appropriate output subclass
		if ($arguments->getOpt('format'))
		{
			$output = $output->getOutputFormatter($arguments->getOpt('format'));
		}

		// Register any user specific events
		if ($hooks = Config::get('hooks'))
		{
			foreach ($hooks as $trigger => $scripts)
			{
				foreach ($scripts as $script)
				{
					Event::register($trigger, function() use ($script, $output)
					{
						if ($output->getMode() != 'minimal')
						{
							$output->addLine("Running '{$script}'");
						}
						shell_exec(escapeshellcmd($script));
					});
				}
			}
		}

		// Reset the output stored on the application
		$this->app->forget('output');
		$this->app->set('output', $output);

		return $response;
	}
249152
public function do_request($request)
    {
        $http = [];

        $http['method'] = $request->method;

        $headers = [];
        foreach ($request->headers as $k => $v) {
            $headers[] = is_string($k) ? "$k: $v" : $v;
        }

        if (isset($request->options['proxy'])) {
            $parts = parse_url($request->options['proxy']);
            if ($parts['scheme'] !== 'http') {
                throw new NotSupportedException(['only support http type proxy: `:proxy`', 'proxy' => $request->options['proxy']]);
            }

            if (isset($parts['pass'])) {
                $headers[] = 'Proxy-Authorization: Basic ' . base64_encode($parts['user'] . ':' . $parts['pass']);
            }
            $http['proxy'] = 'tcp://' . $parts['host'] . ':' . (isset($parts['port']) ? $parts['port'] : '80');
        }

        $http['header'] = $headers;

        if (is_string($request->body)) {
            $http['content'] = $request->body;
        } elseif (is_array($request->body)) {
            if (isset($options['Content-Type']) && strpos($request->headers['Content-Type'], 'json') !== false) {
                $http['content'] = json_encode($request->body, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
            } else {
                $http['content'] = http_build_query($request->body);
            }
        }

        $http['timeout'] = $request->options['timeout'];
        $http['ignore_errors'] = true;

        $ssl = [];
        $ssl['verify_peer'] = $request->options['verify_peer'];
        if (isset($request->options['allow_self_signed'])) {
            $ssl['allow_self_signed'] = $request->options['allow_self_signed'];
        } else {
            $ssl['allow_self_signed'] = !$request->options['verify_peer'];
        }

        if (isset($request->options['cafile'])) {
            $ssl['cafile'] = $this->alias->resolve($request->options['cafile']);
        }

        $start_time = microtime(true);

        if (!$stream = @fopen($request->url, 'rb', false, stream_context_create(['http' => $http, 'ssl' => $ssl]))) {
            throw new ConnectionException(['`:url`: `:last_error_message`', 'url' => $request->url]);
        }
        $meta = stream_get_meta_data($stream);
        $body = stream_get_contents($stream);
        fclose($stream);

        $process_time = round(microtime(true) - $start_time, 3);

        $headers = $meta['wrapper_data'];

        for ($i = count($headers) - 1; $i >= 0; $i--) {
            $header = $headers[$i];
            /** @noinspection NotOptimalIfConditionsInspection */
            if (strpos($header, ':') === false && $headers !== '') {
                break;
            }
        }

        if ($i !== 0) {
            $headers = array_slice($headers, $i);
        }

        $content_type = null;
        foreach ($headers as $header) {
            if (strpos($header, 'Content-Type:') === 0) {
                $content_type = trim(substr($header, 13));
                break;
            }
        }

        $http_code = null;
        if ($headers && preg_match('#\d{3}#', $headers[0], $match)) {
            $http_code = (int)$match[0];
        }

        $response = new Response();
        $response->url = $request->url;
        $response->remote_ip = null;
        $response->http_code = $http_code;
        $response->headers = $headers;
        $response->process_time = 0;
        $response->content_type = $content_type;
        $response->body = $body;
        $response->process_time = $process_time;

        return $response;
    }
204472
public function doRequest($request)
    {
        $inputStream = fopen('php://memory', 'r+');
        $content = $request->getContent();
        if ($content !== null) {
            fwrite($inputStream, $content);
            rewind($inputStream);
        }

        $queryParams = [];
        $postParams = [];
        $queryString = parse_url($request->getUri(), PHP_URL_QUERY);
        if ($queryString != '') {
            parse_str($queryString, $queryParams);
        }
        if ($request->getMethod() !== 'GET') {
            $postParams = $request->getParameters();
        }

        $serverParams = $request->getServer();
        if (!isset($serverParams['SCRIPT_NAME'])) {
            //required by WhoopsErrorHandler
            $serverParams['SCRIPT_NAME'] = 'Codeception';
        }
        
        $cookies = $request->getCookies();
        $headers = $this->extractHeaders($request);

        //set cookie header because dflydev/fig-cookies reads cookies from header
        if (!empty($cookies)) {
            $headers['cookie'] = implode(';', array_map(function ($key, $value) {
                return "$key=$value";
            }, array_keys($cookies), $cookies));
        }

        $zendRequest = new ServerRequest(
            $serverParams,
            $this->convertFiles($request->getFiles()),
            $request->getUri(),
            $request->getMethod(),
            $inputStream,
            $headers,
            $cookies,
            $queryParams,
            $postParams
        );

        $this->request = $zendRequest;

        $cwd = getcwd();
        chdir(codecept_root_dir());

        if ($this->config['recreateApplicationBetweenRequests'] === true || $this->application === null) {
            $application = $this->initApplication();
        } else {
            $application = $this->application;
        }

        if (method_exists($application, 'handle')) {
            //Zend Expressive v3
            $response = $application->handle($zendRequest);
        } else {
            //Older versions
            $application->run($zendRequest);
            $response = $this->responseCollector->getResponse();
            $this->responseCollector->clearResponse();
        }

        chdir($cwd);

        return new Response(
            (string)$response->getBody(),
            $response->getStatusCode(),
            $response->getHeaders()
        );
    }
11158
protected function send(Request $request)
    {
        try {
            $response = $this->client->send($request);
        } catch (ClientException $e) {
            $response = $e->getResponse();
        } catch (ServerException $e) {
            $response = $e->getResponse();
        }

        return $response;
    }
223650
protected function doRequest($request)
    {
        if (!$this->firstRequest) {
            $this->initialize($request);
        }
        $this->firstRequest = false;

        $this->applyBindings();
        $this->applyContextualBindings();
        $this->applyInstances();
        $this->applyApplicationHandlers();

        $request = Request::createFromBase($request);
        $response = $this->kernel->handle($request);

        $method = new \ReflectionMethod(get_class($this->app), 'callTerminableMiddleware');
        $method->setAccessible(true);
        $method->invoke($this->app, $response);

        return $response;
    }
561350
public function executeCurlRequest($request)
    {
        $result = $this->request->cPost($request->getRequestUrl(), $this->config['cacert'], $request->params(), $this->getCharset());

        return $result;
    }
232772
public function execute(Request $request)
    {
        if (!$this->requireProvider("Executing cache request")) return null;

        $cacheKey = $request->getCacheKey();

        if (empty($cacheKey)) {
            if (!empty($this->log)) $this->log->error("Invalid or missing cache key.");
            return null;
        }

        $cacheRefresh = $request->getForceRefresh();

        if (!$cacheRefresh) {
            $cacheData = $this->cacheProvider->get($cacheKey);

            if (!empty($cacheData)) {
                if (!empty($this->log)) $this->log->debug("Cache hit on key " . $cacheKey);

                return $cacheData;
            }
        }

        if (!empty($this->log)) $this->log->debug("CACHE", "Cache miss on key " . $cacheKey);

        $value = $request->executeCallback();

        if (!empty($value)) {
            $this->cacheProvider->set($cacheKey, $value, $request->getCacheTTL());
        }

        return $value;
    }
1229018
public function handle(Request $request)
    {
        try {
            $this->loadConfiguration();

            // Now that Configuration is loaded let's resolve controller
            // for given request.
            $calls = $this->resolveController($request);
            $controller = $calls['controller'];
            $callable   = $calls['callable'];

            // Resolve arguments before calling controller
            $res = $controller->$callable();

            // Check if controller returned Response
            // and if so let's use it as our response
            if (is_a($res, 'Symfony\Component\HttpFoundation\Response')) {
                $this->response = $res;
            }

        } catch (\Exception $e) {
            $error = new \StdClass;
            $error->message = $e->getMessage();
            $error->code    = $e->getCode();
            $this->response->setStatusCode($e->getCode());
            $this->response->setContent(json_encode($error));
            $this->response->headers->set('Content-Type', 'application/json');
        }

        // Send response
        if ($request->getRequestFormat() == 'json') {
            $this->response->headers->set('Content-Type', 'application/json');
        }

        $this->response->send();

    }
384526
public function executeRequest(Google_Http_Request $request)
  {
    $default_options = stream_context_get_options(stream_context_get_default());

    $requestHttpContext = array_key_exists('http', $default_options) ?
        $default_options['http'] : array();

    if ($request->getPostBody()) {
      $requestHttpContext["content"] = $request->getPostBody();
    }

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $headers = "";
      foreach ($requestHeaders as $k => $v) {
        $headers .= "$k: $v\r\n";
      }
      $requestHttpContext["header"] = $headers;
    }

    $requestHttpContext["method"] = $request->getRequestMethod();
    $requestHttpContext["user_agent"] = $request->getUserAgent();

    $requestSslContext = array_key_exists('ssl', $default_options) ?
        $default_options['ssl'] : array();

    if (!array_key_exists("cafile", $requestSslContext)) {
      $requestSslContext["cafile"] = dirname(__FILE__) . '/cacerts.pem';
    }

    $options = array(
        "http" => array_merge(
            self::$DEFAULT_HTTP_CONTEXT,
            $requestHttpContext
        ),
        "ssl" => array_merge(
            self::$DEFAULT_SSL_CONTEXT,
            $requestSslContext
        )
    );

    $context = stream_context_create($options);

    $url = $request->getUrl();

    if ($request->canGzip()) {
      $url = self::ZLIB . $url;
    }

    $this->client->getLogger()->debug(
        'Stream request',
        array(
            'url' => $url,
            'method' => $request->getRequestMethod(),
            'headers' => $requestHeaders,
            'body' => $request->getPostBody()
        )
    );

    // We are trapping any thrown errors in this method only and
    // throwing an exception.
    $this->trappedErrorNumber = null;
    $this->trappedErrorString = null;

    // START - error trap.
    set_error_handler(array($this, 'trapError'));
    $fh = fopen($url, 'r', false, $context);
    restore_error_handler();
    // END - error trap.

    if ($this->trappedErrorNumber) {
      $error = sprintf(
          "HTTP Error: Unable to connect: '%s'",
          $this->trappedErrorString
      );

      $this->client->getLogger()->error('Stream ' . $error);
      throw new Google_IO_Exception($error, $this->trappedErrorNumber);
    }

    $response_data = false;
    $respHttpCode = self::UNKNOWN_CODE;
    if ($fh) {
      if (isset($this->options[self::TIMEOUT])) {
        stream_set_timeout($fh, $this->options[self::TIMEOUT]);
      }

      $response_data = stream_get_contents($fh);
      fclose($fh);

      $respHttpCode = $this->getHttpResponseCode($http_response_header);
    }

    if (false === $response_data) {
      $error = sprintf(
          "HTTP Error: Unable to connect: '%s'",
          $respHttpCode
      );

      $this->client->getLogger()->error('Stream ' . $error);
      throw new Google_IO_Exception($error, $respHttpCode);
    }

    $responseHeaders = $this->getHttpResponseHeaders($http_response_header);

    $this->client->getLogger()->debug(
        'Stream response',
        array(
            'code' => $respHttpCode,
            'headers' => $responseHeaders,
            'body' => $response_data,
        )
    );

    return array($response_data, $responseHeaders, $respHttpCode);
  }