/** * 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); }
/** * @throws HttpException */ protected function handleError() { $body = (string) $this->response->getBody(true); $code = (int) $this->response->getStatusCode(); $content = json_decode($body); throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code); }
/** * request error * @param \Guzzle\Common\Event $event */ public function onRequestError(Event $event) { $this->request = $event->offsetGet('request'); $this->response = $event->offsetGet('response'); $body = $this->response->getBody(true); switch ($this->response->getStatusCode()) { case 400: $this->error400($body); break; case 520: $this->error520($body); break; default: $this->commonError($body); break; } }
/** * Should return if sending the data was successful * * @return bool */ public function isSuccess() { $statuscode = $this->response->getStatusCode(); if (!in_array($statuscode, ['200', '204'])) { throw new \Exception('HTTP Code ' . $statuscode . ' ' . $this->response->getBody()); } return true; }
protected function createResponse(\Guzzle\Http\Message\Response $gResponse, Request $request) { $response = new Response($gResponse->getBody(), $gResponse->getStatusCode()); foreach ($gResponse->getHeaderLines() as $header) { list($name, $value) = explode(':', $header, 2); $response->headers->set($name, $value); } return $this->prepareResponse($response, $request); }
/** * Check the response for an error. * * @param Response $response The response received. * * @param RequestInterface $request The request sent. * * @return void * * @throws \RuntimeException On any error. */ protected function checkError(Response $response, RequestInterface $request) { if ($response->getStatusCode() == 200 || $response->getStatusCode() == 201) { return; } switch ($response->getHeader('Content-Type')) { case 'text/plain': throw new \RuntimeException('Error: ' . $response->getBody(true) . ' URI: ' . $request->getUrl()); case 'application/json': $error = json_decode($response->getBody(true)); if (isset($error->message)) { throw new \RuntimeException($error->message . ' URI: ' . $request->getUrl()); } break; default: throw new \RuntimeException('Unknown Error: No error message was returned from the server - Code: ' . $response->getStatusCode() . ' URI: ' . $response->getRequest()->getUrl()); } }
protected function prepareResponse(Response $data) { if ($data->getStatusCode() != 200) { throw new \InvalidArgumentException($data->getReasonPhrase()); } $response = json_decode($data->getBody(), true); $this->validateResponse($response); return $response; }
/** * @param Response $response * * @return string */ protected static function createMessage(Response $response) { if ($response->getStatusCode() != 400) { return '[' . $response->getStatusCode() . '] A HTTP error has occurred: ' . $response->getBody(true); } $message = 'Some errors occurred:'; foreach ($response->xml()->error as $error) { $message .= PHP_EOL . '[' . (string) $error->code . '] ' . (string) $error->message; } return $message; }
/** * @return \DOMDocument */ public function getDocument() { $request = $this->client->get($this->url); $this->response = $request->send(); $this->setHtml($this->response->getBody(true)); return parent::getDocument(); }
public function cache(RequestInterface $request, Response $response) { $currentTime = time(); $ttl = $request->getParams()->get('cache.override_ttl') ?: $response->getMaxAge() ?: $this->defaultTtl; if ($cacheControl = $response->getHeader('Cache-Control')) { $stale = $cacheControl->getDirective('stale-if-error'); $ttl += $stale == true ? $ttl : $stale; } // Determine which manifest key should be used $key = $this->getCacheKey($request); $persistedRequest = $this->persistHeaders($request); $entries = array(); if ($manifest = $this->cache->fetch($key)) { // Determine which cache entries should still be in the cache $vary = $response->getVary(); foreach (unserialize($manifest) as $entry) { // Check if the entry is expired if ($entry[4] < $currentTime) { continue; } $entry[1]['vary'] = isset($entry[1]['vary']) ? $entry[1]['vary'] : ''; if ($vary != $entry[1]['vary'] || !$this->requestsMatch($vary, $entry[0], $persistedRequest)) { $entries[] = $entry; } } } // Persist the response body if needed $bodyDigest = null; if ($response->getBody() && $response->getBody()->getContentLength() > 0) { $bodyDigest = $this->getBodyKey($request->getUrl(), $response->getBody()); $this->cache->save($bodyDigest, (string) $response->getBody(), $ttl); } array_unshift($entries, array($persistedRequest, $this->persistHeaders($response), $response->getStatusCode(), $bodyDigest, $currentTime + $ttl)); $this->cache->save($key, serialize($entries)); }
/** * {@inheritdoc} */ public function getBodyAsString() { try { $result = $this->response->getBody(true); } catch (\Exception $exception) { throw GuzzleRestException::createFromException($exception); } return $result; }
private function getContent(Response $response) { if ($response->isContentType('xml')) { return $response->xml(); } elseif ($response->isContentType('audio')) { return $response->getBody()->getStream(); } else { return $response->getBody(); } }
public function getResponseBody() { $bodyObject = $this->response->getBody(); $bodyObject->rewind(); $length = $bodyObject->getContentLength(); if ($length === false || $length <= 0) { return ""; } return $bodyObject->read($length); }
/** * @param Response $response * @param string $path * @throws UnexpectedValueException * @return UnifiedRequest */ private function parseRequestFromResponse(Response $response, $path) { try { $requestInfo = Util::deserialize($response->getBody()); } catch (UnexpectedValueException $e) { throw new UnexpectedValueException(sprintf('Cannot deserialize response from "%s": "%s"', $path, $response->getBody()), null, $e); } $request = RequestFactory::getInstance()->fromMessage($requestInfo['request']); $params = $this->configureRequest($request, $requestInfo['server'], isset($requestInfo['enclosure']) ? $requestInfo['enclosure'] : []); return new UnifiedRequest($request, $params); }
/** * @param Response $response * @param string $path * @throws UnexpectedValueException * @return UnifiedRequest */ private function parseRequestFromResponse(Response $response, $path) { // @codingStandardsIgnoreStart $requestInfo = @unserialize($response->getBody()); // @codingStandardsIgnoreEnd if ($requestInfo === false) { throw new UnexpectedValueException(sprintf('Cannot deserialize response from "%s": "%s"', $path, $response->getBody())); } $request = RequestFactory::getInstance()->fromMessage($requestInfo['request']); $params = $this->configureRequest($request, $requestInfo['server']); return new UnifiedRequest($request, $params); }
/** * @param UriInterface $uri * @param Response $response */ public function __construct(UriInterface $uri, Response $response) { $this->uri = $uri; $this->response = $response; // we store the response manually, because otherwise it will not get serialized. It is a php://temp stream $this->body = $response->getBody(true); }
public function testProperlyValidatesWhenUsingContentEncoding() { $plugin = new Md5ValidatorPlugin(true); $request = RequestFactory::getInstance()->create('GET', 'http://www.test.com/'); $request->getEventDispatcher()->addSubscriber($plugin); // Content-MD5 is the MD5 hash of the canonical content after all // content-encoding has been applied. Because cURL will automatically // decompress entity bodies, we need to re-compress it to calculate. $body = EntityBody::factory('abc'); $body->compress(); $hash = $body->getContentMd5(); $body->uncompress(); $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'gzip'), 'abc'); $request->dispatch('request.complete', array('response' => $response)); $this->assertEquals('abc', $response->getBody(true)); // Try again with an unknown encoding $response = new Response(200, array('Content-MD5' => $hash, 'Content-Encoding' => 'foobar'), 'abc'); $request->dispatch('request.complete', array('response' => $response)); // Try again with compress $body->compress('bzip2.compress'); $response = new Response(200, array('Content-MD5' => $body->getContentMd5(), 'Content-Encoding' => 'compress'), 'abc'); $request->dispatch('request.complete', array('response' => $response)); // Try again with encoding and disabled content-encoding checks $request->getEventDispatcher()->removeSubscriber($plugin); $plugin = new Md5ValidatorPlugin(false); $request->getEventDispatcher()->addSubscriber($plugin); $request->dispatch('request.complete', array('response' => $response)); }
/** * {@inheritdoc} */ public function getResponseBody() { if (null === $this->response) { return array(); } $body = json_decode($this->response->getBody(true), true); return is_array($body) ? $body : array(); }
/** * Parses response into an array * * @param Response $response * @return array */ protected function parseResponseIntoArray($response) { if (strpos($response->getContentType(), 'json') === false) { parse_str($response->getBody(true), $array); return $array; } return $response->json(); }
public function visit( CommandInterface $command, Response $response, Parameter $param, &$value, $context = null ) { $value[$param->getName()] = $param->filter($response->getBody()); }
public static function getContent(Response $response) { $body = $response->getBody(true); $content = json_decode($body, true); if (JSON_ERROR_NONE !== json_last_error()) { return $body; } return $content; }
/** * Implement the concrete strategy. * * @param int $retries Number of retries of the request. * @param RequestInterface $request Request that was sent. * @param Response $response Response that was received. * Note that there may not be a response. * @param HttpException $e Exception that was encountered if any. * * @return boolean|integer|null Returns false to not retry or the number * of seconds to delay between retries. * Return true or null to defer to the next * strategy if available, and if not, return 0. */ protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { // This strategy assumes that it must exists a response object. if ($response === null) { return true; } $subject = $response->getBody(true); return preg_match($this->regex, $subject) === 1 ? true : null; }
public static function decode(Response $response) { if (strpos($response->getHeader(Header::CONTENT_TYPE), Mime::JSON) !== false) { $string = (string) $response->getBody(); $response = json_decode($string); self::checkJsonError($string); return $response; } }
/** * {@inheritdoc} */ public function parse(RequestInterface $request, Response $response) { $data = array('code' => null, 'message' => null, 'type' => $response->isClientError() ? 'client' : 'server', 'request_id' => null, 'parsed' => null); if ($body = $response->getBody(true)) { $this->parseBody(new \SimpleXMLElement($body), $data); } else { $this->parseHeaders($request, $response, $data); } return $data; }
/** * {@inheritdoc} */ public function parse(Response $response) { $data = array('code' => null, 'message' => null, 'type' => $response->isClientError() ? 'client' : 'server', 'request_id' => (string) $response->getHeader('x-amzn-RequestId'), 'parsed' => null); if (null !== ($json = json_decode($response->getBody(true), true))) { $data['parsed'] = $json; $json = array_change_key_case($json); $data = $this->doParse($data, $json); } return $data; }
/** * {@inheritdoc} */ protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { if ($response) { // Validate the checksum against our computed checksum if ($checksum = (string) $response->getHeader('x-amz-crc32')) { // Retry the request if the checksums don't match, otherwise, return null return $checksum != hexdec(Stream::getHash($response->getBody(), 'crc32b')) ? true : null; } } }
/** * {@inheritdoc} */ public function parse(Response $response) { // Build array of default error data $data = array('code' => null, 'message' => null, 'errors' => array(), 'type' => $response->isClientError() ? 'client' : 'server', 'parsed' => null); // Parse the json if (null !== ($json = json_decode($response->getBody(true), true))) { $data['parsed'] = $json; } // Do additional, protocol-specific parsing and return the result return $this->doParse($data, $response); }
/** * @param Response $response * * @return array */ public function getContent(Response $response) { $body = $response->getBody(true); $data = json_decode($body, true); if (json_last_error() === JSON_ERROR_UTF8) { $body = utf8_encode($body); $data = json_decode($body, true); } $this->generateException($data); return $data; }
public function createResponse(\Guzzle\Http\Message\Response $response) { $body = $response->getBody(true); if (preg_match('#^Response: Error\\r\\nMessage: Permission denied#', $body)) { return new Response\PermissionDeniedResponse(); } if (preg_match('#^Response: Success\\r\\nMessage: Key tree deleted successfully#', $body)) { return new Response\SuccessResponse(); } throw new Exception\UnexpectedResponseException($body); }
public function createResponse(\Guzzle\Http\Message\Response $response) { $body = $response->getBody(true); if (preg_match('#^Response: Error\\r\\nMessage: Permission denied#', $body)) { return new Response\PermissionDeniedResponse(); } if (preg_match('#^Response: Follows\\r\\nPrivilege: Command\\r\\n(.*)--END COMMAND--\\r\\n\\r\\n$#s', $body, $matches)) { return new Response\CommandResponse(trim($matches[1])); } throw new Exception\UnexpectedResponseException($body); }