@param \swoole_http_request $swooleRequest

@return string
324655
private function transformProtocolVersion(\swoole_http_request $swooleRequest)
    {
        if (
            isset($swooleRequest->server['server_protocol']) &&
            0 !== preg_match('+/(?P<ver>\d\.\d)$+', $swooleRequest->server['server_protocol'], $matches)
        ) {
            return $matches['ver'];
        } else {
            return '1.1';
        }
    }
969892
private function getTokenFromQuery(ServerRequestInterface $request): ?string
    {
        $query_params = $request->getQueryParams();

        return $this->getAccessTokenFromParameters($query_params);
    }
1160955
public function makeRequest(Google_HttpRequest $request) {
    // First, check to see if we have a valid cached version.
    $cached = $this->getCachedRequest($request);
    if ($cached !== false) {
      if (!$this->checkMustRevaliadateCachedRequest($cached, $request)) {
        return $cached;
      }
    }

    $default_options = stream_context_get_options(stream_context_get_default());

    $requestHttpContext = array_key_exists('http', $default_options) ?
        $default_options['http'] : array();
    if (array_key_exists($request->getRequestMethod(),
          self::$ENTITY_HTTP_METHODS)) {
      $request = $this->processEntityRequest($request);
    }

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

    $requestHeaders = $request->getRequestHeaders();
    if ($requestHeaders && is_array($requestHeaders)) {
      $headers = "";
      foreach($requestHeaders as $k => $v) {
        $headers .= "$k: $v\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);

    $response_data = file_get_contents($request->getUrl(),
                                       false,
                                       $context);

    if (false === $response_data) {
      throw new Google_IOException("HTTP Error: Unable to connect");
    }

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

    if ($respHttpCode == 304 && $cached) {
      // If the server responded NOT_MODIFIED, return the cached request.
      $this->updateCachedRequest($cached, $responseHeaders);
      return $cached;
    }

    $request->setResponseHttpCode($respHttpCode);
    $request->setResponseHeaders($responseHeaders);
    $request->setResponseBody($response_data);
    // Store the request in cache (the function checks to see if the request
    // can actually be cached)
    $this->setCachedRequest($request);
    return $request;
  }
204282
function parseBody(Swoole\Request $request)
    {
        $cd = strstr($request->header['Content-Type'], 'boundary');
        if (isset($request->header['Content-Type']) and $cd !== false)
        {
            $this->parseFormData($request, $cd);
        }
        else
        {
            if (substr($request->header['Content-Type'], 0, 33) == 'application/x-www-form-urlencoded')
            {
                parse_str($request->body, $request->post);
            }
        }
    }
1341518
public function getResponse(HttpRequest $request)
    {
        $uri = $request->getUrl();

        $headers = $request->getHeaders();
        $flatHeaders = [];

        foreach ($headers as $key => $value) {
            $flatHeaders[] = $key . ": " . $value;
        }

        $flatHeaders[] = 'Connection: Keep-Alive';
        $flatHeaders[] = 'Expect:';
        $flatHeaders[] = 'Accept-Language: en-GB';
        $flatHeaders[] = 'Cache-Control: no-cache';
        $flatHeaders[] = 'User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)';

        $curl = curl_init($uri);

        curl_setopt($curl, CURLOPT_HEADER, false);

        $payload = $request->getPayload();

        switch ($request->getMethod()) {
            case "head":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "HEAD");
                break;
            case "delete":
                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
            case "post":
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);
                break;
            case "put":
                curl_setopt($curl, CURLOPT_POST, true);
                curl_setopt($curl, CURLOPT_POSTFIELDS, $payload);

                curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
                break;
        }

        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $flatHeaders);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($curl);

        $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        curl_close($curl);

        $httpResponse = new HttpResponse();
        $httpResponse->setResponseBody($response);
        $httpResponse->setResponseCode($responseCode);

        return $httpResponse;
    }
1077373
public static function toString(RequestInterface $request)
    {
        $headers = self::serializeHeaders($request->getHeaders());
        $body    = (string) $request->getBody();
        $format  = '%s %s HTTP/%s%s%s';

        if (! empty($headers)) {
            $headers = "\r\n" . $headers;
        }
        if (! empty($body)) {
            $headers .= "\r\n\r\n";
        }

        return sprintf(
            $format,
            $request->getMethod(),
            $request->getRequestTarget(),
            $request->getProtocolVersion(),
            $headers,
            $body
        );
    }
679658
private function getOverrideMethod(ServerRequestInterface $request): string
    {
        if ($request->getMethod() === 'POST' && $this->parsedBodyParameter !== null) {
            $params = $request->getParsedBody();

            if (isset($params[$this->parsedBodyParameter])) {
                return strtoupper($params[$this->parsedBodyParameter]);
            }
        } elseif ($request->getMethod() === 'GET' && $this->queryParameter !== null) {
            $params = $request->getQueryParams();

            if (isset($params[$this->queryParameter])) {
                return strtoupper($params[$this->queryParameter]);
            }
        }

        return strtoupper($request->getHeaderLine(self::HEADER));
    }
190735
public function onRequest($swooleRequest, $swooleResponse)
    {
        $this->app->make('events')->dispatch('swoole.request');

        $this->resetOnRequest();
        $sandbox = $this->app->make(Sandbox::class);
        $handleStatic = $this->container->make('config')->get('swoole_http.handle_static_files', true);
        $publicPath = $this->container->make('config')->get('swoole_http.server.public_path', base_path('public'));

        try {
            // handle static file request first
            if ($handleStatic && Request::handleStatic($swooleRequest, $swooleResponse, $publicPath)) {
                return;
            }
            // transform swoole request to illuminate request
            $illuminateRequest = Request::make($swooleRequest)->toIlluminate();

            // set current request to sandbox
            $sandbox->setRequest($illuminateRequest);

            // enable sandbox
            $sandbox->enable();

            // handle request via laravel/lumen's dispatcher
            $illuminateResponse = $sandbox->run($illuminateRequest);

            // send response
            Response::make($illuminateResponse, $swooleResponse)->send();
        } catch (Throwable $e) {
            try {
                $exceptionResponse = $this->app
                    ->make(ExceptionHandler::class)
                    ->render(
                        $illuminateRequest,
                        $this->normalizeException($e)
                    );
                Response::make($exceptionResponse, $swooleResponse)->send();
            } catch (Throwable $e) {
                $this->logServerError($e);
            }
        } finally {
            // disable and recycle sandbox resource
            $sandbox->disable();
        }
    }
761849
protected function _getLogMessage($request, $exception)
    {
        $message = sprintf(
            '[%s] %s',
            get_class($exception),
            $exception->getMessage()
        );

        $message .= "\nRequest URL: " . $request->getRequestTarget();

        $referer = $request->getHeaderLine('Referer');
        if ($referer) {
            $message .= "\nReferer URL: " . $referer;
        }

        if ($exception instanceof InvalidResponse && $exception->getResponse()) {
            $message .= "\nProvider Response: " . $exception->getResponse()->getBody();
        }

        $message .= "\nStack Trace:\n" . $exception->getTraceAsString() . "\n\n";

        return $message;
    }
963389
function parseCookie(Swoole\Request $request)
    {
        $request->cookie = self::parseParams($request->header['Cookie']);
    }
758239
public static function crearDesdeSwoole(\swoole_http_request $req)
    {
        // Preparamos Metodo
        $metodo = $req->server['request_method'];

        // Preparamos URL
        $url = 'http';
        if (!empty($req->server['https']) && $req->server['https'] !== 'off') {
            $url .= 's';
        } elseif ($req->server['server_port'] == 443) {
            $url .= 's';
        }

        $url .= '://' . $req->header['host'];
        $url .= $req->server['request_uri'];
        if (isset($req->server['query_string'])) {
            $url .= '?' . $req->server['query_string'];
        }

        // Preparamos parámetros según método
        $parametros = [];
        if (!empty($req->post)) {
            $parametros = $req->post;
        }
        if ($metodo != 'GET' && isset($req->header['content-type'])) {
            $parametros = self::procesarParametros($req->rawContent(), $req->header['content-type'], $parametros);
        }

        // Preparamos cabeceras
        $cabeceras = [];
        foreach($req->header as $nombre => $valor) {
            $nombre = str_replace(' ', '-', ucwords(str_replace('-', ' ', $nombre)));
            if (isset($cabeceras[$nombre])) {
                if (is_array($cabeceras[$nombre])) {
                    $cabeceras[$nombre][] = $valor;
                } else {
                    $cabeceras[$nombre] = [$cabeceras[$nombre], $valor];
                }
            } else {
                $cabeceras[$nombre] = $valor;
            }
        }


        // Preparamos galletas
        $galletas = [];
        if (!empty($req->cookie)) {
            $galletas = $req->cookie;
        }

        // Preparamos arhivos
        $archivos = [];
        if (!empty($req->files)) {
            $archivos = $req->files;
        }

        // Iniciamos instancia de petición con los datos ya preparados
        $peticion = new Peticion($url, $metodo, $parametros, $cabeceras, $galletas, $archivos);

        // Preparamos IP del cliente
        $peticion->cliente_ip = $req->server['remote_addr'];
        if (isset($req->server['x-client-ip'])) {
            $peticion->cliente_ip = $req->server['x-client-ip'];
        } elseif (isset($req->server['x-real-ip'])) {
            $peticion->cliente_ip = $req->server['x-real-ip'];
        } elseif (isset($_SERVER['x-forwarded-for'])) {
            $peticion->cliente_ip = trim(explode(',', $_SERVER['x-forwarded-for'])[0]);
        }

        // Retornamos instancia iniciada
        return $peticion;
    }
970977
public static function renderRequestHeaders(RequestInterface $request): string
    {
        $renderedHeaders = '';
        $headers = $request->getHeaders();
        if ($headers instanceof Headers) {
            $renderedHeaders .= $headers->__toString();
        } else {
            foreach (array_keys($headers) as $name) {
                $renderedHeaders .= $request->getHeaderLine($name);
            }
        }

        return $renderedHeaders;
    }
617886
private function getMessage(ServerRequestInterface $request, Throwable $e): string
    {
        $message = $this->getMessageForError($e);
        // TODO : mettre ce bout de code dans une méthode "requestContext($request)" qui retournerai une string https://github.com/cakephp/cakephp/blob/2341c3cd7c32e315c2d54b625313ef55a86ca9cc/src/Error/BaseErrorHandler.php#L334
        $message .= "\nRequest URL: " . $request->getRequestTarget();
        $referer = $request->getHeaderLine('Referer');
        if ($referer) {
            $message .= "\nReferer URL: " . $referer;
        }
        $message .= "\n\n";

        return $message;
    }
213177
public static function createFromSwooleRequest(SwooleRequest $request)
    {
        if (isset($request->server)) {
            $keys = array_map('strtoupper', array_keys($request->server));
            $server = array_combine($keys, array_values($request->server));
        } else {
            $server = [];
        }
        
        if (isset($request->header)) {
            $keys = array_map(function ($value) {
                return 'HTTP_' . str_replace('-', '_', strtoupper($value));
            }, array_keys($request->header));
            $server = array_merge($server, array_combine($keys, array_values($request->header)));
        }
        
        $_GET = isset($request->get) ? $request->get : [];
        $_POST = isset($request->post) ? $request->post : [];
        $_FILES = isset($request->files) ? $request->files : [];
        $_COOKIE = isset($request->cookie) ? $request->cookie : [];
        $_SERVER = $server;
        
        return (new static($_GET, $_POST, [], $_COOKIE, $_FILES, $server))->setFd($request->fd);
    }
400765
protected function emitRestRequest(array $httpRequest)
    {
        $body = '';
        $headers = [
            'Content-type: application/json'
        ];

        if (array_key_exists('headers', $httpRequest['request'])) {
            foreach ($httpRequest['request']['headers'] as $header => $value) {
                $headers[] = ucfirst($header) . ': ' . $value;
            }
        }
        $headers[] = 'X-Kuzzle-Volatile: ' . json_encode(array_merge($this->getVolatile(), ['sdkVersion' => $this->getSdkVersion()]));

        if (array_key_exists('body', $httpRequest['request'])) {
            $body = json_encode($httpRequest['request']['body']);
            $headers[] = 'Content-length: ' . strlen($body);
        }

        $result = $this->requestHandler->execute([
            'url' => $this->url . $httpRequest['route'],
            'method' => $httpRequest['method'],
            'headers' => $headers,
            'body' => $body,
            'query_parameters' => $httpRequest['query_parameters']
        ]);

        if (!empty($result['error'])) {
            $this->emitEvent('queryError', $result['error'], $httpRequest);
            throw new ErrorException($result['error']);
        }

        $response = json_decode($result['response'], true);

        /**
         * @todo: manage custom exceptions
         */
        if (!empty($response['error'])) {
            $this->emitEvent('queryError', $response['error'], $httpRequest);
            throw new ErrorException($response['error']['message']);
        }

        return $response;
    }
878078
public function send(string $request): string
    {
        $stream = fopen(trim($this->url), 'rb', false, $this->buildContext($request));

        if (!is_resource($stream)) {
            throw new ConnectionFailureException('Unable to establish a connection');
        }

        $this->headers = $this->getDefaultHeaders();

        return stream_get_contents($stream);
    }
224219
public function match(IRequest $httpRequest)
	{
		if ($httpRequest->getHeader('Content-type') != 'application/json') {
			throw new BadRequestException('You can use only JSON!', 415);
		}

		$url = $httpRequest->getUrl();
		$basePath = str_replace('/', '\/', $url->getBasePath());
		$cleanPath = preg_replace("/^{$basePath}/", '', $url->getPath());
		$path = str_replace('/', '\/', $this->getPath());

		$pathRexExp = empty($path) ? "/^.+$/" : "/^{$path}\/.*$/";
		if (!preg_match($pathRexExp, $cleanPath)) {
			return null;
		}

		$path = preg_replace('/^' . $path . '\//', '', $cleanPath);

		$params = array();
		$params['action'] = $this->detectAction($httpRequest);
		$frags = explode('/', $path);

		if (count($frags) % 2 === 0) {
			// Resource ID.
			$id = array_pop($frags);
			if(is_numeric($id)) {
				$params['id'] = $id;
			}else{
				$params['specific_action'] = $id;
				$params['action'] .= ucfirst($id);
			}
		} elseif(count($frags) === 3) {
			$id = array_pop($frags);
			if(is_numeric($id)) {
				$params['id'] = $id;
				$params['specific_action'] = array_pop($frags);
				$params['action'] .= ucfirst($params['specific_action']);
			}else {
				$frags[] = $id;
			}
		}

		if ($params['action'] == 'read' && !@$params['id']) {
			$params['action'] = 'readAll';
		}

		$presenterName = ucfirst(array_pop($frags));

		// Allow to use URLs like domain.tld/presenter.format.
		if (Strings::match($presenterName, "/.+\.(json)$/")) {
			list($presenterName, $format) = explode('.', $presenterName);
		}

		// Associations.
		$assoc = array();
		if (count($frags) > 0 && count($frags) % 2 === 0) {
			foreach ($frags as $k => $f) {
				if ($k % 2 !== 0)
					continue;

				$assoc[$f] = $frags[$k + 1];
			}
		}

		$params['associations'] = $assoc;
		$params['query'] = $httpRequest->getQuery();
		$params['action'] = $this->path2action($params['action']);

		$presenterName = $this->path2presenter($presenterName);
		$presenterName = empty($this->module) ? $presenterName : $this->module . ':' . $presenterName;

		// Remember absolute URL for ::constructUrl(). It is one way route ;-).
		$this->requestUrl = $url->getAbsoluteUrl();

		return new Request(
			$presenterName,
			$httpRequest->getMethod(),
			$params
		);
	}