/**
  * {@inheritDoc}
  */
 public function getHeaderLine($name, $default = null)
 {
     if (!$this->decoratedResponse->hasHeader($name)) {
         return $default;
     }
     return $this->decoratedResponse->getHeaderLine($name);
 }
 /**
  * @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'));
 }
Exemplo n.º 3
0
 /**
  * @param ResponseInterface $response
  * @param string            $class
  *
  * @return array
  */
 public function deserialize(ResponseInterface $response, $class)
 {
     $body = $response->getBody()->__toString();
     if (strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) {
         throw new DeserializeException('The ArrayDeserializer cannot deserialize response with Content-Type:' . $response->getHeaderLine('Content-Type'));
     }
     $content = json_decode($body, true);
     if (JSON_ERROR_NONE !== json_last_error()) {
         throw new DeserializeException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
     }
     return $content;
 }
 /**
  * @param string $message
  * @param ResponseInterface $response
  * @param \DateTime $responseDateTime
  */
 public function __construct($message, ResponseInterface $response, \DateTime $responseDateTime)
 {
     parent::__construct($message, intval($response->getStatusCode()));
     $this->response = $response;
     $this->responseDateTime = $responseDateTime;
     $this->retrySeconds = $response->hasHeader('Retry-After') ? intval($response->getHeaderLine('Retry-After')) : null;
 }
Exemplo n.º 5
0
 /**
  * @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'));
 }
 public function modify(ResponseInterface $response) : ResponseInterface
 {
     if (false === strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
         return $response;
     }
     return $response->withHeader('Content-Type', $this->contentType);
 }
Exemplo n.º 7
0
 /**
  * WosObjectId constructor.
  *
  * @param ResponseInterface $httpResponse
  */
 public function __construct(ResponseInterface $httpResponse)
 {
     if (!$httpResponse->hasHeader('x-ddn-oid')) {
         throw new InvalidResponseException('x-ddn-oid', 'reserve object');
     }
     $this->objectId = $httpResponse->getHeaderLine('x-ddn-oid');
 }
Exemplo n.º 8
0
 /**
  * Send body as response.
  *
  * @param   ResponseInterface  $response  Response object.
  *
  * @return  void
  */
 public function sendBody(ResponseInterface $response)
 {
     $range = $this->getContentRange($response->getHeaderLine('content-range'));
     $maxBufferLength = $this->getMaxBufferLength() ?: 8192;
     if ($range === false) {
         $body = $response->getBody();
         $body->rewind();
         while (!$body->eof()) {
             echo $body->read($maxBufferLength);
             $this->delay();
         }
         return;
     }
     list($unit, $first, $last, $length) = array_values($range);
     ++$last;
     $body = $response->getBody();
     $body->seek($first);
     $position = $first;
     while (!$body->eof() && $position < $last) {
         // The latest part
         if ($position + $maxBufferLength > $last) {
             echo $body->read($last - $position);
             $this->delay();
             break;
         }
         echo $body->read($maxBufferLength);
         $position = $body->tell();
         $this->delay();
     }
 }
Exemplo n.º 9
0
 /**
  * Decodes a JSON response.
  *
  * @param ResponseInterface $response
  * @param bool              $assoc [optional] Return an associative array?
  * @return mixed
  */
 static function jsonFromResponse(ResponseInterface $response, $assoc = false)
 {
     if ($response->getHeaderLine('Content-Type') != 'application/json') {
         throw new \RuntimeException("HTTP response is not of type JSON");
     }
     return json_decode($response->getBody(), $assoc);
 }
 /**
  * Extract a single header from the response into the result.
  */
 private function extractHeader($name, Shape $shape, ResponseInterface $response, &$result)
 {
     $value = $response->getHeaderLine($shape['locationName'] ?: $name);
     switch ($shape->getType()) {
         case 'float':
         case 'double':
             $value = (double) $value;
             break;
         case 'long':
             $value = (int) $value;
             break;
         case 'boolean':
             $value = filter_var($value, FILTER_VALIDATE_BOOLEAN);
             break;
         case 'blob':
             $value = base64_decode($value);
             break;
         case 'timestamp':
             try {
                 $value = new DateTimeResult($value);
                 break;
             } catch (\Exception $e) {
                 // If the value cannot be parsed, then do not add it to the
                 // output structure.
                 return;
             }
     }
     $result[$name] = $value;
 }
 /**
  * @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'));
 }
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
 {
     if (false === strpos($response->getHeaderLine('Content-Type'), 'application/json')) {
         return $next($request, $response);
     }
     return $next($request, $response->withHeader('Content-Type', $this->contentType));
 }
Exemplo n.º 13
0
 /** {@inheritdoc} */
 public function supportPagination(array $data, ResponseInterface $response, ResponseDefinition $responseDefinition)
 {
     $support = true;
     foreach ($this->paginationHeaders as $headerName) {
         $support = $support & $response->getHeaderLine($headerName) !== '';
     }
     return (bool) $support;
 }
 /**
  * @return array
  */
 public function extractData()
 {
     if (false !== $this->data) {
         return $this->data;
     }
     $stream = $this->response->getBody();
     if ($stream->tell()) {
         $stream->rewind();
     }
     $body = $stream->getContents();
     $contentType = $this->response->getHeaderLine('Content-Type');
     $contentTypeParts = explode(';', $contentType);
     $mimeType = trim(reset($contentTypeParts));
     $data = static::parseStringByFormat($body, $mimeType);
     $this->data = $data;
     return $data;
 }
Exemplo n.º 15
0
 /**
  * Check the cache headers and return the expiration time.
  *
  * @param ResponseInterface $response
  *
  * @return Datetime|null
  */
 private static function getExpiration(ResponseInterface $response)
 {
     //Cache-Control
     $cacheControl = $response->getHeaderLine('Cache-Control');
     if (!empty($cacheControl)) {
         $cacheControl = self::parseCacheControl($cacheControl);
         //Max age
         if (isset($cacheControl['max-age'])) {
             return new Datetime('@' . (time() + (int) $cacheControl['max-age']));
         }
     }
     //Expires
     $expires = $response->getHeaderLine('Expires');
     if (!empty($expires)) {
         return new Datetime($expires);
     }
 }
Exemplo n.º 16
0
 /**
  * @param ResponseInterface $response
  * @param string            $class
  *
  * @return ResponseInterface
  */
 public function deserialize(ResponseInterface $response, $class)
 {
     $body = $response->getBody()->__toString();
     if (strpos($response->getHeaderLine('Content-Type'), 'application/json') !== 0) {
         throw new DeserializeException('The ModelDeserializer cannot deserialize response with Content-Type:' . $response->getHeaderLine('Content-Type'));
     }
     $data = json_decode($body, true);
     if (JSON_ERROR_NONE !== json_last_error()) {
         throw new DeserializeException(sprintf('Error (%d) when trying to json_decode response', json_last_error()));
     }
     if (is_subclass_of($class, ApiResponse::class)) {
         $object = call_user_func($class . '::create', $data);
     } else {
         $object = new $class($data);
     }
     return $object;
 }
Exemplo n.º 17
0
 /**
  * Create the stream.
  *
  * @param $socket
  * @param ResponseInterface $response
  *
  * @return Stream
  */
 protected function createStream($socket, ResponseInterface $response)
 {
     $size = null;
     if ($response->hasHeader('Content-Length')) {
         $size = (int) $response->getHeaderLine('Content-Length');
     }
     return new Stream($socket, $size);
 }
 /**
  * Parse response body as JSON.
  *
  * @param  ResponseInterface $response
  * @return mixed
  */
 protected function getJsonFromResponse(ResponseInterface $response)
 {
     $this->assertEquals('application/json;charset=UTF-8', $response->getHeaderLine('Content-Type'));
     $json = json_decode((string) $response->getBody(), true);
     if (json_last_error()) {
         throw new RuntimeException('JSON parse failed: ' . json_last_error_msg());
     }
     return $json;
 }
Exemplo n.º 19
0
 public function __invoke(ServerRequestInterface $request, ResponseInterface $response)
 {
     if (strpos($response->getHeaderLine("Content-Type"), "application/json") == 0) {
         $json = json_decode($response->getBody()->getContents(), true);
         $response = $response->withBody(\GuzzleHttp\Psr7\stream_for($this->twig->render('layout.twig', $json)));
         $response = $response->withHeader("Content-Type", "text/html");
     }
     return $response;
 }
Exemplo n.º 20
0
 /**
  * Populates the current resource from a response object.
  *
  * @param ResponseInterface $response
  *
  * @return $this|ResourceInterface
  */
 public function populateFromResponse(ResponseInterface $response)
 {
     if (strpos($response->getHeaderLine('Content-Type'), 'application/json') === 0) {
         $json = Utils::jsonDecode($response);
         if (!empty($json)) {
             $this->populateFromArray(Utils::flattenJson($json, $this->resourceKey));
         }
     }
     return $this;
 }
 /**
  * @author EA
  * @param ResponseInterface $response
  * @return array
  * @throws WrongResponseException
  */
 protected function processResponse(ResponseInterface $response)
 {
     if ($response->getStatusCode() == 204) {
         return null;
     }
     if (strpos($response->getHeaderLine('Content-Type'), 'text/csv') !== false) {
         return ['csv' => $response->getBody()->getContents()];
     }
     throw new WrongResponseException('Response body was malformed csv', $response->getStatusCode());
 }
 /**
  * Asserts response match with the response schema.
  *
  * @param ResponseInterface $response
  * @param SchemaManager $schemaManager
  * @param string $path percent-encoded path used on the request.
  * @param string $httpMethod
  * @param string $message
  */
 public function assertResponseMatch(ResponseInterface $response, SchemaManager $schemaManager, $path, $httpMethod, $message = '')
 {
     $this->assertResponseMediaTypeMatch($response->getHeaderLine('Content-Type'), $schemaManager, $path, $httpMethod, $message);
     $httpCode = $response->getStatusCode();
     $headers = $response->getHeaders();
     foreach ($headers as &$value) {
         $value = implode(', ', $value);
     }
     $this->assertResponseHeadersMatch($headers, $schemaManager, $path, $httpMethod, $httpCode, $message);
     $this->assertResponseBodyMatch(json_decode($response->getBody()), $schemaManager, $path, $httpMethod, $httpCode, $message);
 }
 public function __invoke(CommandInterface $command, ResponseInterface $response)
 {
     if ($expected = $response->getHeaderLine('x-amz-crc32')) {
         $hash = hexdec(Psr7\hash($response->getBody(), 'crc32b'));
         if ((int) $expected !== $hash) {
             throw new AwsException("crc32 mismatch. Expected {$expected}, found {$hash}.", $command, ['code' => 'ClientChecksumMismatch', 'connection_error' => true, 'response' => $response]);
         }
     }
     $fn = $this->parser;
     return $fn($command, $response);
 }
Exemplo n.º 24
0
 private function getResponseFormat(ResponseInterface $response) : string
 {
     $mimeType = $response->getHeaderLine('Content-Type');
     if (false !== ($pos = strpos($mimeType, ';'))) {
         $mimeType = substr($mimeType, 0, $pos);
     }
     if (isset($this->supportedMimeTypes[$mimeType])) {
         return $this->supportedMimeTypes[$mimeType];
     }
     throw new BadResponseFormatException($mimeType, array_keys($this->supportedMimeTypes));
 }
Exemplo n.º 25
0
 /**
  * {@inheritDoc}
  */
 public function isAuthentic(ResponseInterface $response)
 {
     if (!$response->hasHeader('X-Server-Authorization-HMAC-SHA256')) {
         throw new MalformedResponseException('Response is missing required X-Server-Authorization-HMAC-SHA256 header.', null, 0, $response);
     }
     $responseSigner = new ResponseSigner($this->key, $this->request);
     $compareResponse = $responseSigner->signResponse($response->withoutHeader('X-Server-Authorization-HMAC-SHA256'));
     $responseSignature = $response->getHeaderLine('X-Server-Authorization-HMAC-SHA256');
     $compareSignature = $compareResponse->getHeaderLine('X-Server-Authorization-HMAC-SHA256');
     return hash_equals($compareSignature, $responseSignature);
 }
Exemplo n.º 26
0
 private function parseHeaders(ResponseInterface $response, array &$data)
 {
     if ($response->getStatusCode() == '404') {
         $data['code'] = 'NotFound';
     }
     $data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
     if ($requestId = $response->getHeaderLine('x-amz-request-id')) {
         $data['request_id'] = $requestId;
         $data['message'] .= " (Request-ID: {$requestId})";
     }
 }
Exemplo n.º 27
0
 /**
  * {@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;
 }
Exemplo n.º 28
0
 /**
  * @inheritdoc
  * @throws \InvalidArgumentException
  */
 public function create(ResponseInterface $response, $affectedUrl = null)
 {
     $html = $response->getBody();
     $html = StringHelper::safeEncodeStr((string) $html);
     $contentType = $response->getHeaderLine('content-type');
     $html = HtmlEncodingConverter::convertToUtf($html, $contentType);
     $page = new ElementFinder((string) $html);
     if ($affectedUrl !== null) {
         LinkConverter::convertUrlsToAbsolute($page, $affectedUrl);
     }
     return $page;
 }
Exemplo n.º 29
0
 /**
  * @param RequestInterface                   $request
  * @param array                              $options
  * @param ResponseInterface|PromiseInterface $response
  *
  * @return ResponseInterface|PromiseInterface
  */
 public function processResponse(RequestInterface $request, array $options, ResponseInterface $response)
 {
     $crawler = null;
     if ($response->hasHeader('Content-Type') && false !== strpos($response->getHeaderLine('Content-Type'), 'html')) {
         $crawler = new Crawler(null, $request->getUri());
         $crawler->addContent((string) $response->getBody(), $response->getHeaderLine('Content-Type'));
     }
     $values = null;
     if (isset($options['values'])) {
         if (!$options['values'] instanceof ValueBag) {
             throw new InvalidArgumentException('The "values" option must be an instance of Blackfire\\Player\\ValueBag.');
         }
     }
     if (isset($options['expectations'])) {
         $this->checkExpectations($options['expectations'], $options['values'], $crawler, $request, $response);
     }
     if (isset($options['extractions'])) {
         $this->extractVariables($options['extractions'], $options['values'], $crawler, $request, $response);
     }
     return $response;
 }
 /**
  * @param ResponseInterface     $response
  * @param \swoole_http_response $swooleResponse
  */
 public function reverseTransform(ResponseInterface $response, \swoole_http_response $swooleResponse)
 {
     foreach (array_keys($response->getHeaders()) as $name) {
         $swooleResponse->header($name, $response->getHeaderLine($name));
     }
     $swooleResponse->status($response->getStatusCode());
     $body = $response->getBody();
     $body->rewind();
     # workaround for https://bugs.php.net/bug.php?id=68948
     while (false === $body->eof() && '' !== ($buffer = $body->read($this->responseBuffer))) {
         $swooleResponse->write($buffer);
     }
     $swooleResponse->end();
 }