/** * 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; }
/** * Execute the callable. * * @param callable $callable * @param array $arguments * * @return ResponseInterface */ private function execute($callable, array $arguments = []) { ob_start(); $level = ob_get_level(); try { $return = call_user_func_array($callable, $arguments); if ($return instanceof ResponseInterface) { $response = $return; $return = ''; } else { if (class_exists(ResponseFactory::class)) { $response = (new ResponseFactory())->createResponse(); } else { $response = new Response(); } } while (ob_get_level() >= $level) { $return = ob_get_clean() . $return; } $body = $response->getBody(); if ($return !== '' && $body->isWritable()) { $body->write($return); } return $response; } catch (Throwable $exception) { while (ob_get_level() >= $level) { ob_end_clean(); } throw $exception; } }
public static function getJsonResponse(GuzzleHttp\Psr7\Response $res) { if ($res->getStatusCode() == 200) { return json_decode($res->getBody()->getContents(), true); } return []; }
public function __construct(\GuzzleHttp\Psr7\Response $response) { $json = false; $data = $response->getBody(); $this->rawData = $data; $this->response = $response; if ($response->hasHeader('Content-Type')) { // Let's see if it is JSON $contentType = $response->getHeader('Content-Type'); if (strstr($contentType[0], 'json')) { $json = true; $data = json_decode($data); } } if (!$json) { // We can do another test here $decoded = json_decode($response->getBody()); if ($decoded) { $json = true; $data = $decoded; } } $this->setData($data); $this->setIsJson($json); }
/** * PlayerCommandsResponse constructor. * @param Response $response */ public function __construct(Response $response) { $object = json_decode($response->getBody()); foreach ($object->commands as $command) { $this->commands[] = new Command($command); } }
/** * ListingResponse constructor. * @param Response $response */ public function __construct(Response $response) { $objects = json_decode($response->getBody())->categories; foreach ($objects as $object) { $this->categories[] = new Category($object); } }
/** * Returns generator that yields new event when it's available on stream. * * @return Event[] */ public function getEvents() { $buffer = ''; $body = $this->response->getBody(); while (true) { // if server close connection - try to reconnect if ($body->eof()) { // wait retry period before reconnection sleep($this->retry / 1000); $this->connect(); // clear buffer since there is no sense in partial message $buffer = ''; } $buffer .= $body->read(1); if (preg_match(self::END_OF_MESSAGE, $buffer)) { $parts = preg_split(self::END_OF_MESSAGE, $buffer, 2); $rawMessage = $parts[0]; $remaining = $parts[1]; $buffer = $remaining; $event = Event::parse($rawMessage); // if message contains id set it to last received message id if ($event->getId()) { $this->lastId = $event->getId(); } // take into account server request for reconnection delay if ($event->getRetry()) { $this->retry = $event->getRetry(); } (yield $event); } } }
/** * PaymentsResponse constructor. * @param Response $response */ public function __construct(Response $response) { $objects = json_decode($response->getBody()); foreach ($objects as $object) { $this->payments[] = new Payment($object); } }
/** * @Then the response is JSON */ public function theResponseIsJson() { $this->responseData = json_decode($this->response->getBody()); $expectedType = 'object'; $actualObject = $this->responseData; PHPUnit::assertInternalType($expectedType, $actualObject); }
public function parse(Session $rets, Response $response) { $xml = simplexml_load_string($response->getBody()); $base = $xml->METADATA->{'METADATA-SYSTEM'}; $metadata = new \PHRETS\Models\Metadata\System(); $metadata->setSession($rets); $configuration = $rets->getConfiguration(); if ($configuration->getRetsVersion()->is1_5()) { if (isset($base->System->SystemID)) { $metadata->setSystemId((string) $base->System->SystemID); } if (isset($base->System->SystemDescription)) { $metadata->setSystemDescription((string) $base->System->SystemDescription); } } else { if (isset($base->SYSTEM->attributes()->SystemID)) { $metadata->setSystemId((string) $base->SYSTEM->attributes()->SystemID); } if (isset($base->SYSTEM->attributes()->SystemDescription)) { $metadata->setSystemDescription((string) $base->SYSTEM->attributes()->SystemDescription); } if (isset($base->SYSTEM->attributes()->TimeZoneOffset)) { $metadata->setTimezoneOffset((string) $base->SYSTEM->attributes()->TimeZoneOffset); } } if (isset($base->SYSTEM->Comments)) { $metadata->setComments((string) $base->SYSTEM->Comments); } if (isset($base->attributes()->Version)) { $metadata->setVersion((string) $xml->METADATA->{'METADATA-SYSTEM'}->attributes()->Version); } return $metadata; }
/** * Taken from Mink\BrowserKitDriver * * @param Response $response * * @return \Symfony\Component\BrowserKit\Response */ protected function createResponse(Psr7Response $response) { $body = (string) $response->getBody(); $headers = $response->getHeaders(); $contentType = null; if (isset($headers['Content-Type'])) { $contentType = reset($headers['Content-Type']); } if (!$contentType) { $contentType = 'text/html'; } if (strpos($contentType, 'charset=') === false) { if (preg_match('/\\<meta[^\\>]+charset *= *["\']?([a-zA-Z\\-0-9]+)/i', $body, $matches)) { $contentType .= ';charset=' . $matches[1]; } $headers['Content-Type'] = [$contentType]; } $status = $response->getStatusCode(); $matches = []; $matchesMeta = preg_match('/\\<meta[^\\>]+http-equiv="refresh" content="(\\d*)\\s*;?\\s*url=(.*?)"/i', $body, $matches); if (!$matchesMeta && isset($headers['Refresh'])) { // match by header preg_match('~(\\d*);?url=(.*)~', (string) reset($headers['Refresh']), $matches); } if (!empty($matches) && (empty($matches[1]) || $matches[1] < $this->refreshMaxInterval)) { $uri = new Psr7Uri($this->getAbsoluteUri($matches[2])); $currentUri = new Psr7Uri($this->getHistory()->current()->getUri()); if ($uri->withFragment('') != $currentUri->withFragment('')) { $status = 302; $headers['Location'] = (string) $uri; } } return new BrowserKitResponse($body, $status, $headers); }
public function parse(Session $rets, Response $response, $parameters) { $xml = simplexml_load_string($response->getBody()); $rs = new Results(); $rs->setSession($rets)->setResource($parameters['SearchType'])->setClass($parameters['Class']); if ($this->getRestrictedIndicator($rets, $xml, $parameters)) { $rs->setRestrictedIndicator($this->getRestrictedIndicator($rets, $xml, $parameters)); } $rs->setHeaders($this->getColumnNames($rets, $xml, $parameters)); $rets->debug(count($rs->getHeaders()) . ' column headers/fields given'); $this->parseRecords($rets, $xml, $parameters, $rs); if ($this->getTotalCount($rets, $xml, $parameters) !== null) { $rs->setTotalResultsCount($this->getTotalCount($rets, $xml, $parameters)); $rets->debug($rs->getTotalResultsCount() . ' total results found'); } $rets->debug($rs->getReturnedResultsCount() . ' results given'); if ($this->foundMaxRows($rets, $xml, $parameters)) { // MAXROWS tag found. the RETS server withheld records. // if the server supports Offset, more requests can be sent to page through results // until this tag isn't found anymore. $rs->setMaxRowsReached(); $rets->debug('Maximum rows returned in response'); } unset($xml); return $rs; }
/** * 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; } }
/** * @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); }
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; }
/** * 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(); }
/** * 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_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'); }
/** * Convert response to object * @param Response $response * @return \SimpleXMLElement */ public function prepareResponse(Response $response) { $responseBody = (string) $response->getBody(); if ($responseBody) { return simplexml_load_string($responseBody); } return null; }
/** * DuePlayersResponse constructor. * @param Response $response */ public function __construct(Response $response) { $object = json_decode($response->getBody()); $this->meta = ["execute_offline" => $object->meta->execute_offline, "next_check" => $object->meta->next_check, "more" => $object->meta->more]; foreach ($object->players as $player) { $this->players[] = new Player($player); } }
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); }
protected function verifySSOResponse(Response $response) { $response_content = json_decode($response->getBody()->getContents()); $token = $response_content->access_token; $verfiyRequest = new \GuzzleHttp\Psr7\Request('GET', self::VERIFY_URI, ['Authorization' => 'Bearer ' . $token]); $charResponse = $this->tryRequest($verfiyRequest); return $this->applyRegistrationRules(json_decode($charResponse->getBody()->getContents())); }
/** * @param Response $response * * @throws \Exception * * @return array */ protected function processResponse(Response $response) { $data = json_decode($response->getBody(), true); if ($data['code'] != 0) { throw new \Exception('Zoho Api subscription error : ' . $data['message']); } return $data; }
protected function parseResponse(Response $response) { $xml = simplexml_load_string((string) $response->getBody()); if (!empty($xml->errors)) { throw new EnomException($xml->errors->Err1[0], false); } return $xml; }
/** * 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 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; }
/** * 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; }
/** * @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); }
/** * @test */ public function correctIpReturnsDecodedInfo() { $expected = ['foo' => 'bar', 'baz' => 'foo']; $response = new Response(); $response->getBody()->write(json_encode($expected)); $response->getBody()->rewind(); $this->client->get('http://freegeoip.net/json/1.2.3.4')->willReturn($response)->shouldBeCalledTimes(1); $this->assertEquals($expected, $this->ipResolver->resolveIpLocation('1.2.3.4')); }