Read API

@param Common\RequestInterface $request

@throws \InvalidArgumentException
@return OpenCalaisResponse
336241
public function read(Common\RequestInterface $request)
    {
        if (!$request instanceof OpenCalaisRequest) {
            throw new \InvalidArgumentException("Expected instance of OpenCalaisRequest, got ".get_class($request));
        }
        $this->request = $request;

        return $this->executeRequest();
    }
1006845
public function getParsedResponse(RequestInterface $request)
    {
        try {
            $response = $this->getResponse($request);
        } catch (BadResponseException $e) {
            $response = $e->getResponse();
        }

        $parsed = $this->parseResponse($response);

        $this->checkResponse($response, $parsed);

        return $parsed;
    }
1309157
public function parseQueryFromRequest(RequestInterface $request = null)
    {
        if ($request === null && $this->currentRequest === null) {
            throw new \InvalidArgumentException('No request is provided.');
        }

        $req = $request === null
            ? $this->currentRequest
            : $request;

        /* Rempli un array des paramètres de l'Uri. */
        parse_str($req->getUri()->getQuery(), $parseQuery);

        /*
         * Pour avoir le paramètre non identifié par une clé.
         * Exemple : http://exemple.com/?first_param = 'first_param'
         * Il faut prendre le 1er élément du tableau inversé des paraètres de l'Uri.
         */
        return !empty($parseQuery)
            ? rawurlencode(array_keys($parseQuery)[ 0 ])
            : '%2F';
    }
1199334
public function sendRequest(RequestInterface $request):ResponseInterface{
		$uri     = $request->getUri();
		$method  = $request->getMethod();
		$headers = $this->getRequestHeaders($request);

		$body    = \in_array($method, ['DELETE', 'PATCH', 'POST', 'PUT'], true)
			? $request->getBody()->getContents()
			: null;

		$context = \stream_context_create([
			'http' => [
				'method'           => $method,
				'header'           => $headers,
				'content'          => $body,
				'protocol_version' => '1.1',
				'user_agent'       => $this->options->user_agent,
				'max_redirects'    => 0,
				'timeout'          => 5,
			],
			'ssl' => [
				'cafile'              => $this->options->ca_info,
				'verify_peer'         => $this->options->ssl_verifypeer,
				'verify_depth'        => 3,
				'peer_name'           => $uri->getHost(),
				'ciphers'             => 'HIGH:!SSLv2:!SSLv3',
				'disable_compression' => true,
			],
		]);

		$requestUri = (string)$uri->withFragment('');

		\set_error_handler(function ($severity, $msg, $file, $line){
			throw new \ErrorException($msg, 0, $severity, $file, $line);
		});

		try{
			$responseBody    = \file_get_contents($requestUri, false, $context);
			$responseHeaders = $this->parseResponseHeaders(\get_headers($requestUri, 1, $context));
		}
		catch(\Exception $e){
			$this->logger->error('StreamClient error #'.$e->getCode().': '.$e->getMessage());

			throw new ClientException($e->getMessage(), $e->getCode());
		}

		\restore_error_handler();

		$response = $this->responseFactory
			->createResponse($responseHeaders['statuscode'], $responseHeaders['statustext'])
			->withProtocolVersion($responseHeaders['httpversion'])
		;

		$response->getBody()->write($responseBody);
		$response->getBody()->rewind();

		return $response;
	}
592149
public function next(RequestInterface $request)
    {
        if (!count($this->processingStack)) {
            throw new \RuntimeException('No middleware response created for stack.');
        }
        if (!($request instanceof ServerRequestInterface)) {
            throw new \InvalidArgumentException();
        }
        /** @var ServerMiddlewareInterface $middleware */
        $middleware = array_shift($this->processingStack);
        return $middleware->process($request, $this);
    }
111475
private function cacheKeyFromRequest(RequestInterface $request)
    {
        $uri = $request->getUri();

        $queryStr = $uri->getQuery();
        if (!empty($queryStr)) {
            $queryArr = [];

            parse_str($queryStr, $queryArr);

            $queryArr = $this->parseIgnoredParams($queryArr);
            $queryStr = http_build_query($queryArr);

            $uri = $uri->withQuery($queryStr);
        }

        $cacheKey = 'request/' . $request->getMethod() . '/' . md5((string)$uri);
        return $cacheKey;
    }
277693
protected function processResponse(
        RequestInterface $request,
        PsrRequestInterface $clientRequest,
        PsrResponseInterface $clientResponse
    ): ResponseInterface {
        $endpoint = $this->endpointService->getEndpointForRequest($request);
        $responseContents = $this->getContentsFromMessage($clientResponse);

        try {
            $result = $this->serializer->deserialize($responseContents, $endpoint->getResponseClass(), 'json');
        } catch (Exception $e) {
            $requestContents = $this->getContentsFromMessage($clientRequest);
            throw new InvalidResponseException($e->getMessage(), $requestContents, $responseContents, $e);
        }

        return $result;
    }
1102872
private function deEncodeRequestUrl(RequestInterface $request)
    {
        $query = $request->getUri()->getQuery();
        $decodedQuery = rawurldecode($query);

        $request->getUri()->withQuery($decodedQuery);

        return $request;
    }
508968
public function execute(RequestInterface $request): ResponseInterface
    {
        $this->supports($request);

        if ($request instanceof InputInterface) {
            $request->validate();
        }

        $client = $this->getClient();

        $data = array_replace($request->toArray(), [
            'carrier' => $client->getCarrier(),
            'key'     => $client->getKey(),
        ]);

        $response = $client->call($this->getMethodName(), $data);

        return $this->parseResponse($response->getBody()->getContents());
    }
1247390
protected function readResponse(RequestInterface $request, $socket): ResponseInterface
    {
        $headers = [];
        $reason = null;

        while (false !== ($line = fgets($socket))) {
            if ('' === rtrim($line)) {
                break;
            }
            $headers[] = trim($line);
        }

        $metadatas = stream_get_meta_data($socket);

        if (array_key_exists('timed_out', $metadatas) && true === $metadatas['timed_out']) {
            throw new TimeoutException('Error while reading response, stream timed out', $request, null);
        }

        $parts = explode(' ', array_shift($headers), 3);

        if (count($parts) <= 1) {
            throw new BrokenPipeException('Cannot read the response', $request);
        }

        $protocol = substr($parts[0], -3);
        $status = $parts[1];

        if (isset($parts[2])) {
            $reason = $parts[2];
        }

        // Set the size on the stream if it was returned in the response
        $responseHeaders = [];

        foreach ($headers as $header) {
            $headerParts = explode(':', $header, 2);

            if (!array_key_exists(trim($headerParts[0]), $responseHeaders)) {
                $responseHeaders[trim($headerParts[0])] = [];
            }

            $responseHeaders[trim($headerParts[0])][] = isset($headerParts[1])
                ? trim($headerParts[1])
                : '';
        }

        $response = new Response($status, $responseHeaders, null, $protocol, $reason);
        $stream = $this->createStream($socket, $request, $response);

        return $response->withBody($stream);
    }
856165
public static function fromPsrRequest(RequestInterface $request) {
		if (!$request->hasHeader('C-AAUID') || !$request->hasHeader('C-Access-Token'))
			return null;

		$context = new AccountContext(
			new IRI('aauid:'.$request->getHeaderLine('C-AAUID')),
				$request->getHeaderLine('C-Access-Token'));

		$context->parsePsrRequest($request);

		return $context;
	}
784580
public function process(RequestInterface $request)
    {
        if ($this->processingStack !== null) {
            throw new \RuntimeException('Middleware stack is already processing.');
        }
        if (!count($this->middlewares)) {
            throw new \RuntimeException('Middleware stack is empty.');
        }
        if (!($request instanceof ServerRequestInterface)) {
            throw new \InvalidArgumentException('ServerRequest request expected.');
        }
        $this->processingStack = array_reverse($this->middlewares);
        /** @var ServerMiddlewareInterface $middleware */
        $middleware = array_shift($this->processingStack);
        return $middleware->process($request, $this);
    }
1208049
public function handle(RequestInterface $request): ResponseInterface
    {
        if (!array_key_exists($this->index, $this->middlewares)) {
            return $this->response;
        }

        $current = $this->index;

        ++$this->index;

        $response = $this->container->call([$this->middlewares[$current], 'process'], [$request, $this]);

        return $response;
    }
1190909
public function execute(RequestInterface $request): RequestInterface
    {
        $body = $request->getBody()->getContents();

        $iv = random_bytes(self::INITIATION_VECTOR_LENGTH);
        $aesKey = random_bytes(self::AES_KEY_LENGTH);
        $encryptedAesKey = $this->publicKey->encrypt($aesKey);
        $bodyEncrypted = $this->determineBodyStringEncrypted($body, $aesKey, $iv);
        $hmac = $this->determineHmac($aesKey, $iv, $bodyEncrypted);
        $encryptedHeaders = [
            self::HEADER_CLIENT_ENCRYPTION_IV => [base64_encode($iv)],
            self::HEADER_CLIENT_ENCRYPTION_KEY => [base64_encode($encryptedAesKey)],
            self::HEADER_CLIENT_ENCRYPTION_HMAC => [base64_encode($hmac)],
        ];

        return new Request(
            $request->getMethod(),
            $request->getUri(),
            array_merge($request->getHeaders(), $encryptedHeaders),
            $bodyEncrypted
        );
    }
465230
protected function doRequest(RequestInterface $request)
    {
        $ch = $this->createHandle($request);

        // Execute the request and close the connection.
        $content = curl_exec($ch);

        $error = curl_error($ch);

        if (!$this->getOption('allow_empty_result', false) && !trim((string) $content)) {
            // Error but nothing from cURL? Create our own
            $error = $error ?: 'No HTTP response received';

            throw new HttpRequestException($error, curl_errno($ch));
        }

        if (!$this->getOption('ignore_curl_error', false) && $error !== '') {
            throw new HttpRequestException($error, curl_errno($ch));
        }

        // Get the request information.
        $info = curl_getinfo($ch);

        // Close the connection.
        curl_close($ch);

        return $this->getResponse($content, $info);
    }
769571
private function createRequest(RequestInterface $request)
    {
        $buzzRequest = new BuzzRequest();
        $buzzRequest->setMethod($request->getMethod());
        $buzzRequest->fromUrl($request->getUri()->__toString());
        $buzzRequest->setProtocolVersion($request->getProtocolVersion());
        $buzzRequest->setContent((string) $request->getBody());

        $this->addPsrHeadersToBuzzRequest($request, $buzzRequest);

        return $buzzRequest;
    }
1317593
function withRequestOnMatch(RequestInterface $request)
    {
        $requestTarget = $request->getRequestTarget();
        $requestTarget = new StdString($requestTarget);
        $requestTarget = $requestTarget->stripPrefix( rtrim($this->_stripPrefix, '/') );
        $request       = $request->withRequestTarget( (string) $requestTarget );

        return $request;
    }