/** * @param ResponseInterface $response * @param \DateTime $staleAt * @param \DateTime|null $staleIfErrorTo if null, detected with the headers (RFC 5861) * @param \DateTime $staleWhileRevalidateTo */ public function __construct(ResponseInterface $response, \DateTime $staleAt, \DateTime $staleIfErrorTo = null, \DateTime $staleWhileRevalidateTo = null) { $this->response = $response; $this->staleAt = $staleAt; if ($staleIfErrorTo === null) { $headersCacheControl = $response->getHeader("Cache-Control"); if (!in_array("must-revalidate", $headersCacheControl)) { foreach ($headersCacheControl as $directive) { $matches = []; if (preg_match('/^stale-if-error=([0-9]*)$/', $directive, $matches)) { $this->staleIfErrorTo = new \DateTime('+' . $matches[1] . 'seconds'); break; } } } } else { $this->staleIfErrorTo = $staleIfErrorTo; } if ($staleWhileRevalidateTo === null) { foreach ($response->getHeader("Cache-Control") as $directive) { $matches = []; if (preg_match('/^stale-while-revalidate=([0-9]*)$/', $directive, $matches)) { $this->staleWhileRevalidateTo = new \DateTime('+' . $matches[1] . 'seconds'); break; } } } else { $this->staleWhileRevalidateTo = $staleWhileRevalidateTo; } }
/** * @When the response headers should contain :expectedHeader */ public function theResponseHeadersShouldContain($expectedHeader) { list($headerTitle, $expectedHeaderValue) = explode(':', $expectedHeader); $expectedHeaderValue = trim($expectedHeaderValue); $headerValuesReceived = $this->responseReceived->getHeader($headerTitle); \PHPUnit_Framework_Assert::assertEquals($expectedHeaderValue, $headerValuesReceived[0]); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(RequestInterface $request, ResponseInterface $response) { if (!isset($this->statusAccepted[$response->getStatusCode()])) { // Don't cache it return; } $cacheControl = new KeyValueHttpHeader($response->getHeader('Cache-Control')); $varyHeader = new KeyValueHttpHeader($response->getHeader('Vary')); if ($varyHeader->has('*')) { // This will never match with a request return; } if ($cacheControl->has('no-store')) { // No store allowed (maybe some sensitives data...) return; } if ($cacheControl->has('no-cache')) { // Stale response see RFC7234 section 5.2.1.4 $entry = new CacheEntry($request, $response, new \DateTime('-1 seconds')); return $entry->hasValidationInformation() ? $entry : null; } foreach ($this->ageKey as $key) { if ($cacheControl->has($key)) { return new CacheEntry($request, $response, new \DateTime('+' . (int) $cacheControl->get($key) . 'seconds')); } } if ($response->hasHeader('Expires')) { $expireAt = \DateTime::createFromFormat(\DateTime::RFC1123, $response->getHeaderLine('Expires')); if ($expireAt !== false) { return new CacheEntry($request, $response, $expireAt); } } return new CacheEntry($request, $response, new \DateTime('-1 seconds')); }
/** * @param ResponseInterface $response * * @return ApiResult */ protected function _getResult($response) { if (!$response instanceof ResponseInterface) { throw new \InvalidArgumentException("{$response} should be an instance of ResponseInterface"); } $result = new ApiResult(); $result->setStatusCode($response->getStatusCode()); $callId = $response->getHeader('X-Call-Id'); if (!empty($callId)) { $result->setCallId($callId); } $decoded = json_decode((string) $response->getBody()); if (isset($decoded->meta) && isset($decoded->data) && isset($decoded->meta->code) && $decoded->meta->code == $response->getStatusCode()) { $meta = $decoded->meta; $data = $decoded->data; if (isset($meta->message)) { $result->setStatusMessage($meta->message); } $result->setContent(json_encode($data)); } else { $result->setContent((string) $response->getBody()); } $result->setHeaders($response->getHeaders()); return $result; }
/** * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(ResponseInterface $response) { if ($response->hasHeader("Cache-Control")) { $cacheControlDirectives = $response->getHeader("Cache-Control"); if (in_array("no-store", $cacheControlDirectives)) { // No store allowed (maybe some sensitives data...) return null; } if (in_array("no-cache", $cacheControlDirectives)) { // Stale response see RFC7234 section 5.2.1.4 $entry = new CacheEntry($response, new \DateTime('-1 seconds')); return $entry->hasValidationInformation() ? $entry : null; } $matches = []; if (preg_match('/^max-age=([0-9]*)$/', $response->getHeaderLine("Cache-Control"), $matches)) { // Handle max-age header return new CacheEntry($response, new \DateTime('+' . $matches[1] . 'seconds')); } } if ($response->hasHeader("Expires")) { $expireAt = \DateTime::createFromFormat('D, d M Y H:i:s T', $response->getHeaderLine("Expires")); if ($expireAt !== FALSE) { return new CacheEntry($response, $expireAt); } } return new CacheEntry($response, new \DateTime('1 days ago')); }
protected function checkResponse(ResponseInterface $response, $data) { // Metadata info $contentTypeRaw = $response->getHeader('Content-Type'); $contentTypeArray = explode(';', reset($contentTypeRaw)); $contentType = reset($contentTypeArray); // Response info $responseCode = $response->getStatusCode(); $responseMessage = $response->getReasonPhrase(); // Data info $error = !empty($data['error']) ? $data['error'] : null; $errorCode = !empty($error['error_code']) ? $error['error_code'] : $responseCode; $errorDescription = !empty($data['error_description']) ? $data['error_description'] : null; $errorMessage = !empty($error['error_msg']) ? $error['error_msg'] : $errorDescription; $message = $errorMessage ?: $responseMessage; // Request/meta validation if (399 < $responseCode) { throw new IdentityProviderException($message, $responseCode, $data); } // Content validation if ('application/json' != $contentType) { throw new IdentityProviderException($message, $responseCode, $data); } if ($error) { throw new IdentityProviderException($errorMessage, $errorCode, $data); } }
public static function decode(ResponseInterface $response) { if ($response->hasHeader('Content-Type') && $response->getHeader('Content-Type')[0] == 'application/json') { return json_decode((string) $response->getBody(), true); } return (string) $response->getBody(); }
/** * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(ResponseInterface $response) { if ($response->hasHeader("Cache-Control")) { $values = new KeyValueHttpHeader($response->getHeader("Cache-Control")); if ($values->has('no-store')) { // No store allowed (maybe some sensitives data...) return null; } if ($values->has('no-cache')) { // Stale response see RFC7234 section 5.2.1.4 $entry = new CacheEntry($response, new \DateTime('-1 seconds')); return $entry->hasValidationInformation() ? $entry : null; } if ($values->has('max-age')) { return new CacheEntry($response, new \DateTime('+' . $values->get('max-age') . 'seconds')); } return new CacheEntry($response, new \DateTime()); } if ($response->hasHeader("Expires")) { $expireAt = \DateTime::createFromFormat('D, d M Y H:i:s T', $response->getHeaderLine("Expires")); if ($expireAt !== FALSE) { return new CacheEntry($response, $expireAt); } } return new CacheEntry($response, new \DateTime('-1 seconds')); }
private function handleInvalidContentType(HalClientInterface $client, RequestInterface $request, ResponseInterface $response, $ignoreInvalidContentType) { if ($ignoreInvalidContentType) { return new HalResource($client); } $types = $response->getHeader('Content-Type') ?: ['none']; throw new Exception\BadResponseException(sprintf('Request did not return a valid content type. Returned content type: %s.', implode(', ', $types)), $request, $response, new HalResource($client)); }
function it_returns_a_processed_resource(ResponseInterface $response, HttpClient $httpClient, Processor $processor) { $response->getHeader('content-type')->willReturn(['application/hal+json']); $resource = new Resource([], []); $httpClient->get('http://api.test.com/')->willReturn($response); $processor->process($response, $this)->willReturn($resource); $this->get('http://api.test.com/')->shouldReturn($resource); }
/** * {@inheritdoc} */ protected function getCacheObject(RequestInterface $request, ResponseInterface $response) { $cacheControl = new KeyValueHttpHeader($response->getHeader('Cache-Control')); if ($cacheControl->has('private')) { return; } return parent::getCacheObject($request, $response); }
/** {@inheritdoc} */ public function getPagination(array $data, ResponseInterface $response, ResponseDefinition $responseDefinition) { $paginationLinks = null; if ($response->hasHeader('Link')) { $links = self::parseHeaderLinks($response->getHeader('Link')); $paginationLinks = new PaginationLinks($links['first'], $links['last'], $links['next'], $links['prev']); } return new Pagination((int) $response->getHeaderLine($this->paginationHeaders['page']), (int) $response->getHeaderLine($this->paginationHeaders['perPage']), (int) $response->getHeaderLine($this->paginationHeaders['totalItems']), (int) $response->getHeaderLine($this->paginationHeaders['totalPages']), $paginationLinks); }
/** * Constructor * * @param \Psr\Http\Message\ResponseInterface $response * @param string $userAgent * @throws XRobotsTagParser\Exceptions\XRobotsTagParserException */ public function __construct(ResponseInterface $response, $userAgent = '') { parent::__construct($userAgent); $headers = []; foreach ($response->getHeader(parent::HEADER_RULE_IDENTIFIER) as $name => $values) { $headers[] = $name . ': ' . implode(' ', $values) . "\r\n"; } $this->parse($headers); }
public function getOrchestrateRequestId() { $this->settlePromise(); if ($this->_response) { $value = $this->_response->getHeader('X-ORCHESTRATE-REQ-ID'); return isset($value[0]) ? $value[0] : ''; } return ''; }
/** * * @param RequestInterface $request * @param ResponseInterface $response * @param \Exception $previous * @param array $ctx * @return BearerErrorResponseException */ public static function create(RequestInterface $request, ResponseInterface $response = null, \Exception $previous = null, array $ctx = []) { unset($previous, $ctx); $label = 'Bearer error response'; $bearerReason = self::headerToReason($response->getHeader('WWW-Authenticate')); $message = $label . PHP_EOL . implode(PHP_EOL, ['[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[bearer reason] ' . $bearerReason, '[url] ' . $request->getUri()]); $exception = new static($message, $request, $response); $exception->setBearerReason($bearerReason); return $exception; }
/** * @param ResponseInterface $response * * @return string|null */ private function next(ResponseInterface $response) { $links = Psr7\parse_header($response->getHeader('Link')); foreach ($links as $link) { if ($link['rel'] == 'next') { return trim($link[0], '<>'); } } return null; }
public function parseMetadata(ResponseInterface $response) : array { $metadata = []; foreach ($response->getHeaders() as $header => $value) { $position = strpos($header, static::METADATA_PREFIX); if ($position === 0) { $metadata[ltrim($header, static::METADATA_PREFIX)] = $response->getHeader($header)[0]; } } return $metadata; }
/** * Returns the json object if the response contains valid json, otherwise null. * * @param ResponseInterface $response * @return mixed|null */ protected function getResponseAsJson(ResponseInterface $response) { if ($response->hasHeader('Content-Type')) { $typeHeader = $response->getHeader('Content-Type'); $contentType = array_shift($typeHeader); if (stripos($contentType, 'application/json') === 0) { return json_decode($response->getBody(), false); } } return null; }
public function onResponse(ResponseInterface $response, RequestInterface $request) { $query = $this->getQueryAsArray($request); $header_values = $response->getHeader('Content-Language'); $requestLanguage = isset($query['lang']) ? $query['lang'] : NULL; $responseLanguage = !empty($header_values) ? array_shift($header_values) : NULL; if ($requestLanguage !== $responseLanguage) { $message = 'Invalid language (expected: ' . $requestLanguage . '; actual: ' . $responseLanguage . ')'; throw new InvalidLanguageException($message, $requestLanguage, $responseLanguage, $response); } }
/** * {@inheritdoc} */ public function fromResponse(ResponseInterface $response, $defaultDomain = null, $defaultPath = null) { $defaultDomain = $defaultDomain ? $defaultDomain : $response->getHeaderLine('Host'); foreach ($response->getHeader('Set-Cookie') as $c) { $cookie = Cookie::parse($c); if (!$cookie->expires && $cookie->maxage) { $cookie->setExpires(time() + $cookie->maxage); } $this->add($cookie, $defaultDomain, $defaultPath); } return $this; }
private function generateRequestLog(Request $request, Response $response) { if ($this->options['full']) { return RequestSerializer::toString($request); } $msg = sprintf("%s %s", $request->getMethod(), $request->getRequestTarget()); if ($request->hasHeader('X-Request-Id')) { $msg .= ' RequestId: ' . $request->getHeader('X-Request-Id')[0]; } elseif ($response->hasHeader('X-Request-Id')) { $msg .= ' RequestId: ' . $response->getHeader('X-Request-Id')[0]; } return $msg; }
/** * @param ResponseInterface $response * @param \DateTime $staleAt * @param \DateTime|null $staleIfErrorTo if null, detected with the headers (RFC 5861) * @param \DateTime $staleWhileRevalidateTo */ public function __construct(ResponseInterface $response, \DateTime $staleAt, \DateTime $staleIfErrorTo = null, \DateTime $staleWhileRevalidateTo = null) { $this->response = $response; $this->staleAt = $staleAt; $values = new KeyValueHttpHeader($response->getHeader("Cache-Control")); if ($staleIfErrorTo === null && $values->has('stale-if-error')) { $this->staleIfErrorTo = (new \DateTime())->setTimestamp($this->staleAt->getTimestamp() + (int) $values->get('stale-if-error')); } else { $this->staleIfErrorTo = $staleIfErrorTo; } if ($staleWhileRevalidateTo === null && $values->has('stale-while-revalidate')) { $this->staleWhileRevalidateTo = new \DateTime('+' . $values->get('stale-while-revalidate') . 'seconds'); } else { $this->staleWhileRevalidateTo = $staleWhileRevalidateTo; } }
/** * Get the content type. * * @param ServerRequestInterface $request * @param ResponseInterface $response * @return string */ protected function getContentType(ServerRequestInterface $request, ResponseInterface $response) { if (!$response->hasHeader('Content-Type')) { $contentType = $this->determineContentType($request); } else { $contentType = $response->getHeader('Content-Type'); if (is_array($contentType)) { $contentType = $contentType[0]; } $contentTypeParts = preg_split('/\\s*;\\s*/', $contentType); if (count($contentTypeParts)) { $contentType = $contentTypeParts[0]; } } return $contentType; }
/** * Add content security policy header to response * * @param ResponseInterface $response * * @return ResponseInterface */ protected function addPolicyHeader(ResponseInterface $response) { $this->loadDefaultProfiles(); $currentHeader = $response->getHeader($this->header); $initialConfig = []; if (count($currentHeader)) { $initialConfig = $this->decodeConfiguration($currentHeader[0]); } $initialDirectives = $this->encodeConfiguration($initialConfig); $this->mergeProfileWithConfig($initialConfig); $newDirectives = $this->encodeConfiguration($this->config); if ($newDirectives != $initialDirectives) { $response = $response->withHeader($this->header, $newDirectives); } return $response; }
/** * Decode a response on a specific header (content encoding or transfer encoding mainly). * * @param string $headerName Name of the header * @param ResponseInterface $response Response * * @return ResponseInterface A new instance of the response decoded */ private function decodeOnEncodingHeader($headerName, ResponseInterface $response) { if ($response->hasHeader($headerName)) { $encodings = $response->getHeader($headerName); $newEncodings = []; while ($encoding = array_pop($encodings)) { $stream = $this->decorateStream($encoding, $response->getBody()); if (false === $stream) { array_unshift($newEncodings, $encoding); continue; } $response = $response->withBody($stream); } $response = $response->withHeader($headerName, $newEncodings); } return $response; }
/** * @param ResponseInterface $response * @return CacheEntry|null entry to save, null if can't cache it */ protected function getCacheObject(ResponseInterface $response) { if (!isset($this->statusAccepted[$response->getStatusCode()])) { // Don't cache it return null; } if ($response->hasHeader("Cache-Control")) { $values = new KeyValueHttpHeader($response->getHeader("Cache-Control")); if (!$values->isEmpty()) { return $this->getCacheObjectForCacheControl($response, $values); } } if ($response->hasHeader("Expires") && ($expireAt = \DateTime::createFromFormat(\DateTime::RFC1123, $response->getHeaderLine("Expires")))) { return new CacheEntry($response, $expireAt); } return new CacheEntry($response, new \DateTime('-1 seconds')); }
private function cacheResponse(Request $request, Response $response) { if ('GET' !== $request->getMethod() || !$response->hasHeader('Cache-Control')) { return; } $cacheControl = $response->getHeader('Cache-Control'); $abortTokens = ['private', 'no-cache', 'no-store']; if (count(array_intersect($abortTokens, $cacheControl)) > 0) { return; } foreach ($cacheControl as $value) { $parts = explode('=', $value); if (count($parts) == 2 && 'max-age' === $parts[0]) { $this->cache->save($this->getCacheKey($request), ['headers' => $response->getHeaders(), 'body' => (string) $response->getBody()], intval($parts[1])); return; } } }
/** * @param RequestInterface $request * @return bool */ public function isVaryEquals(RequestInterface $request) { if ($this->response->hasHeader('Vary')) { if ($this->request === null) { return false; } $varyHeaders = new KeyValueHttpHeader($this->response->getHeader('Vary')); foreach ($varyHeaders as $key => $value) { if (!$this->request->hasHeader($key) && !$request->hasHeader($key)) { // Absent from both continue; } elseif ($this->request->getHeaderLine($key) == $request->getHeaderLine($key)) { // Same content continue; } return false; } } return true; }
/** * {@inheritdoc} * @throws \RuntimeException */ public function emit(ResponseInterface $response) { $headers = $response->getHeader('X-Easy-Name'); if (count($headers) === 0) { return; } $pageName = $headers[0] ?: ''; if (empty($pageName)) { return; } $pageDir = sprintf('%s/%s', $this->exportDir, $pageName); $pageFile = sprintf('%s/index.html', $pageDir); if (!is_dir($pageDir)) { if (!@mkdir($pageDir, 0777, true) && !is_dir($pageDir)) { throw new \RuntimeException(sprintf('Cannot create directory "%s"', $pageDir)); } } $response->getBody()->rewind(); file_put_contents($pageFile, $response->getBody()->getContents()); }
/** * @param RequestInterface $request * @param array $options * @param ResponseInterface|PromiseInterface $response * * @return ResponseInterface|PromiseInterface */ public function checkThrottling(RequestInterface $request, array $options, ResponseInterface $response) { if (!isset($options['__throttle_retries'])) { $options['__throttle_retries'] = $this::$maxRetries; } // Return the response if it wasn't throttled or if we don't have any // retries left if ($response->getStatusCode() !== 429 || !($options['__throttle_retries'] > 0)) { return $response; } $options['__throttle_retries']--; // If the response was throttled, wait the specified time // and repeat the request. sleep($response->getHeader('Retry-After')[0]); /** @var PromiseInterface|ResponseInterface $promise */ $promise = $this($request, $options); // Add a header to the final response that says it was throttled return $promise->then(function (ResponseInterface $response) { return $response->withHeader('X-FS-THROTTLED', ''); }); }