/** * 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); } } }
/** * @Then the response is JSON */ public function theResponseIsJson() { $this->responseData = json_decode($this->response->getBody()); $expectedType = 'object'; $actualObject = $this->responseData; PHPUnit::assertInternalType($expectedType, $actualObject); }
/** * Initialize * * @param HttpResponse $response */ public function __construct(HttpResponse $response) { $this->response = $response; if ($this->isSuccessful()) { $this->messages = new MessageGroup(json_decode($this->response->getBody(), true)); } }
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); }
/** * Get the response body contents. * * @return string * The original body contents. */ public function contents() { $body = $this->response->getBody(); if (!$body) { return null; } return $body->getContents(); }
/** * @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')); }
/** * @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()); }
/** * Response constructor * * @param HttpResponse $httpResponse * @return self */ public function __construct(HttpResponse $httpResponse) { $header = $httpResponse->getHeader('Content-Type'); if (!is_array($header) && stripos($header, 'text/javascript') !== false) { $this->_response = $this->processJson($httpResponse->getBody()); } else { $this->_response = $this->processXml($httpResponse->getBody()); } }
private function getResponse(HttpResponse $httpResponse) { $response = new Response(); if ($httpResponse->getBody()) { $resp = (string) $httpResponse->getBody(); $decoded = json_decode($resp, true); $response->setBody($decoded); } return $response; }
protected function parse(Response $response, $type = 'json') { switch ($type) { case 'json': return json_decode((string) $response->getBody(), true); case 'xml': return simplexml_load_file((string) $response->getBody()); default: throw new Exception("Invalid repsonse type"); } }
/** * Create an array of the response object * * @param Response $response * @return array */ private function buildResponse(Response $response) { $this->response['body'] = $response->getBody()->getContents(); $this->response['size'] = $response->getBody()->getSize(); $this->response['status_code'] = $response->getStatusCode(); //Build the response headers $headers = $response->getHeaders(); foreach ($headers as $name => $value) { $this->response['headers'][$name] = $value; } return $this->response; }
/** * @param Response $response * @return array Parsed JSON result * @throws JotihuntApiException */ public function parseResponse(Response $response) { try { $resultArray = json_decode($response->getBody()->getContents(), true); if (!is_array($resultArray)) { throw new JotihuntApiException('Jotihunt error: Unexpected result: ' . $response->getBody()->getContents()); } if (array_key_exists('error', $resultArray)) { throw new JotihuntApiException('Jotihunt error: ' . $resultArray['error']); } return $resultArray; } catch (\RuntimeException $e) { throw new JotihuntApiException('Jotihunt error: ' . $e->getMessage()); } }
/** * Returns response in XML format * @return \SimpleXMLElement * @throws Exception */ public function toXML() { // Allow Internal Error Processing libxml_use_internal_errors(true); // Load Response to XML $xml = simplexml_load_string($this->response->getBody()->getContents()); // Check for Errors $xml_error = libxml_get_last_error(); if ($xml_error !== false) { // Clear errors for next request libxml_clear_errors(); throw new Exception($xml_error->message, $xml_error->code); } return $xml; }
public static function getJsonResponse(GuzzleHttp\Psr7\Response $res) { if ($res->getStatusCode() == 200) { return json_decode($res->getBody()->getContents(), true); } return []; }
/** * 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); } }
/** * 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 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; }
/** * 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; }
/** * PaymentsResponse constructor. * @param Response $response */ public function __construct(Response $response) { $objects = json_decode($response->getBody()); foreach ($objects as $object) { $this->payments[] = new Payment($object); } }
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; }
/** * 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); } }
/** * 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); }
/** * Returns last SOAP response. * * @return mix The last SOAP response, as an XML string. */ public function lastResponse() { if ($this->response instanceof Response) { return $this->response->getBody(); } return null; }
/** * Get the response body as a json string. * * @return string * @throws \Hedii\ZoteroApi\Exceptions\BadMethodCallException */ public function getJson() { if (!$this->response) { throw new BadMethodCallException('Cannot call getJson() on null'); } return (string) $this->response->getBody(); }
/** * @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); }
/** * 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); } }
/** * @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; }
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); }
/** * 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(); }
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'); }