/** * get the response phrase * @return array */ public function getFailedReason() { if ($this->isFailed()) { $error = $this->response->json(); return array_key_exists('error', $error) ? $error['error'] : array(); } return null; }
/** * @return ErrorResponse|SuccessResponse */ public function deduce() { /* @var array $response */ $response = (array) $this->response->json(); 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()); }
/** * @return array */ private function getDecodedJson() { if (!$this->decoded) { try { $this->decoded = $this->response->json(); } catch (ParseException $e) { return array(); } } return $this->decoded; }
/** * Check the return of a request response * * @param Response $response * @return false if error, decoded response if valid status * @author Niko */ private function checkResponse(Response $response) { if ($response->getStatusCode() != 200) { $res = $response->json(); var_dump($response->getStatusCode()); if (isset($res['Error'])) { $this->log($response->getStatusCode(), $res['Error']); } return false; } return $response->json(); }
/** * Parse body of response * * @return Crawler | array | string */ private function parseBody() { $type = $this->getType(); $body = (string) $this->resource->getBody(); if (!$body) { return ''; } if (in_array($type, ['text/html', 'text/xml'])) { return new Crawler($body); } if ($type === 'application/json') { return $this->resource->json(); } return $body; }
private static function wrapResponse(Response $response) { $payload = $response->json(["object" => true]); // strip the envelope if (isset($payload->data) && isset($payload->meta)) { return new static($payload->data); } return new static($payload); }
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()); }
function it_maps_declined_response_402_to_payment_result_object(ClientException $exception, Response $response, ResultObjectMapperInterface $resultMapper, MethodInterface $method) { $result = ['error' => 'Error string']; $resultObject = new Payment(); $response->getStatusCode()->willReturn(402); $response->json()->willReturn($result); $method->createResultObject()->willReturn($resultObject); $exception->getResponse()->willReturn($response); $resultMapper->map($result, $resultObject)->shouldBeCalled()->willReturn($resultObject); $this->get($exception, $method)->getResult()->shouldReturn($resultObject); }
public function testCanReadFindAddressResponse() { $json = file_get_contents(__DIR__ . '\\GetAddressIO.json'); $response = new Response(200, [], Stream::factory($json)); $json = $response->json(); $address = new Address(); $address->setLatitude($json['Latitude'])->setLongitude($json['Longitude'])->setStreet($json['Addresses'][0]); $this->assertEquals($address->getLatitude(), '51.503038'); $this->assertEquals($address->getLongitude(), '-0.128371'); $this->assertEquals($address->getStreet(), 'Prime Minister & First Lord of the Treasury, 10 Downing Street, , , , London, Greater London'); }
/** * Parse the returned response. * * @param \GuzzleHttp\Message\Response $response * @return array * * @throws \RuntimeException */ protected function parseResponse(Response $response) { $contentType = explode(';', $response->getHeader('content-type'))[0]; switch ($contentType) { case 'text/javascript': case 'application/json': return $response->json(); case 'application/xml': return $response->xml(); } throw new \RuntimeException("Unsupported returned content-type [{$contentType}]"); }
/** * @param \GuzzleHttp\Message\Response $response * @return Error */ protected function handleResponse($response) { $contentType = $response->getHeader('content-type'); if (stripos($contentType, 'application/json') === false) { return $response; } $json = $response->json(); if ($response->getStatusCode() >= 400) { // oops an error with the response return new Error($response->getStatusCode(), $json['code'], $json['message']); } return $json; }
public function testCanReadFindAddressResponse() { $json = file_get_contents(__DIR__ . '\\PostcodeData.json'); $response = new Response(200, [], Stream::factory($json)); $json = $response->json(); $address = new Address(); $address->setStreet($json['details'][0]['street'])->setTown($json['details'][0]['city'])->setMunicipality($json['details'][0]['municipality'])->setProvince($json['details'][0]['province'])->setLatitude($json['details'][0]['lat'])->setLongitude($json['details'][0]['lon']); $this->assertEquals($address->getStreet(), 'Evert van de Beekstraat'); $this->assertEquals($address->getTown(), 'Schiphol'); $this->assertEquals($address->getMunicipality(), 'Haarlemmermeer'); $this->assertEquals($address->getProvince(), 'Noord-Holland'); $this->assertEquals($address->getLatitude(), '52.3035437835548'); $this->assertEquals($address->getLongitude(), '4.7474064734608'); }
/** * @param Response $response * @return array|mixed * @throws JsonApiResponseException */ public function handleResponse($response) { $contentType = $response->getHeader('content-type'); // if its not json, then just return the response and handle it in your own object. if (stripos($contentType, 'application/json') === false) { return $response; } $json = $response->json(); // adobe says hey this didn't work! if ($response->getStatusCode() >= 400) { // oops an error with the response, from Adobe complaining about something in your code. throw new JsonApiResponseException($response->getStatusCode(), $json['message'], $json['code']); } return $json; }
/** * 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()); } }
/** * {@inheritdoc} */ public function parseBody(Response $response, $format = '') { $output = NULL; if (empty($format)) { $format = isset($this->defaults['form']) ? $this->defaults['form'] : NULL; } if ($format == $this::FORMAT_JSON || $format == $this::FORMAT_CJSON) { $output = $response->json(); } if ($format == $this::FORMAT_ATOM || $format == $this::FORMAT_RSS) { $output = $this->xmlToArray($response->xml()); } if ($output['isException']) { throw new MpxException(sprintf('Exception returned: %s', print_r($output, TRUE)), $output['responseCode']); } if (isset($output)) { return $output; } throw new MpxException('Custom formats are not supported.'); }
/** * @param Response $httpResponse * @return array * @throws \RuntimeException */ protected function extractDataFromResponse($httpResponse, GiropayResponse $giropayResponse) { $response = new PaymentResponseDTO(PaymentType::$BANK_ACCOUNT, GiropayPaymentGatewayType::$GIROPAY); $response->rawResponse($httpResponse->getBody(true)); try { $data = $httpResponse->json(); if (!array_key_exists("rc", $data) || !is_numeric($data["rc"])) { throw new \RuntimeException("Missing required response parameter rc"); } if (!array_key_exists($data["rc"], GiropayResultType::$TYPES)) { throw new \RuntimeException("Unknown Result Code: " . $data["rc"]); } $result = GiropayResultType::$TYPES[$data["rc"]]; $giropayResponse->setResult($result); if (GiropayResultType::$OK->equals($result) && !$this->verifyHttpResponseHash($httpResponse)) { throw new \RuntimeException("The validation hash was invalid"); } } catch (Guzzle\Common\Exception\RuntimeException $e) { throw new \RuntimeException("Json payload could not be parsed", 0, $e); } return $data; }
/** * Convert Guzzle response to collections * * @param Response $response * @return Collection */ private function getCollection(Response $response) { $companies = $response->json()['companies']; $collections = []; foreach ($companies as $company) { $collection = new Collection(); $collection->vat = $company['vat']; $collection->name = $company['name']; $collection->address = $company['address']; $collection->zipcode = $company['zipcode']; $collection->phone = $company['phone']; $collection->email = $company['email']; $collection->startdate = $company['startdate']; $collection->enddate = $company['enddate']; $collection->employees = $company['employees']; $collection->industrycode = $company['industrycode']; $collection->companydesc = $company['companydesc']; $collection->creditbankrupt = $company['creditbankrupt']; $collections[] = $collection; } return new Collection($collections); }
private function detectType(\GuzzleHttp\Message\Response $response) { switch ($response->getHeader('content-type')) { case 'application/json': return $response->json(); break; case 'application/xml': case 'text/xml': return json_decode(json_encode($response->xml()), true); break; default: return $response->getBody(); } }
protected function checkErrors(Response $response, $responseCode = 200) { $json = $response->json(); $allowedPorts = array(); $allowedPorts[] = $responseCode; if ($responseCode = 200) { $allowedPorts[] = 201; } if (!in_array($response->getStatusCode(), $allowedPorts)) { throw new NitrapiHttpErrorException("Invalid http status code " . $response->getStatusCode()); } if (isset($json['status']) && $json['status'] == "error") { throw new NitrapiHttpErrorException("Got Error from API " . $json["message"]); } }
/** * Constructor * * @param GuzzleResponse $response */ public function __construct(GuzzleResponse $response) { $headers = $response->getHeaders(); //-- this is a hack on my part and I'm terribly sorry it exists //-- but deal with it. foreach ($headers as $header => $value) { $this->headers[$header] = implode(',', array_values((array) $value)); } $this->url = $response->getEffectiveUrl(); $url_parts = explode('?', $this->url); if (isset($url_parts[1])) { $query = explode('&', $url_parts[1]); foreach ($query as $params) { $kv = explode('=', $params); $this->params[$kv[0]] = isset($kv[1]) ? $kv[1] : ''; } } // $this->params = $response->request_parameters; // $this->method = $response->request_method; $this->json = $response->json(); // $json = json_decode($this->json, TRUE); $this->data = isset($this->json['data']) ? $this->json['data'] : []; $this->meta = isset($this->json['meta']) ? $this->json['meta'] : []; if (isset($this->json['code']) && $this->json['code'] !== 200) { $this->meta = $this->json; } $this->pagination = isset($this->json['pagination']) ? $this->json['pagination'] : []; $this->user = isset($this->json['user']) ? $this->json['user'] : []; $this->access_token = isset($this->json['access_token']) ? $this->json['access_token'] : NULL; $this->limit = isset($this->headers[self::RATE_LIMIT_HEADER]) ? $this->headers[self::RATE_LIMIT_HEADER] : 0; $this->remaining = isset($this->headers[self::RATE_LIMIT_REMAINING_HEADER]) ? $this->headers[self::RATE_LIMIT_REMAINING_HEADER] : 0; }
/** * traitement du retour d'un service * * @param Response $response la reponse obtenue * @return false en cas d'erreur / le json obtenu sinon * @author Nicolas */ private function checkResponse(Response $response) { if ($response->getStatusCode() != 200) { if (isset($res['errors'])) { // au cas ou le serveur ne soit même pas joignable $this->checkError($res['errors']); } return false; } return $response->json(); }
/** * @param Response $response * @return array */ public static function parseJSON(Response $response) { return $response->json(); }
/** * @Then I should get an array of tweets */ public function iShouldAnArrayOfTweets() { PHPUnit_Framework_Assert::assertNotEmpty($this->response->json()); }
/** * Handles a successful fetch of tweet data. * * @param \GuzzleHttp\Message\Response $response * @param \Phergie\Irc\Event\UserEventInterface $event * @param \Phergie\Irc\Bot\React\EventQueueInterface $queue */ public function handleSuccess(Response $response, Event $event, Queue $queue) { $json = $response->json(array('object' => true)); $this->logger->debug('Received response', array('json' => $json)); $formatted = $this->formatter->format($json); $queue->ircPrivmsg($event->getSource(), $formatted); }
/** * @expectedException \GuzzleHttp\Exception\ParseException * @expectedExceptionMessage Unable to parse JSON data: JSON_ERROR_SYNTAX - Syntax error, malformed JSON */ public function testThrowsExceptionWhenFailsToParseJsonResponse() { $response = new Response(200, [], Stream::factory('{"foo": "')); $response->json(); }
public function getData() { return $this->response->json(); }