Ejemplo n.º 1
0
 public function __construct(\GuzzleHttp\Psr7\Response $response)
 {
     $json = false;
     $data = $response->getBody();
     $this->rawData = $data;
     $this->response = $response;
     if ($response->hasHeader('Content-Type')) {
         // Let's see if it is JSON
         $contentType = $response->getHeader('Content-Type');
         if (strstr($contentType[0], 'json')) {
             $json = true;
             $data = json_decode($data);
         }
     }
     if (!$json) {
         // We can do another test here
         $decoded = json_decode($response->getBody());
         if ($decoded) {
             $json = true;
             $data = $decoded;
         }
     }
     $this->setData($data);
     $this->setIsJson($json);
 }
Ejemplo n.º 2
0
 public function testCanConstructWithHeadersAsArray()
 {
     $r = new Response(200, ['Foo' => ['baz', 'bar']]);
     $this->assertSame(['Foo' => ['baz', 'bar']], $r->getHeaders());
     $this->assertSame('baz, bar', $r->getHeaderLine('Foo'));
     $this->assertSame(['baz', 'bar'], $r->getHeader('Foo'));
 }
Ejemplo n.º 3
0
 /**
  * {@inheritdoc}
  */
 public function getLatestResponseHeaders()
 {
     if (null === $this->response) {
         return;
     }
     return ['reset' => (int) (string) $this->response->getHeader('RateLimit-Reset'), 'remaining' => (int) (string) $this->response->getHeader('RateLimit-Remaining'), 'limit' => (int) (string) $this->response->getHeader('RateLimit-Limit')];
 }
Ejemplo n.º 4
0
 /**
  * Response constructor
  *
  * @param  HttpResponse $httpResponse
  * @return self
  */
 public function __construct(HttpResponse $httpResponse)
 {
     $header = $httpResponse->getHeader('Content-Type');
     if (!is_array($header) && stripos($header, 'text/javascript') !== false) {
         $this->_response = $this->processJson($httpResponse->getBody());
     } else {
         $this->_response = $this->processXml($httpResponse->getBody());
     }
 }
 /**
  * Get cache ttl value
  *
  * @param Response $response
  *
  * @return int
  */
 protected function getCacheTtl(Response $response)
 {
     if ($this->useHeaderTtl && $response->hasHeader('Cache-Control')) {
         $cacheControl = $response->getHeader('Cache-Control')[0];
         if (preg_match('`max-age=(\\d+)`', $cacheControl, $match)) {
             return intval($match[1]);
         }
     }
     return $this->defaultTtl;
 }
Ejemplo n.º 6
0
 /**
  * @param ObjectInterface $object
  * @param array           $data
  * @param Response        $response
  * @return ObjectInterface
  */
 public function create(ObjectInterface $object, array $data, Response $response = null)
 {
     // If object had relationId, we pass it to new object
     if ($object->getAttribute("relationId")) {
         $relationId = $object->getAttribute("relationId");
         $object = new $object($relationId);
     } else {
         $object = new $object();
     }
     if (isset($data['items']) or isset($data[0])) {
         // If we have list of items
         $object = $this->createList($object, $data);
     } else {
         if (isset($data["id"])) {
             // TODO: Some things don't provide ID, possible BUG, that it isn't implemented in CREST
             $object->setAttribute("id", $data['id']);
             $uri = $object->getAttribute("uri") . $object->getAttribute("id") . "/";
             $object->setAttribute("uri", $uri);
         } elseif (!empty($data['href']) && is_numeric(basename($data["href"]))) {
             // TODO: Meybe not bug, so we just take it from href
             $object->setAttribute("id", (int) basename($data["href"]));
             $uri = $object->getAttribute("uri") . $object->getAttribute("id") . "/";
             $object->setAttribute("uri", $uri);
         }
         foreach ($data as $key => $value) {
             if (array_key_exists($key, $object->getRelations())) {
                 // ˇˇ
                 if (is_string($value)) {
                     // TODO: Sometimes relationship is only a string with href, not array like usually.
                     // TODO: When crest behaves as it should, remove this!
                     // Seen in GET crest.../wars/21/  value "killmails"
                     $object->setValue($key, $value);
                     continue;
                 }
                 // ^^
                 // Create new relation object with relation_id
                 $relation = $object->getRelations($key);
                 $object->setValue($key, $this->create(new $relation($object->getAttribute("id")), $value));
             } else {
                 $object->setValue($key, $value);
             }
         }
     }
     // Add cache-control header to Object, but only if this Endpoint made request
     //  we cant add cache-control for relationships, as we don't have data for them
     // Add HTTP Code, might be useful
     if ($response) {
         // On POST/PUT/DELETE responses cache-control isn't provided.
         if ($response->hasHeader("cache-control")) {
             $object->setAttribute("cache", $response->getHeader("cache-control")[0]);
         }
         $object->setAttribute("httpCode", $response->getStatusCode());
     }
     return $object;
 }
Ejemplo n.º 7
0
 public function parse(Response $response)
 {
     $collection = new Collection();
     if (!$response->getBody()) {
         return $collection;
     }
     // help bad responses be more multipart compliant
     $body = "\r\n" . $response->getBody()->__toString() . "\r\n";
     // multipart
     preg_match('/boundary\\=\\"(.*?)\\"/', $response->getHeader('Content-Type'), $matches);
     if (isset($matches[1])) {
         $boundary = $matches[1];
     } else {
         preg_match('/boundary\\=(.*?)(\\s|$|\\;)/', $response->getHeader('Content-Type'), $matches);
         $boundary = $matches[1];
     }
     // strip quotes off of the boundary
     $boundary = preg_replace('/^\\"(.*?)\\"$/', '\\1', $boundary);
     // clean up the body to remove a reamble and epilogue
     $body = preg_replace('/^(.*?)\\r\\n--' . $boundary . '\\r\\n/', "\r\n--{$boundary}\r\n", $body);
     // make the last one look like the rest for easier parsing
     $body = preg_replace('/\\r\\n--' . $boundary . '--/', "\r\n--{$boundary}\r\n", $body);
     // cut up the message
     $multi_parts = explode("\r\n--{$boundary}\r\n", $body);
     // take off anything that happens before the first boundary (the preamble)
     array_shift($multi_parts);
     // take off anything after the last boundary (the epilogue)
     array_pop($multi_parts);
     $message_parser = new MessageParser();
     $parser = new Single();
     // go through each part of the multipart message
     foreach ($multi_parts as $part) {
         // get Guzzle to parse this multipart section as if it's a whole HTTP message
         $parts = $message_parser->parseResponse("HTTP/1.1 200 OK\r\n" . $part);
         // now throw this single faked message through the Single GetObject response parser
         $single = new Response($parts['code'], $parts['headers'], Stream::factory($parts['body']));
         $obj = $parser->parse($single);
         // add information about this multipart to the returned collection
         $collection->push($obj);
     }
     return $collection;
 }
 public function testBase()
 {
     $response = new Response(200, ['Cache-Control' => ['max-age = 120', ' stale-while-revalidate=  60 ', '  private ', 'zero=0', 'nothing = ', 'false = false']]);
     $values = new KeyValueHttpHeader($response->getHeader('Cache-Control'));
     $this->assertTrue($values->has('max-age'));
     $this->assertTrue($values->has('stale-while-revalidate'));
     $this->assertTrue($values->has('private'));
     $this->assertTrue($values->has('zero'));
     $this->assertTrue($values->has('nothing'));
     $this->assertTrue($values->has('false'));
     $this->assertEquals(120, $values->get('max-age'));
     $this->assertEquals(60, $values->get('stale-while-revalidate'));
     $this->assertEquals(0, $values->get('zero'));
     $this->assertEquals('', $values->get('nothing'));
     $this->assertEquals('false', $values->get('false'));
 }
Ejemplo n.º 9
0
 public function verifySubProtocol(Request $request, Response $response)
 {
     $subProtocolRequest = $request->getHeader('Sec-WebSocket-Protocol');
     if (empty($subProtocolRequest)) {
         return true;
     }
     $subProtocolResponse = $response->getHeader('Sec-WebSocket-Protocol');
     if (count($subProtocolResponse) !== 1) {
         // there should be exactly one subprotocol sent back if we requested
         return false;
     }
     if (in_array($subProtocolResponse[0], $subProtocolRequest)) {
         // the response is one of the requested subprotocols
         return true;
     }
     return false;
 }
Ejemplo n.º 10
0
 /**
  * Validate the HTTP response and throw exceptions on errors
  *
  * @param HttpResponse $response
  * @throws ServerException
  */
 private function validateResponse($response)
 {
     if ($response->getStatusCode() !== 200) {
         $statusCode = $response->getStatusCode();
         throw new ServerException('Server responded with HTTP status ' . $statusCode, $statusCode);
     } else {
         if (strpos($response->getHeader('Content-Type')[0], 'application/json') === false) {
             throw new ServerException('Server did not respond with the expected content-type (application/json)');
         }
     }
     try {
         $body = (string) $response->getBody();
         $json = json_decode($body, true);
         if (json_last_error()) {
             throw new ServerException(json_last_error_msg());
         }
     } catch (RuntimeException $e) {
         throw new ServerException($e->getMessage());
     }
 }
Ejemplo n.º 11
0
 public function testCanSetHeaderAsArray()
 {
     $r = new Response(200, ['foo' => ['baz ', ' bar ']]);
     $this->assertEquals('baz, bar', $r->getHeaderLine('foo'));
     $this->assertEquals(['baz', 'bar'], $r->getHeader('foo'));
 }
Ejemplo n.º 12
0
 /**
  * @param RequestInterface $request
  * @param Response $response
  * @return \Guzzle\Http\EntityBodyInterface|mixed|string
  */
 public function handleResponse(Request $request, Response $response)
 {
     $body = $response->getBody(true);
     $contentType = $response->getHeader('Content-Type')[0];
     switch ($contentType) {
         case "application/json":
             $body = json_decode($body, true);
             break;
     }
     return [$response->getStatusCode(), $body];
 }
Ejemplo n.º 13
0
 /**
  * Builds a pretty failure message from the specified response's warning headers, using the specified request for
  * additional information.
  * @param \GuzzleHttp\Psr7\Request   $request   HTTP request object
  * @param \GuzzleHttp\Psr7\Response  $response  HTTP response object
  * @return string
  */
 protected function buildFailureMessage(Request $request, Response $response)
 {
     $message = "Unsuccessful " . $request->getMethod() . " to " . $request->getUri() . " (" . $response->getStatusCode() . ")";
     $warnings = $response->getHeader('Warning');
     foreach ($warnings as $w) {
         $message .= "\nWarning: " . $w;
     }
     return $message;
 }
Ejemplo n.º 14
0
 /**
  * Response contents type.
  *
  * @return string The response header content type.
  */
 protected function type()
 {
     $type = $this->response->getHeader('Content-Type');
     return strtolower(reset($type));
 }
Ejemplo n.º 15
0
 /**
  * After each request update the rate limits that are received in the headers
  */
 private function _updateRateLimits()
 {
     App::getInstance()->getRateLimit()->update(current($this->_response->getHeader(ApiHelper::HEADER_RATE_LIMIT)), current($this->_response->getHeader(ApiHelper::HEADER_RATE_LIMIT_REMAINING)), current($this->_response->getHeader(ApiHelper::HEADER_RATE_LIMIT_RESET)));
 }
Ejemplo n.º 16
0
 /**
  *
  * @return string
  */
 public function getHeader($header)
 {
     return $this->response->getHeader($header);
 }
Ejemplo n.º 17
0
 /**
  * Attempt to pull rate limit headers from response and add to client
  *
  * @param  Response  $response
  *
  * @return void
  */
 private function parseRateLimitFromResponse(Response $response)
 {
     $this->rate_limit = new RateLimit($response->getHeader('X-Rate-Limit-Limit'), $response->getHeader('X-Rate-Limit-Remaining'), $response->getHeader('X-Rate-Limit-Reset'));
 }
Ejemplo n.º 18
0
 /**
  * Attempts to pull rate limit headers from response and add to client.
  *
  * @param    Response $response
  *
  * @return   void
  */
 private function parseRateLimitFromResponse(Response $response)
 {
     $rateLimitHeaders = array_filter([$response->getHeader('X-Rate-Limit-Limit'), $response->getHeader('X-Rate-Limit-Remaining'), $response->getHeader('X-Rate-Limit-Reset')]);
     if (count($rateLimitHeaders) == 3) {
         $rateLimitClass = new ReflectionClass(RateLimit::class);
         $this->rate_limit = $rateLimitClass->newInstanceArgs($rateLimitHeaders);
     }
 }
Ejemplo n.º 19
0
 public function assertResponseHasContentType($expected, Response $response)
 {
     $this->assertContains($expected, $response->getHeader('Content-Type'));
 }
Ejemplo n.º 20
0
 /**
  * Assert that the response can be parsed
  * 
  * @param Request  $request
  * @param Response $response
  * @param array    $options
  */
 protected function parseResponseAssert($request, $response, $options)
 {
     $parse = $options['parse'];
     list($contentType) = preg_replace('/\\s*;.*$/', '', $response->getHeader('Content-Type')) + [null];
     // Only JSON is currently supported
     if ($parse !== 'application/json') {
         throw new \Exception("Parsing is only supported for 'application/json', not '{$parse}'");
     }
     if (!isset($contentType)) {
         trigger_error("Server response doesn't specify the content type, assuming {$parse}", E_USER_NOTICE);
     }
     if (!in_array($contentType, [$parse, 'text/plain'])) {
         $message = "Server responded with '{$contentType}', while expecting '{$parse}'";
         throw new InvalidContentException($message, $request, $response);
     }
 }