static function retryDecider($retries, Request $request, Response $response = null, RequestException $exception = null) { // Limit the number of retries to 5 if ($retries >= 5) { return false; } // Retry connection exceptions if ($exception instanceof ConnectException) { return true; } if ($response) { // Retry on server errors if ($response->getStatusCode() >= 500) { return true; } // Retry on rate limits if ($response->getStatusCode() == 429) { $retryDelay = $response->getHeaderLine('Retry-After'); if (strlen($retryDelay)) { printf(" retry delay: %d secs\n", (int) $retryDelay); sleep((int) $retryDelay); return true; } } } return false; }
/** * @param GuzzleException $guzzleException */ public function setErrorResponse(GuzzleException $guzzleException) { $this->exception = $guzzleException; if ($guzzleException instanceof RequestException) { $this->response = $guzzleException->getResponse(); $this->status = $this->response->getStatusCode(); } $this->timeResponse = microtime(true); }
/** * Check response content is successful or not * * @return boolean */ public function isSuccessful() { $statusCode = $this->response->getStatusCode(); if ($statusCode == self::STATUS_CONSUME_OK || $statusCode == self::STATUS_DELETE_OK || $statusCode == self::STATUS_PRODUCE_OK) { return true; } $this->errorMessage = self::$status[$statusCode]; return false; }
/** * @return ErrorResponse|SuccessResponse */ public function deduce() { /* @var array $response */ $response = (array) json_decode($this->response->getBody()->getContents()); if (array_key_exists('type', $response) && $response['type'] === 'error') { return new ErrorResponse($this->response->getStatusCode(), $this->response->getHeaders(), $this->response->getBody()); } return new SuccessResponse($this->response->getStatusCode(), $this->response->getHeaders(), $this->response->getBody()); }
/** * Connect to server. */ private function connect() { $headers = []; if ($this->lastId) { $headers['Last-Event-ID'] = $this->lastId; } $this->response = $this->client->request('GET', $this->url, ['stream' => true, 'headers' => $headers]); if ($this->response->getStatusCode() == 204) { throw new RuntimeException('Server forbid connection retry by responding 204 status code.'); } }
/** * Check if the response given by fcm is parsable * * @param GuzzleResponse $response * * @throws InvalidRequestException * @throws ServerResponseException * @throws UnauthorizedRequestException */ private function isJsonResponse(GuzzleResponse $response) { if ($response->getStatusCode() == 200) { return; } if ($response->getStatusCode() == 400) { throw new InvalidRequestException($response); } if ($response->getStatusCode() == 401) { throw new UnauthorizedRequestException($response); } throw new ServerResponseException($response); }
/** * Search book by tags like title, author, publisher etc. * * @param array $query * * @return mixed */ public function search(array $query) { $processed = $this->transformQueryParameters($query, $this->queryTransformationMap()); $query = implode(' ', $processed[1]); foreach ($processed[0] as $key => $value) { $query .= ' ' . $key . $value; } $query = $this->prepareQuery($query); $this->response = $this->client->get($query); if ($this->response->getStatusCode() != 200) { $this->response = null; } return $this; }
public static function make(Response $response) { $code = $response->getStatusCode(); $body = json_decode($response->getBody(), true); if ($response->getStatusCode() == 200) { if (!is_array($body) && is_string($body)) { $body = ['message' => $body]; } } else { if (!$body['message']) { $body = ['message' => $response->getReasonPhrase(), 'details' => $body]; } } return new RuleResponse($code, $body); }
/** * @param Response $response * @return AuthorizationResponse */ public function create(Response $response) { if ($response->getStatusCode() === 200) { return new AuthorizationResponse($response, AuthorizationResponse::AUTHORISED); } return new AuthorizationResponse($response, AuthorizationResponse::UNAUTHORISED); }
/** * Set last logs * * @param Response|ResponseInterface $response */ public function setLastLogs($response) { $this->statusCode = $response->getStatusCode(); $content = json_decode($response->getBody()->getContents()); $this->message = isset($content->message) ? $content->message : null; $this->errors = isset($content->errors) ? $content->errors : null; }
public static function getJsonResponse(GuzzleHttp\Psr7\Response $res) { if ($res->getStatusCode() == 200) { return json_decode($res->getBody()->getContents(), true); } return []; }
protected function updateGame(\Morpheus\SteamGame $game, \GuzzleHttp\Psr7\Response $response) { $body = json_decode($response->getBody()); $result = reset($body); if ($response->getStatusCode() == 200 && isset($result->success) && $result->success === true) { $game->steam_store_data = json_encode($result->data); } elseif ($response->getStatusCode() !== 200) { \Log::warning('Steam Store API call failed', ['status code' => $response->getStatusCode(), 'game' => $game]); } elseif (!isset($result->success)) { \Log::warning('Unexpected Steam Store API response', ['body' => $result, 'game' => $game]); } else { \Log::notice('Game not found in Steam Store database', ['game' => $game]); } $game->steam_store_updated = date('Y-m-d H:i:s'); $game->save(); }
/** * Send poll request from task response * * If response is not from async task, return null * * @param Elasticsearch\Job $job * @param \GuzzleHttp\Psr7\Response $response * @param Encryptor $encryptor * @param int $retriesCount * @return \GuzzleHttp\Psr7\Response|null */ public function sendOrchestratorPollRequest(Elasticsearch\Job $job, \GuzzleHttp\Psr7\Response $response, Encryptor $encryptor, $retriesCount) { if ($response->getStatusCode() != 202) { return null; } try { $data = ResponseDecoder::decode($response); if (!is_array($data)) { throw new \Exception('Not json reponse'); } if (empty($data['url'])) { return null; } } catch (\Exception $e) { //@TODO log error with debug priority return null; } $timeout = 2; try { return $this->get($data['url'], array('config' => array('curl' => array(CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_0)), 'headers' => array('X-StorageApi-Token' => $encryptor->decrypt($job->getToken()), 'X-KBC-RunId' => $job->getRunId(), 'X-User-Agent', KeboolaOrchestratorBundle::SYRUP_COMPONENT_NAME . " - JobExecutor", 'X-Orchestrator-Poll', (int) $retriesCount), 'timeout' => 60 * $timeout)); } catch (RequestException $e) { $handlerContext = $e->getHandlerContext(); if (is_array($handlerContext)) { if (array_key_exists('errno', $handlerContext)) { if ($handlerContext['errno'] == CURLE_OPERATION_TIMEOUTED) { $this->logger->debug('curl.debug', array('handlerContext' => $e->getHandlerContext())); throw new Exception\CurlException(sprintf('Task polling timeout after %d minutes', $timeout), $e->getRequest(), $e->getResponse(), $e); } } } throw $e; } }
/** * @throws HttpException */ protected function handleError() { $body = (string) $this->response->getBody(); $code = (int) $this->response->getStatusCode(); $content = json_decode($body); throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code); }
/** * Indicates if there should be a retry or not. * * @param integer $retryCount The retry count. * @param \GuzzleHttp\Psr7\Response $response The HTTP response object. * * @return boolean */ public function shouldRetry($retryCount, $response) { if ($retryCount >= $this->_maximumAttempts || array_search($response->getStatusCode(), $this->_retryableStatusCodes) || is_null($response)) { return false; } else { return true; } }
function it_should_encode_a_responses_collection() { $response = new Response(200); $responses = array($response); $format = ['code' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'body' => (string) $response->getBody()]; $formatted = json_encode(array($format), JSON_PRETTY_PRINT); $this->encodeResponsesCollection($responses)->shouldEqual($formatted); }
function it_should_throw_exception_if_response_is_not_correct_for_finishing_the_verification_process(Response $response, StreamInterface $stream) { $response->getStatusCode()->willReturn(500); $response->getBody()->willReturn($stream); $stream->getContents()->willReturn('Error'); $this->client->sendRequest(Argument::type(Request::class))->shouldBeCalledTimes(1)->willReturn($response); $this->shouldThrow(PactException::class)->during('finishProviderVerificationProcess'); }
/** * Set Values to the class members * * @param Response $response */ private function setParams(Response $response) { $this->protocol = $response->getProtocolVersion(); $this->statusCode = (int) $response->getStatusCode(); $this->headers = $response->getHeaders(); $this->body = json_decode($response->getBody()->getContents()); $this->extractBodyParts(); }
public function testCanCreateNewResponseWithStatusAndReason() { $r = new Response(200); $r2 = $r->withStatus(201, 'Foo'); $this->assertEquals(200, $r->getStatusCode()); $this->assertEquals('OK', $r->getReasonPhrase()); $this->assertEquals(201, $r2->getStatusCode()); $this->assertEquals('Foo', $r2->getReasonPhrase()); }
/** * @throws ApiException */ protected function handleError($getCode = false) { $code = (int) $this->response->getStatusCode(); if ($getCode) { return $code; } $content = (string) $this->response->getBody(); $this->reportError($code, $content); }
/** * Guess Magento version from downloader body * * @param Response $response * * @return string|boolean */ public function getMagentoVersion(Response $response) { if ($response->getStatusCode() == 200) { if (preg_match('/([0-9]{1,2}\\.[0-9]{1,2}\\.[0-9]{1,2}(\\.[0-9]{1,2})?)/', $response->getBody(), $match)) { return $match[1]; } } return false; }
/** * Attempt to create local response type from guzzle response * * @param GuzzleResponse $guzzleResponse * * @return Response */ protected static function createLocalResponse(GuzzleResponse $guzzleResponse) { $response = new Response($guzzleResponse->getBody(), $guzzleResponse->getStatusCode()); $headers = $guzzleResponse->getHeaders(); array_walk($headers, function ($values, $name) use($response) { $response->header($name, implode(', ', $values), true); }); return $response; }
public function testStatusCanBeNumericString() { $r = new Response('404'); $r2 = $r->withStatus('201'); $this->assertSame(404, $r->getStatusCode()); $this->assertSame('Not Found', $r->getReasonPhrase()); $this->assertSame(201, $r2->getStatusCode()); $this->assertSame('Created', $r2->getReasonPhrase()); }
protected function getSerializedResponse(Response $response) { $cached = new \SplFixedArray(5); $cached[0] = $response->getStatusCode(); $cached[1] = $response->getHeaders(); $cached[2] = $response->getBody()->__toString(); $cached[3] = $response->getProtocolVersion(); $cached[4] = $response->getReasonPhrase(); return serialize($cached); }
/** * @param $expected * @param string $message * @return $this */ public function assertStatus($expected, $message = null) { $actual = $this->response->getStatusCode(); $message = $message ?: "Failed asserting that [{$actual}] is [{$expected}]"; if ($this->getErrors()) { $message .= '. ' . json_encode($this->getErrors(), JSON_PRETTY_PRINT); } PHPUnit_Framework_Assert::assertEquals($expected, $actual, $message); return $this; }
/** * @param Response $response */ function out(Response $response) { header(sprintf('%s %s %s', $response->getProtocolVersion(), $response->getStatusCode(), $response->getReasonPhrase())); foreach ($response->getHeaders() as $name => $values) { foreach ($values as $value) { header(sprintf('%s: %s', $name, $value), false); } } stream_copy_to_stream(\GuzzleHttp\Psr7\StreamWrapper::getResource($response->getBody()), fopen('php://output', 'w')); }
/** * ServerResponseException constructor. * * @param GuzzleResponse $response */ public function __construct(GuzzleResponse $response) { $code = $response->getStatusCode(); $responseHeader = $response->getHeaders(); $responseBody = $response->getBody()->getContents(); if (array_keys($responseHeader, "Retry-After")) { $this->retryAfter = $responseHeader["Retry-After"]; } parent::__construct($responseBody, $code); }
/** * @param Response $response * * @throws \LogicException */ protected static function createException(Response $response) { $content = json_decode($response->getBody()->getContents(), true); if (is_array($content) && array_key_exists('errors', $content)) { $message = json_encode($content['errors'], JSON_UNESCAPED_UNICODE); } else { $message = $response->getReasonPhrase(); } throw new \LogicException($message, $response->getStatusCode()); }
/** * Prints last response body. * * @Then print response */ public function printResponse() { if (!isset($this->requestData['method'])) { $this->requestData['method'] = 'method-not-set'; } if (!isset($this->requestData['url'])) { $this->requestData['url'] = 'url-not-set'; } echo sprintf("%s %s => %d:\n%s", $this->requestData['method'], $this->requestData['url'], $this->response->getStatusCode(), $this->response->getBody()); }
/** * Guess Magento version from copyright in public file * * @param Response $response * @param string|boolean $edition * * @return string|boolean */ public function getVersion(Response $response, $edition) { if ($response->getStatusCode() == 200 && $edition != false) { preg_match('/@copyright.*/', $response->getBody(), $match); if (isset($match[0]) && preg_match('/[0-9-]{4,}/', $match[0], $match) && isset($match[0])) { return $this->getMagentoVersionByYear($match[0], $edition); } } return false; }