public function formatProvider() { $request = new Request('PUT', '/', ['x-test' => 'abc'], Stream::factory('foo')); $response = new Response(200, ['X-Baz' => 'Bar'], Stream::factory('baz')); $err = new RequestException('Test', $request, $response); return [['{request}', [$request], (string) $request], ['{response}', [$request, $response], (string) $response], ['{request} {response}', [$request, $response], $request . ' ' . $response], ['{request} {response}', [$request], $request . ' '], ['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"], ['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"], ['{res_headers}', [$request], 'NULL'], ['{req_body}', [$request], 'foo'], ['{res_body}', [$request, $response], 'baz'], ['{res_body}', [$request], 'NULL'], ['{method}', [$request], $request->getMethod()], ['{url}', [$request], $request->getUrl()], ['{resource}', [$request], $request->getResource()], ['{req_version}', [$request], $request->getProtocolVersion()], ['{res_version}', [$request, $response], $response->getProtocolVersion()], ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHost()], ['{hostname}', [$request, $response], gethostname()], ['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()], ['{code}', [$request, $response], $response->getStatusCode()], ['{code}', [$request], 'NULL'], ['{phrase}', [$request, $response], $response->getReasonPhrase()], ['{phrase}', [$request], 'NULL'], ['{error}', [$request, $response, $err], 'Test'], ['{error}', [$request], 'NULL'], ['{req_header_x-test}', [$request], 'abc'], ['{req_header_x-not}', [$request], ''], ['{res_header_X-Baz}', [$request, $response], 'Bar'], ['{res_header_x-not}', [$request, $response], ''], ['{res_header_X-Baz}', [$request], 'NULL']]; }
public function __construct(Response $response) { try { $this->details = $response->json(); $message = $this->details['error']['message']; } catch (ParseException $e) { $message = $response->getReasonPhrase(); } parent::__construct(sprintf('The request failed and returned an invalid status code ("%d") : %s', $response->getStatusCode(), $message), $response->getStatusCode()); }
/** * Making request using Guzzle * * @param string $method Type of request, either POST, GET, PUT or DELETE * @param string $endpoint The operation / task for API * @param array $data The parameter need to be passed * @param array $options The options like header, body, etc * * @return EntityBodyInterface|string * @throws \Exception */ private function sendRequest($method, $endpoint, array $data = array(), array $options = array()) { $uri = $this->buildUri($endpoint); if ($method === "GET" || $method === "PUT") { $uri = $this->buildUri($endpoint, $data); } elseif (count($data)) { $options['body'] = $data; } $this->request = $this->client->createRequest($method, $uri, $options); $this->response = $this->client->send($this->request); if ($this->response->getStatusCode() >= 400) { $bt = debug_backtrace(); $caller = $bt[2]; if (isset($caller['class']) && $caller['class'] === get_class(new StacklaModel())) { $json = (string) $this->response->getBody(); if (JsonValidator::validate($json, true)) { $content = json_decode($json, true); if (isset($content['errors'])) { $caller['object']->fromArray($content); } } } if ($this->logger) { $this->logger->addError('-> REQUEST [' . $this->request->getMethod() . ' - ' . $this->request->getUrl() . "]", array($this->request->getMethod() !== "GET" ? (string) $this->request->getBody() : "")); $this->logger->addError('<- RESPONSE [' . $this->response->getStatusCode() . ':' . $this->response->getReasonPhrase() . "]", array((string) $this->response->getBody())); } } else { if ($this->logger) { $this->logger->addInfo('-> REQUEST [' . $this->request->getMethod() . ' - ' . $this->request->getUrl() . "]", array($this->request->getMethod() !== "GET" ? (string) $this->request->getBody() : "")); $this->logger->addInfo('<- RESPONSE [' . $this->response->getStatusCode() . ':' . $this->response->getReasonPhrase() . "]", array($this->response->json())); } } $statusCode = $this->response->getStatusCode(); switch ($statusCode) { case 200: return (string) $this->response->getBody(); case 400: throw ApiException::create(sprintf("Server return %s error code. Bad request: The request could not be understood. %s", $this->response->getStatusCode(), (string) $this->response->getBody()), $statusCode, (string) $this->response->getBody()); case 401: throw ApiException::create(sprintf("Server return %s error code. Unauthorized: Authentication credentials invalid or not authorised to access resource", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody()); case 403: throw ApiException::create(sprintf("\n Server return %s error code. Rate limit exceeded: Too many requests in the current time window", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody()); case 404: throw ApiException::create(sprintf("Server return %s error code. Invalid resource: Invalid resource specified or resource not found", $this->response->getStatusCode()), $statusCode, (string) $this->response->getBody()); default: throw ApiException::create(sprintf("Server return %s error code.Server error: An error on the server prohibited a successful response; please contact support. %s", $this->response->getStatusCode(), (string) $this->response->getBody()), $statusCode, (string) $this->response->getBody()); } }
/** * Announces HTTP request to Wildfire channel * * @param GuzzleHttp\Message\Request * @param GuzzleHttp\Message\Response when dealing with error events, response may not be populated * @param float $elapsed */ public function publishRequest(Request $request, Response $response = null, $elapsed = 0) { $request_body = $request->getBody(); $request_preview = ''; if ($request_body) { $request_body->seek(0); // rewind the cursor in case a read was already done $request_preview = $request_body->read($this->_preview_length); $request_body->seek(0); // rewind the cursor, so subsequent reads are not affected } // Ensure response is populated before extracting body from it $response_body = $response ? $response->getBody() : ''; $response_preview = ''; if ($response_body) { $response_body->seek(0); // rewind the cursor, in case a read was already done $response_preview = $response_body->read($this->_preview_length); $response_body->seek(0); // rewind the cursor, so subsequent reads are not affected } $phrase = $response ? $response->getReasonPhrase() : self::ERROR_NO_RESPONSE; $table = []; $table[] = ['Key', 'Value']; $table[] = ['Phrase', $phrase]; $table[] = ['Host', $request->getHost()]; $table[] = ['Protocol', $request->getScheme()]; $table[] = ['User Agent', $request->getHeader('User-Agent')]; $table[] = ['Request', $request_preview]; $table[] = ['Response', $response_preview]; if ($response && $response->getEffectiveUrl() != $request->getUrl()) { $table[] = ['Effective URL', $response->getEffectiveUrl()]; } $elapsed = number_format($elapsed, 4); $status = $response ? $response->getStatusCode() : 0; $message = sprintf("%s <%s> (%d) %s (%f)s", $this->_remote_prefix, $request->getMethod(), $status, $request->getUrl(), $elapsed); $this->_client->table($message, $table); }
private static function convertResponse(Response $response) { $headers = array_map(function ($h) { return implode(', ', $h); }, $response->getHeaders()); return ['status' => $response->getStatusCode(), 'reason' => $response->getReasonPhrase(), 'headers' => $headers, 'body' => base64_encode((string) $response->getBody())]; }
/** * Parses both the {@link \Instaphp\Utils\Http\Response HTTP Response} and * the {@link \Instaphp\Instagram\Response Instagram Response} and scans them * for errors and throws the apropriate exception. If there's no errors, * this method returns the Instagram Response object. * * @param \GuzzelHttp\Message\Response $response * @return \Instaphp\Instagram\Response * @throws \Instaphp\Exceptions\OAuthParameterException * @throws \Instaphp\Exceptions\OAuthRateLimitException * @throws \Instaphp\Exceptions\APINotFoundError * @throws \Instaphp\Exceptions\APINotAllowedError * @throws \Instaphp\Exceptions\APIInvalidParametersError * @throws \Instaphp\Exceptions\HttpException */ protected function parseResponse(Response $response) { if ($response == NULL) { throw new \Instaphp\Exceptions\Exception("Response object is NULL"); } $igresponse = new \Instaphp\Instagram\Response($response); //-- First check if there's an API error from the Instagram response if (isset($igresponse->meta['error_type'])) { switch ($igresponse->meta['error_type']) { case 'OAuthParameterException': throw new \Instaphp\Exceptions\OAuthParameterException($igresponse->meta['error_message'], $igresponse->meta['code'], $igresponse); break; case 'OAuthRateLimitException': throw new \Instaphp\Exceptions\OAuthRateLimitException($igresponse->meta['error_message'], $igresponse->meta['code'], $igresponse); break; case 'APINotFoundError': throw new \Instaphp\Exceptions\APINotFoundError($igresponse->meta['error_message'], $igresponse->meta['code'], $igresponse); break; case 'APINotAllowedError': throw new \Instaphp\Exceptions\APINotAllowedError($igresponse->meta['error_message'], $igresponse->meta['code'], $igresponse); break; case 'APIInvalidParametersError': throw new \Instaphp\Exceptions\APIInvalidParametersError($igresponse->meta['error_message'], $igresponse->meta['code'], $igresponse); break; default: break; } } //-- Next, look at the HTTP status code for 500 errors when Instagram is //-- either down or just broken (like it seems to be a lot lately) switch ($response->getStatusCode()) { case 500: case 502: case 503: case 400: //-- 400 error slipped through? throw new \Instaphp\Exceptions\HttpException($response->getReasonPhrase(), $response->getStatusCode(), $igresponse); break; case 429: throw new \Instaphp\Exceptions\OAuthRateLimitException($igresponse->meta['error_message'], 429, $igresponse); break; default: //-- no error then? break; } return $igresponse; }
public function testProxiesSetters() { $str = Stream::factory('foo'); $response = new Response(200, ['Foo' => 'bar'], $str); $future = MockTest::createFuture(function () use($response) { return $response; }); $future->setStatusCode(202); $this->assertEquals(202, $future->getStatusCode()); $this->assertEquals(202, $response->getStatusCode()); $future->setReasonPhrase('foo'); $this->assertEquals('foo', $future->getReasonPhrase()); $this->assertEquals('foo', $response->getReasonPhrase()); }
public function testStatusAndReasonAreMutable() { $response = new Response(200); $response->setStatusCode(201); $this->assertEquals(201, $response->getStatusCode()); $response->setReasonPhrase('Foo'); $this->assertEquals('Foo', $response->getReasonPhrase()); }
public function testCanProvideCustomStatusCodeAndReasonPhrase() { $response = new Response(999, [], null, ['reason_phrase' => 'hi!']); $this->assertEquals(999, $response->getStatusCode()); $this->assertEquals('hi!', $response->getReasonPhrase()); }