/** * Determine an exception code from the given response, exception data and * JSON body. * * @param Response $response * @param array $data * @param array $json * * @return string|null */ private function determineCode(Response $response, array $data, array $json) { if (409 === $response->getStatusCode()) { return 'DocumentAlreadyExists'; } return $this->determineCodeFromErrors($data['errors']); }
/** * Parses additional exception information from the response headers * * @param RequestInterface $request Request that was issued * @param Response $response The response from the request * @param array $data The current set of exception data */ protected function parseHeaders(RequestInterface $request, Response $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})"; } }
/** * Factory method to create a new Oauth exception. * * @param RequestInterface $request * @param Response $response * * @return OauthException */ public static function factory(RequestInterface $request, Response $response) { $message = 'Client error response' . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl())); $e = new static($message); $e->setResponse($response); $e->setRequest($request); return $e; }
/** * @param $statusCode * @param $url * @param RequestInterface $request * @param Response $response */ public function validate($statusCode, $url, RequestInterface $request, Response $response) { if ($response->getStatusCode() === $statusCode) { return; } $message = $url . ' gives a non-200 status code response.'; $this->logger->warning($message, array('request' => (string) $request, 'response' => (string) $response)); throw new RuntimeException($message . ' See logs.' . $response->serialize()); }
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; }
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); }
public function testRetrieving() { $response = new Response(200); $response->setBody(json_encode(array('status' => 1, 'complete' => 1, 'list' => array(123 => array('item_id' => 123, 'resolved_id' => 123, 'given_url' => 'http://acairns.co.uk', 'given_title' => 'Andrew Cairns', 'favorite' => 0, 'status' => 0, 'time_added' => time(), 'time_updated' => time(), 'time_read' => 0, 'time_favorited' => 0, 'sort_id' => 0, 'resolved_title' => 'Andrew Cairns', 'resolved_url' => 'http://acairns.co.uk', 'excerpt' => 'Some excerpt about something', 'is_article' => 0, 'is_index' => 0, 'has_video' => 0, 'has_image' => 0, 'word_count' => 123))))); $this->setPocketResponse($response); $response = $this->pockpack->retrieve(); $this->assertEquals(1, $response->status); $this->assertEquals(1, $response->complete); $this->assertNotEmpty($response->list); $this->assertNotEmpty($response->list->{123}); $item = $response->list->{123}; $this->assertEquals(123, $item->item_id); $this->assertEquals(123, $item->resolved_id); $this->assertEquals('Andrew Cairns', $item->given_title); $this->assertEquals('Andrew Cairns', $item->resolved_title); $this->assertEquals('http://acairns.co.uk', $item->given_url); $this->assertEquals('http://acairns.co.uk', $item->resolved_url); $this->assertEquals('Some excerpt about something', $item->excerpt); $this->assertEquals(0, $item->is_article); $this->assertEquals(0, $item->favorite); $this->assertEquals(0, $item->status); $this->assertEquals(0, $item->time_read); $this->assertEquals(0, $item->time_favorited); $this->assertEquals(0, $item->sort_id); $this->assertEquals(0, $item->is_index); $this->assertEquals(0, $item->has_video); $this->assertEquals(0, $item->has_image); $this->assertEquals(123, $item->word_count); }
/** * {@inheritdoc} */ protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { if ($response && $response->isClientError()) { $parts = $this->exceptionParser->parse($request, $response); return isset(self::$throttlingExceptions[$parts['code']]) ? true : null; } }
/** * Get the response of the query. * Will be the json decoded data if success, else the error message. * * @return array|string */ public function getResponse() { if (false === $this->response->isSuccessful()) { return $this->response->getMessage(); } return $this->response->json(); }
public static function getApiLimit(Response $response) { $remainingCalls = $response->getHeader('X-RateLimit-Remaining'); if (null !== $remainingCalls && 1 > $remainingCalls) { throw new ApiLimitExceedException($remainingCalls); } }
/** * Receive a response header from curl * * @param resource $curl Curl handle * @param string $header Received header * * @return int */ public function receiveResponseHeader($curl, $header) { static $normalize = array("\r", "\n"); $length = strlen($header); $header = str_replace($normalize, '', $header); if (strpos($header, 'HTTP/') === 0) { $startLine = explode(' ', $header, 3); $code = $startLine[1]; $status = isset($startLine[2]) ? $startLine[2] : ''; // Only download the body of the response to the specified response // body when a successful response is received. if ($code >= 200 && $code < 300) { $body = $this->request->getResponseBody(); } else { $body = EntityBody::factory(); } $response = new Response($code, null, $body); $response->setStatus($code, $status); $this->request->startResponse($response); $this->request->dispatch('request.receive.status_line', array('request' => $this, 'line' => $header, 'status_code' => $code, 'reason_phrase' => $status)); } elseif ($pos = strpos($header, ':')) { $this->request->getResponse()->addHeader(trim(substr($header, 0, $pos)), trim(substr($header, $pos + 1))); } return $length; }
/** * {@inheritdoc} */ protected function getDelay($retries, RequestInterface $request, Response $response = null, HttpException $e = null) { if ($response && $response->isClientError()) { $parts = $this->parser->parse($response); return $parts['code'] == 'ProvisionedThroughputExceededException' || $parts['code'] == 'ThrottlingException' ? true : null; } }
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)); }
public function dispatch($request, $connection) { $response = new Response(200); $path = $request->getPath(); if ($this->match($path)) { echo "Found match for path: {$path}" . PHP_EOL; if (is_callable($this->routes[$path])) { call_user_func_array($this->routes[$path], array($request, $response, $connection)); } else { throw new \Exception('Invalid route definition.'); } return; } if (is_null($this->fileHandler)) { throw new \Exception('No file handler configured'); } if (false === $this->fileHandler->canHandleRequest($request)) { $response->setStatus(404); $response->setBody('File not found'); $connection->send($response); $connection->close(); return; } $this->fileHandler->handleRequest($request, $response, $connection); }
public function debug() { $r = new Response(); var_dump($r->getReasonPhrase()); $req = new Request(); $req->getPath(); }
/** * @param Guzzle\Http\Message\RequestInterface * @return Guzzle\Http\Message\Response */ public function handshake(RequestInterface $request) { $body = $this->sign($request->getHeader('Sec-WebSocket-Key1', true), $request->getHeader('Sec-WebSocket-Key2', true), (string) $request->getBody()); $headers = array('Upgrade' => 'WebSocket', 'Connection' => 'Upgrade', 'Sec-WebSocket-Origin' => $request->getHeader('Origin', true), 'Sec-WebSocket-Location' => 'ws://' . $request->getHeader('Host', true) . $request->getPath()); $response = new Response(101, $headers, $body); $response->setStatus(101, 'WebSocket Protocol Handshake'); return $response; }
/** * Tests getRateReset method */ public function testRateReset() { $response = new Response(200); $response->setHeader('X-Rate-Reset', '100'); $client = new GenderizeClient(); $client->setLastResponse($response); $this->assertEquals('100', $client->getRateReset()); }
private function getRequestTime(GuzzleResponse $response) { $time = $response->getInfo('total_time'); if (null === $time) { $time = 0; } return (int) ($time * 1000); }
public function onOpen(ConnectionInterface $conn, RequestInterface $request = null) { $this->log('open', $conn); $response = new Response(200, array('Content-type' => 'text/javascript', 'Content-Length' => $this->getFilesize($request->getPath()))); $response->setBody($this->getContent($request->getPath())); $conn->send((string) $response); $conn->close(); }
/** * @param \Guzzle\Http\Message\Response $response * @param array $extra */ public function logResponse($response, $extra = array()) { !array_key_exists("serialization_time", $extra) && ($extra["serialization_time"] = "-"); !array_key_exists("deserialization_time", $extra) && ($extra["deserialization_time"] = "-"); !array_key_exists("search_time", $extra) && ($extra["search_time"] = "-"); !array_key_exists("method", $extra) && ($extra["method"] = "-"); $this->logger->debug(self::getProcessId() . ' ' . $extra["method"] . ' ' . $response->getInfo("url") . ' ' . $response->getInfo("total_time") . ' ' . $extra["deserialization_time"] . ' ' . $extra["serialization_time"] . ' ' . $extra["search_time"]); }
/** * 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(); }
/** * Get response as an array. * * @return array */ private function getResponseAsArray() { $this->result = $this->response->json(); if ($this->responseHasErrors()) { return false; } return $this->result; }
/** * 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; }
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; } }
/** * Seconds remaining until a new time window opens * * @return null */ public function getRateReset() { if (!$this->lastResponse) { return null; } /** @var Header $limit */ $limit = $this->lastResponse->getHeader('X-Rate-Reset'); return $limit ? $limit->normalize() : null; }
public function testReceivingAccessTokenAndUsername() { $response = new Response(200); $response->setBody(json_encode(array('access_token' => 'fake_access_token', 'username' => 'acairns'))); $this->setPocketResponse($response); $data = $this->pockpack_auth->receiveTokenAndUsername('fake_consumer_key', 'fake_access_token'); $this->assertEquals('fake_access_token', $data['access_token']); $this->assertEquals('acairns', $data['username']); }
/** * 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 getContent(Response $response) { $body = $response->getBody(true); $content = json_decode($body, true); if (json_last_error() !== JSON_ERROR_NONE) { return $body; } return $content; }
/** * @test * @expectedException PHPSC\PagSeguro\Client\PagSeguroException */ public function handleErrorShouldRaiseExceptionWhenHostIsFromPagSeguro() { $client = new Client($this->httpClient); $event = new Event(['request' => $this->request, 'response' => $this->response]); $this->request->expects($this->any())->method('getHost')->willReturn(Production::WS_HOST); $this->response->expects($this->any())->method('getStatusCode')->willReturn(401); $this->response->expects($this->any())->method('getBody')->willReturn('Unauthorized'); $client->handleError($event); }
public function visit( CommandInterface $command, Response $response, Parameter $param, &$value, $context = null ) { $value[$param->getName()] = $param->filter($response->getBody()); }