/**
  * {@inheritdoc}
  */
 public function getLatestResponseHeaders()
 {
     if (null === $this->response) {
         return;
     }
     return array('reset' => (int) (string) $this->response->getHeader('RateLimit-Reset'), 'remaining' => (int) (string) $this->response->getHeader('RateLimit-Remaining'), 'limit' => (int) (string) $this->response->getHeader('RateLimit-Limit'));
 }
Esempio n. 2
0
 public function decode(ResponseInterface $raw, $totalTime = 0)
 {
     $executionTime = $callTime = 0;
     if ($raw->hasHeader('X-Execution-Time')) {
         $executionTime = $raw->getHeader('X-Execution-Time');
     }
     if ($raw->hasHeader('X-Call-Time')) {
         $callTime = $raw->getHeader('X-Call-Time');
     }
     $body = '';
     try {
         $body = (string) $raw->getBody();
         $result = $this->_getDecoder()->decode($body, self::FORMAT, $this->_getDecodeContext());
     } catch (\Exception $e) {
         if (!empty($body)) {
             $body = ' (' . $body . ')';
         }
         error_log("Invalid API Response: " . $body);
         throw new InvalidApiResponseException("Unable to decode raw api response.", 500, $e);
     }
     if (!property_exists($result, 'type') || !property_exists($result, 'status') || !property_exists($result, 'result') || !property_exists($result->status, 'message') || !property_exists($result->status, 'code')) {
         error_log("Invalid API Result: " . json_encode($result));
         throw new InvalidApiResponseException("Invalid api result", 500);
     }
     if ($executionTime === 0) {
         $executionTime = $totalTime;
     }
     if ($callTime === 0) {
         $callTime = $executionTime;
     }
     return ResponseBuilder::create(ApiCallData::create($result->type, $result->result, $result->status->code, $result->status->message, (double) str_replace([',', 'ms'], '', $totalTime), (double) str_replace([',', 'ms'], '', $executionTime), (double) str_replace([',', 'ms'], '', $callTime)));
 }
Esempio n. 3
0
 /**
  * Gets the age of a response in seconds.
  *
  * @param ResponseInterface $response
  *
  * @return int
  */
 public static function getResponseAge(ResponseInterface $response)
 {
     if ($response->hasHeader('Age')) {
         return (int) $response->getHeader('Age');
     }
     $date = strtotime($response->getHeader('Date') ?: 'now');
     return time() - $date;
 }
Esempio n. 4
0
 /**
  * @param ResponseInterface $response raw json response
  * @param bool              $throw    Should throw API errors as exceptions
  *
  * @throws \Exception
  */
 public function __construct(ResponseInterface $response = null, $throw = true)
 {
     if ($response !== null) {
         $this->_executionTime = $response->getHeader('X-Execution-Time');
         $this->_callTime = $response->getHeader('X-Call-Time');
         $this->readJson((string) $response->getBody(), $throw);
     }
 }
 protected function getResponse(GuzzleResponse $response)
 {
     if (strpos($response->getHeader('Content-Type'), 'json')) {
         $returnResponse = new JsonResponse($response->getBody());
     } elseif (strpos($response->getHeader('Content-Type'), 'xml')) {
         $returnResponse = new XmlResponse($response->xml());
     } else {
         throw new \Exception('Unknow return type');
     }
     return $returnResponse;
 }
Esempio n. 6
0
 /**
  * Gets the Location header.
  *
  * @throws \RuntimeException If the Location header is missing
  *
  * @return string
  */
 public function getLocation()
 {
     if (!$this->response->hasHeader('Location')) {
         throw new \RuntimeException('Response is missing a Location header');
     }
     return $this->response->getHeader('Location');
 }
Esempio n. 7
0
 /**
  * @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;
 }
 function it_should_make_post_request(ResponseInterface $responce)
 {
     $responce->getHeader("Content-Type")->willReturn('blablaxmlblabla');
     $responce->getBody()->willReturn('<xml></xml>');
     $this->client->post(Argument::any(), Argument::any())->willReturn($responce);
     $responce->xml()->willReturn(new \SimpleXMLElement('<xml></xml>'));
     $this->post(Argument::type('string'))->shouldBeAnInstanceOf('Bxav\\Component\\ResellerClub\\Model\\XmlResponse');
 }
Esempio n. 9
0
 public function visit(GuzzleCommandInterface $command, ResponseInterface $response, Parameter $param, &$result, array $context = array())
 {
     // Retrieving a single header by name
     $name = $param->getName();
     if ($header = $response->getHeader($param->getWireName())) {
         $result[$name] = $param->filter($header);
     }
 }
Esempio n. 10
0
 private function parseHeaders(ResponseInterface $response, array &$data)
 {
     $data['message'] = $response->getStatusCode() . ' ' . $response->getReasonPhrase();
     if ($requestId = $response->getHeader('x-amz-request-id')) {
         $data['request_id'] = $requestId;
         $data['message'] .= " (Request-ID: {$requestId})";
     }
 }
 /**
  * @Then the response is oauth2 format
  */
 public function theResponseHasTheOAuth2Format()
 {
     $expectedHeaders = ['cache-control' => 'no-store', 'pragma' => 'no-cache'];
     foreach ($expectedHeaders as $name => $value) {
         if ($this->response->getHeader($name) != $value) {
             throw new \Exception(sprintf("Header %s is should be %s, %s given", $name, $value, $this->response->getHeader($name)));
         }
     }
 }
Esempio n. 12
0
 /**
  * Populates the current resource from a response object.
  *
  * @param ResponseInterface $response
  *
  * @return $this|ResourceInterface
  */
 public function populateFromResponse(ResponseInterface $response)
 {
     if (strpos($response->getHeader('Content-Type'), 'application/json') === 0) {
         $json = $response->json();
         if (!empty($json)) {
             $this->populateFromArray($this->flatten($json));
         }
     }
     return $this;
 }
Esempio n. 13
0
 public function parse(ResponseInterface $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;
 }
 /**
  * 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->getHeader('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($response->json(['object' => true]), $schemaManager, $path, $httpMethod, $httpCode, $message);
 }
Esempio n. 15
0
 public function parseMetadata(ResponseInterface $response)
 {
     $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);
         }
     }
     return $metadata;
 }
Esempio n. 16
0
 /**
  * @Then The following headers should be set
  * @param \Behat\Gherkin\Node\TableNode $table
  * @throws \Exception
  */
 public function theFollowingHeadersShouldBeSet(\Behat\Gherkin\Node\TableNode $table)
 {
     foreach ($table->getTable() as $header) {
         $headerName = $header[0];
         $expectedHeaderValue = $header[1];
         $returnedHeader = $this->response->getHeader($headerName);
         if ($returnedHeader !== $expectedHeaderValue) {
             throw new \Exception(sprintf("Expected value '%s' for header '%s', got '%s'", $expectedHeaderValue, $headerName, $returnedHeader));
         }
     }
 }
 /**
  * @param \GuzzleHttp\Message\ResponseInterface       $response
  * @param \GuzzleHttp\Message\MessageParser           $parser
  * @param \GuzzleHttp\Message\MessageFactoryInterface $messageFactory
  */
 public function __construct(ResponseInterface $response, MessageParser $parser = null, MessageFactoryInterface $messageFactory = null)
 {
     $matches = null;
     $body = $response->getBody();
     $header = $response->getHeader('Content-Type');
     if (!preg_match('/boundary=(.*)$/', $header, $matches) || !isset($matches[1])) {
         throw new InvalidArgumentException("Unable to parse boundary from content type : '{$header}'");
     }
     $this->response = $response;
     $this->parser = $parser ?: new MessageParser();
     $this->factory = $messageFactory ?: new MessageFactory();
     $this->iterator = new MultipartStreamIterator($body, $matches[1]);
 }
 /**
  * @param RequestInterface|ResponseInterface $message
  * @return string
  */
 protected function formatBody($message)
 {
     $header = $message->getHeader('Content-Type');
     if (JsonStringFormatter::isJsonHeader($header)) {
         $formatter = new JsonStringFormatter();
         return $formatter->format($message->getBody());
     } elseif (XmlStringFormatter::isXmlHeader($header)) {
         $formatter = new XmlStringFormatter();
         return $formatter->format($message->getBody());
     }
     $factory = new StringFactoryFormatter();
     return $factory->format($message->getBody());
 }
 public function parseResponse(ResponseInterface $response, $classes = array())
 {
     $contentType = $response->getHeader('content-type');
     $contentType = explode(';', $contentType);
     $boundary = false;
     foreach ($contentType as $part) {
         $part = explode('=', $part, 2);
         if (isset($part[0]) && 'boundary' == trim($part[0])) {
             $boundary = $part[1];
         }
     }
     $body = (string) $response->getBody();
     if (!empty($body)) {
         $body = str_replace("--{$boundary}--", "--{$boundary}", $body);
         $parts = explode("--{$boundary}", $body);
         $responses = array();
         foreach ($parts as $i => $part) {
             $part = trim($part);
             if (!empty($part)) {
                 list($rawHeaders, $part) = explode("\r\n\r\n", $part, 2);
                 $headers = $this->parseRawHeaders($rawHeaders);
                 $status = substr($part, 0, strpos($part, "\n"));
                 $status = explode(" ", $status);
                 $status = $status[1];
                 list($partHeaders, $partBody) = $this->parseHttpResponse($part, false);
                 $response = new Response($status, $partHeaders, Stream::factory($partBody));
                 // Need content id.
                 $key = $headers['content-id'];
                 $class = '';
                 if (!empty($this->expected_classes[$key])) {
                     $class = $this->expected_classes[$key];
                 }
                 try {
                     $response = Google_Http_REST::decodeHttpResponse($response);
                     if (isset($classes[$key])) {
                         $response = new $classes[$key]($response);
                     }
                 } catch (Google_Service_Exception $e) {
                     // Store the exception as the response, so successful responses
                     // can be processed.
                     $response = $e;
                 }
                 $responses[$key] = $response;
             }
         }
         return $responses;
     }
     return null;
 }
Esempio n. 20
0
 /**
  * Get the right I/O Class and rewrite the content.
  *
  * @return $this
  */
 protected function parseResponse()
 {
     $strContentType = $this->request->getHeader('Content-Type');
     $strContentType = preg_replace("/;.*\$/", "", $strContentType);
     // Search a engine
     $objIOEngine = \CtoCommunication\InputOutput\Factory::getEngingeForContentType($strContentType);
     // Check if we have found one
     if ($objIOEngine == false) {
         throw new \RuntimeException("No I/O class found for " . $strContentType);
     }
     // Parse response
     $this->response = $objIOEngine->InputResponse($this->response, $this->objCodifyengine);
     // Write Debug msg
     $strDebug = "";
     $strDebug .= "Success:     ";
     $strDebug .= $this->response->isSuccess() ? "true" : "false";
     $strDebug .= "\n";
     if ($this->response->isSplitcontent() == true) {
         $strDebug .= "Split:       " . $this->response->isSplitcontent();
         $strDebug .= "\n";
         $strDebug .= "Splitinfo:   " . "Count - " . $this->response->getSplitcount() . " Name - " . $this->response->getSplitname();
         $strDebug .= "\n";
     }
     if ($this->response->getError() != null && is_object($this->response->getError())) {
         $strDebug .= "Error:       " . $this->response->getError()->getMessage();
         $strDebug .= "\n";
         $strDebug .= "Error RPC:   " . $this->response->getError()->getRPC();
         $strDebug .= "\n";
         $strDebug .= "Error Class: " . $this->response->getError()->getClass();
         $strDebug .= "\n";
         $strDebug .= "Error Func.: " . $this->response->getError()->getFunction();
         $strDebug .= "\n";
     }
     $strDebug .= "Response:    " . substr(json_encode($this->response->getResponse()), 0, 2048);
     $this->objDebug->addDebug("Response Object", $strDebug);
     return $this;
 }
Esempio n. 21
0
 /**
  * Set the appropriate URL on the request based on the location header
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  * @param array             $protocols
  */
 private function setRedirectUrl(RequestInterface $request, ResponseInterface $response, array $protocols)
 {
     $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($request->getUrl());
         // Remove query string parameters and just take what is present on
         // the redirect Location header
         $originalUrl->getQuery()->clear();
         $location = $originalUrl->combine($location);
     }
     // Ensure that the redirect URL is allowed based on the protocols.
     if (!in_array($location->getScheme(), $protocols)) {
         throw new BadResponseException(sprintf('Redirect URL, %s, does not use one of the allowed redirect protocols: %s', $location, implode(', ', $protocols)), $request, $response);
     }
     $request->setUrl($location);
 }
Esempio n. 22
0
 /**
  * 
  * @param HttpResponse $response
  * @return \webignition\InternetMediaType\InternetMediaType
  */
 private function getContentTypeFromResponse(HttpResponse $response)
 {
     $mediaTypeParser = new InternetMediaTypeParser();
     $mediaTypeParser->setAttemptToRecoverFromInvalidInternalCharacter(true);
     $mediaTypeParser->setIgnoreInvalidAttributes(true);
     return $mediaTypeParser->parse($response->getHeader('content-type'));
 }
Esempio n. 23
0
 /**
  * @param string $header
  * @return string
  */
 public function header($header)
 {
     return $this->response->getHeader($header);
 }
Esempio n. 24
0
 function it_throws_exception_when_invalid_response_format_is_received($client, ResponseInterface $response)
 {
     $response->getHeader('Content-Type')->willReturn('application/xhtml+xml');
     $response->getBody()->willReturn('body');
     $response->getStatusCode()->willReturn(400);
     $client->get('uri/1')->willReturn($response)->shouldBeCalled();
     $this->shouldThrow(new InvalidResponseFormatException('body', 400))->during('get', [1]);
 }
Esempio n. 25
0
 public function extractCookies(RequestInterface $request, ResponseInterface $response)
 {
     if ($cookieHeader = $response->getHeader('Set-Cookie', true)) {
         foreach ($cookieHeader as $cookie) {
             $sc = SetCookie::fromString($cookie);
             if (!$sc->getDomain()) {
                 $sc->setDomain($request->getHost());
             }
             $this->setCookie($sc);
         }
     }
 }
Esempio n. 26
0
 /**
  * Set the appropriate URL on the request based on the location header
  *
  * @param RequestInterface  $request
  * @param ResponseInterface $response
  */
 private function setRedirectUrl(RequestInterface $request, 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($request->getUrl());
         // Remove query string parameters and just take what is present on
         // the redirect Location header
         $originalUrl->getQuery()->clear();
         $location = $originalUrl->combine($location);
     }
     $request->setUrl($location);
 }
Esempio n. 27
0
 private function getManifestEntries($key, $currentTime, ResponseInterface $response, $persistedRequest)
 {
     $entries = [];
     $manifest = $this->cache->fetch($key);
     if (!$manifest) {
         return $entries;
     }
     // Determine which cache entries should still be in the cache
     $vary = $response->getHeader('Vary');
     foreach (unserialize($manifest) as $entry) {
         // Check if the entry is expired
         if ($entry[4] < $currentTime) {
             continue;
         }
         $varyCmp = isset($entry[1]['vary']) ? $entries[1]['vary'] : '';
         if ($vary != $varyCmp || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) {
             $entries[] = $entry;
         }
     }
     return $entries;
 }
Esempio n. 28
0
 private function genericHandler(ResponseInterface $response)
 {
     $code = (string) $response->getStatusCode();
     return ['request_id' => (string) $response->getHeader('x-amzn-requestid'), 'code' => null, 'message' => null, 'type' => $code[0] == '4' ? 'client' : 'server', 'parsed' => $response->json()];
 }
 private function handle304Response(RequestInterface $request, ResponseInterface $response, ResponseInterface $validated, CompleteEvent $event)
 {
     // Make sure that this response has the same ETag
     if ($validated->getHeader('ETag') !== $response->getHeader('ETag')) {
         // Revalidation failed, so remove from cache and retry.
         $this->storage->delete($request);
         $event->intercept($event->getClient()->send($request));
         return;
     }
     // Replace cached headers with any of these headers from the
     // origin server that might be more up to date
     $modified = false;
     foreach (self::$replaceHeaders as $name) {
         if ($validated->hasHeader($name) && $validated->getHeader($name) != $response->getHeader($name)) {
             $modified = true;
             $response->setHeader($name, $validated->getHeader($name));
         }
     }
     // Store the updated response in cache
     if ($modified) {
         $this->storage->cache($request, $response);
     }
 }
Esempio n. 30
0
 private function responseToArray(ResponseInterface $response)
 {
     $responseType = $response->getHeader('Content-Type');
     if (false === strpos($responseType, 'application/json') && false === strpos($responseType, 'application/xml')) {
         throw new InvalidResponseFormatException((string) $response->getBody(), $response->getStatusCode());
     }
     return strpos($responseType, 'application/json') !== false ? $response->json() : $response->xml();
 }