cache response

@param string $requestUri
@param array $requestGetData
@param array $apiMethodInfoMetadata
@param string $responseData
@param $responseFormatClass
@param array $responseHeaders
493586
public function cacheResponseByTypo3Cache(
        $requestUri,
        array $requestGetData,
        array $apiMethodInfoMetadata,
        $responseData,
        $responseFormatClass,
        array $responseHeaders
    ) {
        $identifier = $this->buildIdentifier($requestUri, $requestGetData);
        $frontendCacheExpires = (integer) $apiMethodInfoMetadata['expires'];
        $typo3CacheExpires = (integer) $apiMethodInfoMetadata[self::API_METHOD_TYPO3CACHE_EXPIRES];
        $typo3CacheTags = explode(',', $apiMethodInfoMetadata[self::API_METHOD_TYPO3CACHE_TAGS]);

        $cacheData = array();
        $cacheData['requestUri'] = $requestUri;
        $cacheData['requestGetData'] = $requestGetData;
        $cacheData['responseData'] = $responseData;
        $cacheData['responseFormatClass'] = $responseFormatClass;
        $cacheData['responseHeaders'] = $responseHeaders;
        $cacheData['frontendCacheExpires'] = $frontendCacheExpires;

        $this->cache->set($identifier, $cacheData, $typo3CacheTags, $typo3CacheExpires);
    }
516696
public function matches($requestUri)
    {
        $requestUri = $this->normalizeUri($requestUri);
        $regex = $this->compile();

        if (preg_match('#^'.$regex.'$#i', $requestUri, $out)) {
            $this->data = $this->getOnlyStringKeys($out);
            return true;
        }

        return false;
    }
511716
public function doRequest($apiName, array $data, $answerFormat = self::ANSWER_FORMAT_ARRAY, $try_number = 1)
    {
        $requestId = $this->getNextId();
        $requestData = [
            'jsonrpc' => '2.0',
            'id'     => $requestId,
            'method' => 'call',
            'params' => [
                $apiName,
                $data['method'],
                $data['params']
            ]
        ];
        try {
            $connection = $this->getConnection();
            $connection->send(json_encode($requestData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $answerRaw = $connection->receive();
            $answer = json_decode($answerRaw, self::ANSWER_FORMAT_ARRAY === $answerFormat);

            if (
                (self::ANSWER_FORMAT_ARRAY === $answerFormat && isset($answer['error']))
                || (self::ANSWER_FORMAT_OBJECT === $answerFormat && isset($answer->error))
            ) {
                throw new ConnectionException('got error in answer: ' . $answer['error']['code'] . ' ' . $answer['error']['message']);
            }
            //check that answer has the same id or id from previous tries, else it is answer from other request
            if (self::ANSWER_FORMAT_ARRAY === $answerFormat) {
                $answerId = $answer['id'];
            } elseif (self::ANSWER_FORMAT_OBJECT === $answerFormat) {
                $answerId = $answer->id;
            }
            if ($requestId - $answerId > ($try_number - 1)) {
                throw new ConnectionException('got answer from old request');
            }


        } catch (ConnectionException $e) {

            if ($try_number < $this->maxNumberOfTriesToCallApi) {
                //if got WS Exception, try to get answer again
                $answer = $this->doRequest($apiName, $data, $answerFormat, $try_number + 1);
            } elseif ($this->isExistReserveNodeUrl()) {
                //if got WS Exception after few ties, connect to reserve node
                $this->connectToReserveNode();
                $answer = $this->doRequest($apiName, $data, $answerFormat);
            } else {
                //if nothing helps
                throw $e;
            }
        }

        return $answer;
    }
554335
protected static function defaultCreateResponses(
        UriInterface $requestUri,
        EncoderInterface $encoder
    ): ResponsesInterface {
        $encoder->forOriginalUri($requestUri);
        $responses = new Responses(
            new MediaType(MediaTypeInterface::JSON_API_TYPE, MediaTypeInterface::JSON_API_SUB_TYPE),
            $encoder
        );

        return $responses;
    }
99641
private void setHeaders(HttpServletResponse response) {
        setHeader(response, "Expires", Long.valueOf(System.currentTimeMillis() + cacheTimeoutMs).toString()); 
        setHeader(response, "Cache-Control", "public, must-revalidate, max-age=" + cacheTimeout); // HTTP 1.1.
        setHeader(response, "Pragma", "public"); 
    }
1364918
@Api
	public static void configureNoCaching(HttpServletResponse response) {
		// HTTP 1.0 header:
		response.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);
		response.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);

		// HTTP 1.1 header:
		response.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);
	}
1144517
protected function getProcessedCacheId(ImageInterface $image, $requestString, $source)
    {

        $osuffix = $image->getSourceFormat();
        $psuffix = $image->getFileFormat();

        unset($this->cachedNames[$requestString]);

        $this->cachedNames[$requestString] = $this->processCache->createKey(
            $source.$osuffix.$psuffix,
            $requestString,
            $this->config->cache_prefix,
            $psuffix
        );

        return $this->cachedNames[$requestString];
    }
824903
private void setResponeHeaders(HttpServletResponse response) {

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", System.currentTimeMillis());
        response.setContentType("text/plain; charset=utf-8");
        response.setCharacterEncoding("utf-8");
    }
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;
    }
592824
private function sendHttpFoundationResponse(int $requestId, HttpFoundationResponse $response): void
    {
        $statusCode = $response->getStatusCode();

        $headerData  = "Status: {$statusCode}\r\n";
        $headerData .= $response->headers."\r\n";

        $stream = fopen('php://memory', 'r+');
        fwrite($stream, $response->getContent());

        $this->writeResponse($requestId, $headerData, $stream);
    }
983702
public function prepareHeaders($requestHeaders)
    {
        $responseHeaders = [];

        if (isset($requestHeaders['Origin'], $this->_cors['Origin'])) {
            if (in_array('*', $this->_cors['Origin']) || in_array($requestHeaders['Origin'], $this->_cors['Origin'])) {
                $responseHeaders['Access-Control-Allow-Origin'] = $requestHeaders['Origin'];
            }
        }

        $this->prepareAllowHeaders('Headers', $requestHeaders, $responseHeaders);

        if (isset($requestHeaders['Access-Control-Request-Method'])) {
            $responseHeaders['Access-Control-Allow-Methods'] = implode(', ', $this->_cors['Access-Control-Request-Method']);
        }

        if (isset($this->_cors['Access-Control-Allow-Credentials'])) {
            $responseHeaders['Access-Control-Allow-Credentials'] = $this->_cors['Access-Control-Allow-Credentials'] ? 'true' : 'false';
        }

        if (isset($this->_cors['Access-Control-Max-Age']) && $this->isOptions()) {
            $responseHeaders['Access-Control-Max-Age'] = $this->_cors['Access-Control-Max-Age'];
        }

        if (isset($this->_cors['Access-Control-Expose-Headers'])) {
            $responseHeaders['Access-Control-Expose-Headers'] = implode(', ', $this->_cors['Access-Control-Expose-Headers']);
        }

        return $responseHeaders;
    }
782042
private function getRequireData($requestPath, array $getData = [])
    {
        $responseData = $this->get($requestPath, $getData);

        return self::requireNotNull($responseData);
    }
1188002
private function handleCacheListeners(RequestInterface $request, ResponseInterface $response, $cacheHit, $cacheItem)
    {
        foreach ($this->config['cache_listeners'] as $cacheListener) {
            $response = $cacheListener->onCacheResponse($request, $response, $cacheHit, $cacheItem);
        }

        return $response;
    }
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;
    }
742516
public function getRequireArrayOrFalse($requestPath, array $getData = [])
    {
        $responseData = $this->get($requestPath, $getData);

        return self::requireArrayOrFalse($responseData);
    }
419631
public function save($api, $class, $version, $cacheArray)
    {
        $cacheKey = md5($api . $class);

        if (!isset($this->cache[$cacheKey])) {
            $this->cache[$cacheKey] = [
                'api'     => $api,
                'class'   => $class,
                'version' => []
            ];
        }

        $this->cache[$cacheKey]['version'][$version] = $cacheArray;
    }
991996
public function getAccessTokenData(RequestInterface $request, ResponseInterface $response)
    {
        // Get the token parameter
        if ($token_param = $this->tokenType->getAccessTokenParameter($request, $response)) {
            // Get the stored token data (from the implementing subclass)
            // Check we have a well formed token
            // Check token expiration (expires is a mandatory paramter)
            if (!$token = $this->tokenStorage->getAccessToken($token_param)) {
                $response->setError(401, 'invalid_token', 'The access token provided is invalid');
            } elseif (!isset($token["expires"]) || !isset($token["client_id"])) {
                $response->setError(401, 'malformed_token', 'Malformed token (missing "expires")');
            } elseif (time() > $token["expires"]) {
                $response->setError(401, 'invalid_token', 'The access token provided has expired');
            } else {
                return $token;
            }
        }

        $authHeader = sprintf('%s realm="%s"', $this->tokenType->getTokenType(), $this->config['www_realm']);

        if ($error = $response->getParameter('error')) {
            $authHeader = sprintf('%s, error="%s"', $authHeader, $error);
            if ($error_description = $response->getParameter('error_description')) {
                $authHeader = sprintf('%s, error_description="%s"', $authHeader, $error_description);
            }
        }

        $response->addHttpHeaders(array('WWW-Authenticate' => $authHeader));

        return null;
    }