Example #1
2
 /**
  * Returns object with properties int:status object:body
  * @param string $method
  * @param string $path
  * @param array $query
  * @param bool $doAuth
  * @throws \InvalidArgumentException
  * @throws \Exception
  * @return \stdClass
  */
 public function request($method, $path, $query = array(), $doAuth = false)
 {
     $this->userAgent = 'Rocker REST Client v' . Server::VERSION;
     $method = strtolower($method);
     $request = $this->initiateRequest($method, $path, $query);
     if ($doAuth) {
         $this->addAuthHeader($request);
     }
     try {
         $this->lastResponse = $request->send();
     } catch (\Guzzle\Http\Exception\ClientErrorResponseException $e) {
         $this->lastResponse = $e->getResponse();
         if ($this->lastResponse->getStatusCode() == 401 && !$doAuth && !empty($this->user)) {
             trigger_error('Doing unauthenticated requests to an URI that requires authentication (' . $path . ')', E_WARNING);
             return $this->request($method, $path, $query, true);
         }
     }
     if ($this->lastResponse->getStatusCode() == 400) {
         throw new ClientException($this->lastResponse, 400);
     }
     if ($this->lastResponse->getStatusCode() == 204) {
         return (object) array('status' => 204, 'body' => array());
     }
     if (strpos($this->lastResponse->getContentType(), 'json') === false) {
         throw new ClientException($this->lastResponse, ClientException::ERR_UNEXPECTED_CONTENT_TYPE, 'Server responded with unexpected content type (' . $this->lastResponse->getContentType() . ')');
     }
     $str = (string) $this->lastResponse->getBody();
     $body = json_decode($str);
     return (object) array('status' => $this->lastResponse->getStatusCode(), 'headers' => $this->headerCollectionToArray($this->lastResponse->getHeaders()), 'body' => $body);
 }
 public function getResponseHeaders()
 {
     $headers = array();
     foreach ($this->response->getHeaders()->getAll() as $header => $headerObject) {
         $allHeaderValues = $headerObject->toArray();
         // only getting the first of the array, most of the cases this will
         // work as expected
         $headers[$header] = $allHeaderValues[0];
     }
     return $headers;
 }
Example #3
0
 /**
  * Factory method that allows for easy instantiation from a Response object.
  *
  * @param Response        $response
  * @param AbstractService $service
  * @return static
  */
 public static function fromResponse(Response $response, AbstractService $service)
 {
     $object = new static($service);
     if (null !== ($headers = $response->getHeaders())) {
         $object->setMetadata($headers, true);
     }
     return $object;
 }
 /**
  * Get all response headers.
  *
  * @return array Associative array with $header => $value (value can be an array if it hasn't a single value)
  *
  * @throws \RuntimeException If request hasn't been send already
  */
 public function getHeaders()
 {
     $headers = array();
     foreach ($this->response->getHeaders()->getAll() as $header => $headerObject) {
         $allHeaderValues = $headerObject->toArray();
         $headers[strtolower($header)] = implode(';', $allHeaderValues);
     }
     return $headers;
 }
Example #5
0
 /**
  * Returns a list of headers as key/value pairs.
  *
  * @return array List of headers as key/value pairs.
  */
 public function getHeaders()
 {
     $headers = array();
     foreach (parent::getHeaders() as $header) {
         $values = $header->toArray();
         $headers[$header->getName()] = $values[0];
     }
     return $headers;
 }
 /**
  * Prepares an EmbeddedResponse from the original response and data
  *
  * @param Guzzle\Http\Message\Response $originalResponse
  * @param array                        $data
  *
  * @return Desk\Relationship\Resource\EmbeddedResponse
  */
 public function createResponse(Response $originalResponse, array $data)
 {
     $statusCode = $originalResponse->getStatusCode();
     $reasonPhrase = $originalResponse->getReasonPhrase();
     $headers = $originalResponse->getHeaders();
     $body = json_encode($data);
     // set reason phrase -- needs to be done vie
     $response = $this->newResponse($statusCode, $headers, $body);
     $response->setReasonPhrase($reasonPhrase);
     return $response;
 }
Example #7
0
 protected function processPrefixedHeaders(Response $response, Parameter $param, &$value)
 {
     if ($prefix = $param->getSentAs()) {
         $container = $param->getName();
         $len = strlen($prefix);
         foreach ($response->getHeaders()->toArray() as $key => $header) {
             if (stripos($key, $prefix) === 0) {
                 $value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header;
             }
         }
     }
 }
Example #8
0
 /**
  * @param array $responseCollection
  * @return \CanalTP\AbstractGuzzle\Guzzle
  */
 public function getMock(array $responseCollection)
 {
     $plugin = new MockPlugin();
     foreach ($responseCollection as $response) {
         if ($response instanceof Psr7Response) {
             $response = new Response($response->getStatusCode(), $response->getHeaders(), $response->getBody());
         }
         $plugin->addResponse($response);
     }
     $client = GuzzleFactory::createClient('');
     $client->addSubscriber($plugin);
     return $client;
 }
Example #9
0
 /**
  * Reads response meta tags to guess content-type charset.
  */
 protected function createResponse(GuzzleResponse $response)
 {
     $body = $response->getBody(true);
     $statusCode = $response->getStatusCode();
     $headers = $response->getHeaders()->getAll();
     $contentType = $response->getContentType();
     if (!$contentType || false === strpos($contentType, 'charset=')) {
         if (preg_match('/\\<meta[^\\>]+charset *= *["\']?([a-zA-Z\\-0-9]+)/i', $body, $matches)) {
             $contentType .= ';charset=' . $matches[1];
         }
     }
     $headers['Content-Type'] = $contentType;
     return new Response($body, $statusCode, $headers);
 }
Example #10
0
 /**
  * Process a prefixed header array
  *
  * @param Response  $response Response that contains the headers
  * @param Parameter $param    Parameter object
  * @param array     $value    Value response array to modify
  */
 protected function processPrefixedHeaders(Response $response, Parameter $param, &$value)
 {
     // Grab prefixed headers that should be placed into an array with the prefix stripped
     if ($prefix = $param->getSentAs()) {
         $container = $param->getName();
         $len = strlen($prefix);
         // Find all matching headers and place them into the containing element
         foreach ($response->getHeaders() as $key => $header) {
             if (stripos($key, $prefix) === 0) {
                 // Account for multi-value headers
                 $value[$container][substr($key, $len)] = count($header) == 1 ? end($header) : $header;
             }
         }
     }
 }
Example #11
0
 /**
  * {@inheritdoc}
  */
 public function cache($key, Response $response, $ttl = null)
 {
     if ($ttl === null) {
         $ttl = $this->defaultTtl;
     }
     if ($ttl) {
         $response->setHeader('X-Guzzle-Cache', "key={$key}, ttl={$ttl}");
         // Remove excluded headers from the response  (see RFC 2616:13.5.1)
         foreach ($this->excludeResponseHeaders as $header) {
             $response->removeHeader($header);
         }
         // Add a Date header to the response if none is set (for validation)
         if (!$response->getDate()) {
             $response->setHeader('Date', Utils::getHttpDate('now'));
         }
         $this->cache->save($key, array($response->getStatusCode(), $response->getHeaders()->getAll(), $response->getBody(true)), $ttl);
     }
 }
 public function cache($key, Response $response, $ttl = null)
 {
     if ($ttl === null) {
         $ttl = $this->defaultTtl;
     }
     $ttl += $response->getMaxAge();
     if ($ttl) {
         $response->setHeader('X-Guzzle-Cache', "key={$key}; ttl={$ttl}");
         // Remove excluded headers from the response  (see RFC 2616:13.5.1)
         foreach ($this->excludeResponseHeaders as $header) {
             $response->removeHeader($header);
         }
         // Add a Date header to the response if none is set (for validation)
         if (!$response->getDate()) {
             $response->setHeader('Date', gmdate(ClientInterface::HTTP_DATE));
         }
         $this->cache->save($key, array($response->getStatusCode(), $response->getHeaders()->toArray(), $response->getBody(true)), $ttl);
     }
 }
Example #13
0
 protected function createResponse(GuzzleResponse $response)
 {
     $headers = $response->getHeaders()->toArray();
     return new Response($response->getBody(true), $response->getStatusCode(), $headers);
 }
Example #14
0
 /**
  * Takes a response and stocks common values from both the body and the headers.
  *
  * @param Response $response
  * @return $this
  */
 public function populateFromResponse(Response $response)
 {
     $this->content = $response->getBody();
     $headers = $response->getHeaders();
     return $this->setMetadata($headers, true)->setContentType((string) $headers['Content-type'])->setLastModified((string) $headers['Last-Modified'])->setContentLength((string) $headers['Content-Length'])->setEtag((string) $headers['ETag']);
 }
Example #15
0
 /**
  * @param bool $asObjects
  * @return \Guzzle\Common\Collection
  */
 public function getHeaders($asObjects = false)
 {
     return $this->response->getHeaders($asObjects);
 }
Example #16
0
 /**
  * Process response
  *
  * @param \Guzzle\Http\Message\Response $response
  *
  * @return \Guzzle\Http\Message\Response
  *
  * @throws ApiBadResponseException
  */
 protected function processResponse(\Guzzle\Http\Message\Response $response)
 {
     // Get the nonce from headers
     $headers = $response->getHeaders();
     if (!$headers->offsetExists('replay-nonce')) {
         throw new ApiBadResponseException('Response does not contain "replay-nonce" header', 16);
     }
     // Update the nonce in DB & memory
     $nonce = (string) $headers->get('replay-nonce');
     $this->storage->updateNonce($nonce);
     $this->nonce = $nonce;
     return $response;
 }
Example #17
0
 /**
  * @param \Guzzle\Http\Message\Response $guzzleResponse
  * @return array
  */
 private function parseHeaders($guzzleResponse)
 {
     $responseHeaders = array();
     foreach ($guzzleResponse->getHeaders() as $header) {
         $value = $header->toArray();
         $responseHeaders[$header->getName()] = $value[0];
     }
     return $responseHeaders;
 }
Example #18
0
 /**
  * Save data to the cache adapter
  *
  * @param string   $key      The cache key
  * @param Response $response The response to cache
  * @param int      $lifetime Amount of seconds to cache
  *
  * @return int Returns the lifetime of the cached data
  */
 protected function saveCache($key, Response $response, $lifetime = null)
 {
     $lifetime = $lifetime ?: $this->defaultLifetime;
     // If the data is cacheable, then save it to the cache adapter
     if ($lifetime) {
         // Remove excluded headers from the response  (see RFC 2616:13.5.1)
         foreach ($this->excludeResponseHeaders as $header) {
             $response->removeHeader($header);
         }
         // Add a Date header to the response if none is set (for validation)
         if (!$response->getDate()) {
             $response->setHeader('Date', Utils::getHttpDate('now'));
         }
         $data = array('c' => $response->getStatusCode(), 'h' => $response->getHeaders(), 'b' => $response->getBody(true));
         if ($this->serialize) {
             $data = serialize($data);
         }
         $this->getCacheAdapter()->save($key, $data, $lifetime);
     }
     return $lifetime;
 }
 /**
  * Create a tailored PUT request for each file
  *
  * @param Response $response
  * @return \Guzzle\Http\Message\EntityEnclosingRequestInterface
  */
 protected function createPutRequest(Response $response)
 {
     $segments = Url::factory($response->getEffectiveUrl())->getPathSegments();
     $name = end($segments);
     // Retrieve content and metadata
     $file = $this->newContainer->dataObject()->setName($name);
     $file->setMetadata($response->getHeaders(), true);
     return $this->getClient()->put($file->getUrl(), $file::stockHeaders($file->getMetadata()->toArray()), $response->getBody());
 }
Example #20
0
 protected function createResponse(GuzzleResponse $response)
 {
     $headers = $response->getHeaders()->getAll();
     $headers = array_map(function ($header) {
         if ($header instanceof GuzzleHeader) {
             return $header->toArray();
         }
         return $header;
     }, $headers);
     return new Response($response->getBody(true), $response->getStatusCode(), $headers);
 }
Example #21
0
 public function getHeaders()
 {
     return $this->_response->getHeaders()->toArray();
 }
Example #22
0
 /**
  * Takes a response and stocks common values from both the body and the headers.
  *
  * @param Response $response
  * @return $this
  */
 public function populateFromResponse(Response $response)
 {
     $this->content = $response->getBody();
     $headers = $response->getHeaders();
     return $this->setMetadata($headers, true)->setContentType((string) $headers[HeaderConst::CONTENT_TYPE])->setLastModified((string) $headers[HeaderConst::LAST_MODIFIED])->setContentLength((string) $headers[HeaderConst::CONTENT_LENGTH])->setEtag((string) $headers[HeaderConst::ETAG]);
 }
Example #23
0
 /**
  * @param HttpResponse $response
  */
 public function __construct(HttpResponse $response)
 {
     $this->response = $response;
     $this->limiter = new RateLimit($response->getHeaders());
 }
 /**
  * Decodes a response into a standard formatted array. (See
  * ClientInterface for documentation).
  *
  * @param  Response $response Guzzle response
  *
  * @return array                       Response as array
  */
 private function decodeResponse(Response $response)
 {
     return array('headers' => $response->getHeaders(), 'status' => $response->getStatusCode(), 'reason' => $response->getReasonPhrase(), 'version' => $response->getProtocolVersion(), 'body' => (string) $response->getBody(true));
 }
 /**
  * Returns a Kinvey service specific exception
  *
  * @param RequestInterface $request  Unsuccessful request
  * @param Response         $response Unsuccessful response that was encountered
  *
  * @return Exception
  */
 public function fromResponse(RequestInterface $request, Response $response)
 {
     $message = $response->json();
     $parts = array('type' => isset($message['error']) ? $message['error'] : null, 'description' => isset($message['description']) ? $message['description'] : null, 'request_id' => $response->getHeaders()->get('x-kinvey-request-id'), 'debug' => isset($message['debug']) && !empty($message['debug']) ? $message['debug'] : null);
     return $this->createException($request, $response, $parts);
 }
Example #26
0
 protected function createResponse(GuzzleResponse $response)
 {
     return new Response($response->getBody(true), $response->getStatusCode(), $response->getHeaders()->getAll());
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function getHeaders()
 {
     return $this->response->getHeaders();
 }