@param \Psr\Http\Message\RequestInterface  $request
@param \Psr\Http\Message\ResponseInterface $response

@return \GuzzleHttp\Psr7\Uri
@throws \Exception
960347
protected function getRefreshUri(RequestInterface $request, ResponseInterface $response)
    {
        if (preg_match(static::REFRESH_EXPRESSION, $response->getHeaderLine('Refresh'), $matches)) {
            return new Uri($matches[1]);
        }

        return $this->solveJavascriptChallenge($request, $response);
    }
35682
private function sendErrorDocument(
        ResponseInterface $response): ResponseInterface
        {
        if ($this->errorDocument && preg_match(
                "/^(4|5){1}[0-2]{1}[0-9]{1}$/", $response->getStatusCode())
            ) {
            $this->errorDocument = str_replace(
                "{status}", $response->getStatusCode(), $this->errorDocument
            );
            if ($this->errorDocument !== filter_input(INPUT_SERVER, "REQUEST_URI")) {
                $response = $response->withHeader(
                    Response::HEADER_REFRESH,
                    "0; " . $this->errorDocument
                );
            }
        }
        return $response;
    }
338544
public function handle(
        ServerRequestInterface $request, ResponseInterface $response
    )
    {
        $path = array_key_exists(self::QUERY_PARAM, $request->getQueryParams())
            ? $request->getQueryParams()[self::QUERY_PARAM]
            : '';
        $uri = Uri::create($request->getUri());
        $queryString = ltrim(
            str_replace(
                self::QUERY_PARAM."={$path}",
                '',
                $uri->getQuery()
            ),
            '&'
        );
        $uri = $uri->withPath(str_replace('//', '/', "/$path"))
            ->withQuery($queryString);
        /** @var ServerRequestInterface $request */
        $request = $request->withUri($uri);
        return $this->executeNext($request, $response);
    }
1227204
public static function create(RequestInterface $request, ResponseInterface $response = null)
    {
        $uri = $request->getUri();

        if (is_null($response)) {
            return new static("No response error, uri: '$uri'");
        }

        // Extract error message from body
        $status = $response->getStatusCode();
        $json   = json_decode($response->getBody());
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new static("Cloudflare API error ($status) on: '$uri'", $status);
        }


        // Error message
        if (isset($json->errors) && count($json->errors) >= 1) {
            return new static($json->errors[0]->message . ", uri: '$uri'", $json->errors[0]->code);
        }

        // No success, but no error
        if (isset($json->success) && !$json->success) {
            return new static("Request was unsuccessful, uri: '$uri'");
        }

        // Unknown
        return new static("Unknown error, uri: '$uri'");

    }
1300977
protected function describe(RequestInterface $request, ResponseInterface $response = null)
    {
        if (!$response) {
            return sprintf('%s %s failed', $request->getMethod(), $request->getUri());
        }

        return sprintf(
            '%s %s returned %s %s',
            $request->getMethod(),
            $request->getUri(),
            $response->getStatusCode(),
            $response->getReasonPhrase()
        );
    }
1290348
protected function setUriHeader(Response $response, Request $request)
    {
        $response->header('X-PJAX-URL', $request->getRequestUri());

        return $this;
    }
670141
private function redirectUri(
        RequestInterface $request,
        ResponseInterface $response,
        array $protocols
    ) {
        $location = Psr7\UriResolver::resolve(
            $request->getUri(),
            new Psr7\Uri($response->getHeaderLine('Location'))
        );

        // Ensure that the redirect URI is allowed based on the protocols.
        if (!in_array($location->getScheme(), $protocols)) {
            throw new BadResponseException(
                sprintf(
                    'Redirect URI, %s, does not use one of the allowed redirect protocols: %s',
                    $location,
                    implode(', ', $protocols)
                ),
                $request,
                $response
            );
        }

        return $location;
    }
1010661
private function setRedirectUrl(
        RequestInterface $redirectRequest,
        ResponseInterface $response
    ) {
        $location = $response->getHeader('Location');
        $location = Url::fromString($location);

        // Combine location with the original URL if it is not absolute.
        if (!$location->isAbsolute()) {
            $originalUrl = Url::fromString($redirectRequest->getUrl());
            // Remove query string parameters and just take what is present on
            // the redirect Location header
            $originalUrl->getQuery()->clear();
            $location = $originalUrl->combine($location);
        }

        $redirectRequest->setUrl($location);
    }
878321
public function handleResponse(Request $request, Response $response)
    {
        if ($response->getStatusCode() == 422) {
            $errors = $response->getOriginalContent()['validation_errors'];

            throw new HttpResponseException(
                redirect()->back()->withInput($request->input())->withErrors($errors)
            );
        }

        if ($response->getStatusCode() == 403) {
            abort(403);
        }

        return $response->isNotFound() ? abort(404) : $response->getOriginalContent();
    }
974264
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        // We're not using straight-up $_GET, because we want everything to be
        // unit testable.
        $getVars = $request->getQueryParameters();

        // CSP headers
        $response->setHeader('Content-Security-Policy', "default-src 'none'; img-src 'self'; style-src 'self'; font-src 'self';");

        $sabreAction = isset($getVars['sabreAction']) ? $getVars['sabreAction'] : null;

        switch ($sabreAction) {
            case 'asset':
                // Asset handling, such as images
                $this->serveAsset(isset($getVars['assetName']) ? $getVars['assetName'] : null);

                return false;
            default:
            case 'info':
                try {
                    $this->server->tree->getNodeForPath($request->getPath());
                } catch (DAV\Exception\NotFound $e) {
                    // We're simply stopping when the file isn't found to not interfere
                    // with other plugins.
                    return;
                }

                $response->setStatus(200);
                $response->setHeader('Content-Type', 'text/html; charset=utf-8');

                $response->setBody(
                    $this->generateDirectoryIndex($request->getPath())
                );

                return false;

            case 'plugins':
                $response->setStatus(200);
                $response->setHeader('Content-Type', 'text/html; charset=utf-8');

                $response->setBody(
                    $this->generatePluginListing()
                );

                return false;
        }
    }
383773
private function decorateResponse(ResponseInterface $response)
    {
        if ($response instanceof Http\Response) {
            return $response;
        }

        return new Http\Response($this, $response);
    }
755766
public function httpGet(RequestInterface $request, ResponseInterface $response)
    {
        $queryParams = $request->getQueryParameters();
        if (!array_key_exists('mount', $queryParams)) {
            return;
        }

        $currentUri = $request->getAbsoluteUrl();

        // Stripping off everything after the ?
        list($currentUri) = explode('?', $currentUri);

        $this->davMount($response, $currentUri);

        // Returning false to break the event chain
        return false;
    }
245063
public static function factory(RequestInterface $request, Response $response)
    {
        $message = 'Client error response' . PHP_EOL . implode(PHP_EOL, array(
            '[status code] ' . $response->getStatusCode(),
            '[reason phrase] ' . $response->getReasonPhrase(),
            '[url] ' . $request->getUrl(),
        ));

        $e = new static($message);
        $e->setResponse($response);
        $e->setRequest($request);

        return $e;
    }
1148396
public function response(ServerRequestInterface $request, ResponseInterface $response)
    {
        // Throw Not Found
        //$this->response->exception(404);

        // Demo contents
        $contents = 'It works!';

        // PSR-7 JSON response
        return $this->response->dispatch($response, 200, $contents); // 202
    }
993423
protected function modifyRequest(RequestInterface $request, ResponseInterface $response)
    {
        sleep(8);

        return modify_request(
            $request,
            [
                'uri'         => UriResolver::resolve(
                    $request->getUri(),
                    $this->getRefreshUri($request, $response)
                ),
                'body'        => '',
                'method'      => 'GET',
                'set_headers' => [
                    'Referer'    => $request->getUri()->withUserInfo('', ''),
                ],
            ]
        );
    }
170255
public function execute(ServerRequestInterface $request, ResponseInterface $response) : ResponseInterface {
		$httpRequestResponse = new HTTPRequestResponseContainer($request, $response);

		$this->dispatchRequestFilters($httpRequestResponse);

		$this->dispatchResponseFilters($httpRequestResponse);

		return $httpRequestResponse->getResponse();
	}
641512
protected function saveToCache(
        RequestInterface $request,
        ResponseInterface $response
    ): bool {
        $key = $this->getCacheItemKey($request);

        try {
            $body = (string) $response->getBody();
            rewind_body($response);

            $cacheItem = $this
                ->cache
                ->getItem($key)
                ->expiresAfter(new \DateInterval($this->cacheTtl))
                ->set([
                    GuzzleClientMiddlewareInterface::BODY    => $body,
                    GuzzleClientMiddlewareInterface::HEADERS => $response->getHeaders(),
                    GuzzleClientMiddlewareInterface::STATUS  => $response->getStatusCode(),
                    GuzzleClientMiddlewareInterface::REASON  => $response->getReasonPhrase(),
                    GuzzleClientMiddlewareInterface::VERSION => $response->getProtocolVersion(),
                ]);
        } catch (InvalidArgumentException | \Exception $e) {
            if (null !== $this->logger) {
                $this->logger->error($e->getMessage());
            }

            return false;
        }

        $result = $this->cache->save($cacheItem);

        if ($result && null !== $this->logger) {
            $this->logger->info('Guzzle request result is saved to cache', [
                GuzzleClientMiddlewareInterface::URI => (string) $request->getUri(),
            ]);
        }

        return $result;
    }