Example #1
1
 /**
  * Simple exception factory for creating Intercom standardised exceptions
  *
  * @param RequestInterface $request The Request
  * @param Response $response The response
  * @return BadResponseException
  */
 public static function factory(RequestInterface $request, Response $response)
 {
     $response_json = $response->json();
     $intercom_unavailable_error = NULL;
     if (!static::isValidIntercomError($response_json)) {
         if ($response->isServerError()) {
             $label = 'Server error response';
             $class = __NAMESPACE__ . '\\ServerErrorResponseException';
             $intercom_unavailable_error = 'Service Unavailable: Back-end server is at capacity';
         } else {
             $label = 'Unsuccessful response';
             $class = __CLASS__;
         }
     } elseif ($response->isClientError()) {
         $label = 'Client error response';
         $class = __NAMESPACE__ . '\\ClientErrorResponseException';
     } elseif ($response->isServerError()) {
         $label = 'Server error response';
         $class = __NAMESPACE__ . '\\ServerErrorResponseException';
     } else {
         $label = 'Unsuccessful response';
         $class = __CLASS__;
     }
     $message = $label . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl()));
     $e = new $class($message);
     $e->setResponse($response);
     $e->setRequest($request);
     // Sets the errors if the error response is the standard Intercom error type
     if (static::isValidIntercomError($response_json)) {
         $e->setErrors($response_json['errors']);
     } elseif ($intercom_unavailable_error != NULL) {
         $e->setErrors(array('code' => 'service_unavailable', "message" => $intercom_unavailable_error));
     }
     return $e;
 }
Example #2
1
 /**
  * Simple exception factory for creating Intercom standardised exceptions
  *
  * @param RequestInterface $request The Request
  * @param Response $response The response
  * @return BadResponseException
  */
 public static function factory(RequestInterface $request, Response $response)
 {
     if (!static::isValidIntercomError($response->json())) {
         $label = 'Unsuccessful response';
         $class = __CLASS__;
     } elseif ($response->isClientError()) {
         $label = 'Client error response';
         $class = __NAMESPACE__ . '\\ClientErrorResponseException';
     } elseif ($response->isServerError()) {
         $label = 'Server error response';
         $class = __NAMESPACE__ . '\\ServerErrorResponseException';
     } else {
         $label = 'Unsuccessful response';
         $class = __CLASS__;
     }
     $message = $label . PHP_EOL . implode(PHP_EOL, array('[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl()));
     $e = new $class($message);
     $e->setResponse($response);
     $e->setRequest($request);
     // Sets the errors if the error response is the standard Intercom error type
     if (static::isValidIntercomError($response->json())) {
         $e->setErrors($response->json()['errors']);
     }
     return $e;
 }
 /**
  * @param array $query
  *
  * @return array
  */
 public function genderize(array $query)
 {
     $queryString = '?' . http_build_query($query);
     $request = $this->get($queryString);
     $this->setLastResponse($request->send());
     return $this->lastResponse->json();
 }
 /**
  * Get the response of the query.
  * Will be the json decoded data if success, else the error message.
  *
  * @return array|string
  */
 public function getResponse()
 {
     if (false === $this->response->isSuccessful()) {
         return $this->response->getMessage();
     }
     return $this->response->json();
 }
 /**
  * Get response as an array.
  *
  * @return array
  */
 private function getResponseAsArray()
 {
     $this->result = $this->response->json();
     if ($this->responseHasErrors()) {
         return false;
     }
     return $this->result;
 }
Example #6
0
 /**
  * @param string $what
  * @return null
  */
 protected function extractFromResponse($what)
 {
     $data = $this->guzzleResponse->json();
     if ($data && is_array($data)) {
         if (array_key_exists($what, $data)) {
             return $data[$what];
         }
     }
     return null;
 }
Example #7
0
 public function __construct(\Guzzle\Http\Message\Response $response, $type)
 {
     $this->_response = $response;
     // if json returned - parse and fill structure
     $contentType = $this->_response->getContentType();
     if (strpos($contentType, ';')) {
         list($contentType, ) = explode(';', $contentType);
     }
     if ($contentType == 'application/json') {
         $this->_structure = new $type($this->_response->json());
     } else {
         throw new \Exception('Structure parser for content type "' . $this->_response->getContentType() . '" not implemented');
     }
 }
 /**
  * Parses response into an array
  *
  * @param Response $response
  * @return array
  */
 protected function parseResponseIntoArray($response)
 {
     if (strpos($response->getContentType(), 'json') === false) {
         parse_str($response->getBody(true), $array);
         return $array;
     }
     return $response->json();
 }
Example #9
0
 /**
  * {@inheritdoc}
  */
 public function json()
 {
     try {
         $result = $this->response->json();
     } catch (\Exception $exception) {
         throw GuzzleRestException::createFromException($exception);
     }
     return $result;
 }
Example #10
0
 /**
  * Format the raw API response into an array of Models.
  *
  * @param Guzzle\Http\Message\Response $response api response
  * @param string $model the name of the class to instantiate
  *
  * @return array
  */
 public function formatResponse(Response $response, $model)
 {
     $body = $response->json();
     $collection = [];
     foreach ($body['data'] as $item) {
         $collection[] = new $model($this, $item);
     }
     // foreach body[data]
     return $collection;
 }
 public function decodeResponse(Response $response)
 {
     $jsonResponse = $response->json();
     if (isset($jsonResponse["result"]) && ($result = $jsonResponse["result"]) !== "success") {
         throw new RpcErrorException($result);
     }
     if (!isset($jsonResponse["arguments"])) {
         throw new RpcNoResultException();
     }
     return $jsonResponse["arguments"];
 }
 public function decodeResponse(Response $response)
 {
     $json = $response->json();
     if (isset($json["error"])) {
         throw new RpcErrorException($json["error"]);
     }
     if (!isset($json["result"])) {
         throw new RpcNoResultException();
     }
     return $json["result"];
 }
 /**
  * Executing service description defined operations returns the result
  * @group unit
  */
 public function testMagicOperationsReturnResult()
 {
     $responseData = array("this" => "that");
     Phockito::when($this->mockResponse->getStatusCode())->return(200);
     Phockito::when($this->mockResponse->json())->return($this->testDescription);
     Phockito::when($this->mockRequest->send())->return($this->mockResponse);
     Phockito::when($this->client)->get(anything())->return($this->mockRequest);
     Phockito::when($this->client)->callParent(anything(), anything())->return($responseData);
     $result = $this->client->SomeOperation(array());
     $this->assertEquals($result, $responseData);
 }
 public function testSuccess()
 {
     $body = file_get_contents(dirname(dirname(__FILE__)) . '/Mock/TokenPurchaseSuccess.txt');
     $httpResponse = new Response(200, array('Content-Type' => 'application/json'), $body);
     $response = new TokenPurchaseResponse($this->getMockRequest(), $httpResponse->json());
     $this->assertTrue($response->isSuccessful());
     $this->assertFalse($response->isRedirect());
     $this->assertNull($response->getCode());
     $this->assertNull($response->getMessage());
     $this->assertSame('205182114555', $response->getTransactionReference());
 }
Example #15
0
 /**
  * @param \Guzzle\Http\Message\Response $response
  */
 public function __construct(\Guzzle\Http\Message\Response $response)
 {
     if ($response->isSuccessful()) {
         $this->response = $response->json();
         foreach ($this->response as $key => $value) {
             $this->response[$key] = $value;
         }
     } else {
         // TODO: Error handling
     }
 }
Example #16
0
 /**
  * Get response as an array, returns false if no result.
  *
  * @param bool|array
  */
 private function getResponseAsArray()
 {
     $this->result = $this->response->json();
     if (isset($this->result['isLastPage'])) {
         $this->lastPage = $this->result['isLastPage'];
     }
     if ($this->responseHasErrors()) {
         return false;
     }
     return $this->result;
 }
Example #17
0
 /**
  * Parse the received response into a usable format
  *
  * @return [type] [description]
  */
 private function parse()
 {
     $data = $this->httpResponse->json();
     foreach ($data['messages'] as $message) {
         $msg = new Message($message);
         $this->messages[] = $msg;
         if ($message['type'] === 'error' || $message['type'] === 'non-document-error') {
             $this->errors[] = $msg;
         } else {
             if (isset($message['subType']) && $message['type'] === 'info' && $message['subType'] === 'warning') {
                 $this->warnings[] = $msg;
             }
         }
     }
 }
 public static function factory(RequestInterface $request, Response $response)
 {
     $response_json = $response->json();
     $generic_error = null;
     $cls = null;
     $is_lc_error = static::isLCApiError($response_json);
     $err_code = null;
     $err_message = null;
     $err_domain = null;
     $err_exception = null;
     $err_trace = null;
     $validation_failures = array();
     if ($is_lc_error) {
         $err_code = isset($response_json['error']['code']) ? $response_json['error']['code'] : null;
         $err_message = isset($response_json['error']['message']) ? $response_json['error']['message'] : null;
         $err_domain = isset($response_json['error']['domain']) ? $response_json['error']['domain'] : null;
         $err_exception = isset($response_json['error']['exception']) ? $response_json['error']['exception'] : null;
         $err_trace = isset($response_json['error']['trace']) ? $response_json['error']['trace'] : null;
         // parse validation failures
         $failures = isset($response_json['error']['validation_failures']) ? $response_json['error']['validation_failures'] : null;
         if ($failures) {
             foreach ($failures as $failure) {
                 $validation_failures[] = new ValidationFailure(isset($failure['name']) ? $failure['name'] : null, isset($failure['message']) ? $failure['message'] : null, isset($failure['extra_data']) ? $failure['extra_data'] : null);
                 unset($failure);
             }
         }
     } else {
         $err_message = 'Server communication error';
     }
     if ($is_lc_error) {
         $cls = __NAMESPACE__ . '\\ClientErrorResponseException';
     } elseif ($response->isClientError()) {
         $cls = __NAMESPACE__ . '\\ServerErrorResponseException';
     } else {
         $cls = __CLASS__;
     }
     /** @var Payin7APIException $e */
     $e = new $cls($err_message);
     $e->setResponse($response);
     $e->setRequest($request);
     $e->setServerErrorCode($err_code);
     $e->setServerErrorMessage($err_message);
     $e->setServerErrorDomain($err_domain);
     $e->setServerErrorException($err_exception);
     $e->setServerErrorTrace($err_trace);
     $e->setServerValidationFailures($validation_failures);
     return $e;
 }
Example #19
0
 /**
  * Create Exception object from response
  *
  * @param  \Guzzle\Http\Message\Response $response
  * @return WebPayException
  */
 public static function exceptionFromResponse(\Guzzle\Http\Message\Response $response)
 {
     $status = $response->getStatusCode();
     $data = $response->json();
     $errorInfo = isset($data['error']) ? $data['error'] : null;
     switch ($status) {
         case 400:
         case 404:
             return new InvalidRequestException($status, $errorInfo);
         case 401:
             return new AuthenticationException($status, $errorInfo);
         case 402:
             return new CardException($status, $errorInfo);
         default:
             return new APIException($status, $errorInfo);
     }
 }
Example #20
0
 /**
  * @covers Guzzle\Http\Message\Response::json
  * @expectedException \Guzzle\Common\Exception\RuntimeException
  * @expectedExceptionMessage Unable to parse response body into JSON: 4
  */
 public function testThrowsExceptionWhenFailsToParseJsonResponse()
 {
     $response = new Response(200, array(), '{"foo": "');
     $response->json();
 }
Example #21
0
 /**
  * Log response.
  *
  * @param Response $response API response.
  *
  * @return void
  */
 protected function logResponse(Response $response)
 {
     try {
         $body = $response->json();
         if (isset($body['error'])) {
             if (isset($body['message'])) {
                 $this->logger->error($body['message']);
             }
         } else {
             if (isset($body['message'])) {
                 $this->logger->info(sprintf('Accepted %s', $body['message']));
             }
             if (isset($body['url'])) {
                 $this->logger->info(sprintf('You can see the build on %s', $body['url']));
             }
         }
     } catch (\Guzzle\Common\Exception\RuntimeException $e) {
         // the response body is not in JSON format
         $body = $response->getBody(true);
         if ($body) {
             $this->logger->error($body);
         }
     }
 }
Example #22
0
 private function processResponse(Response $response)
 {
     if (!$response->isSuccessful()) {
         throw new ApiServerException($response->getMessage(), $response->getStatusCode());
     }
     if (self::FORMAT_ARRAY === $this->outputFormat) {
         return $response->json();
     }
     return $response->getBody(true);
 }
Example #23
0
 /**
  * Construct from http response
  * @internal
  */
 protected final function __construct(Response $response)
 {
     $this->raw = $response->json();
 }
 /**
  * Log response.
  *
  * @param  Response $response API response.
  * @return void
  *
  * @codeCoverageIgnore
  */
 protected function logResponse(Response $response)
 {
     $body = $response->json();
     if (isset($body['error'])) {
         if (isset($body['message'])) {
             $this->logger->error($body['message']);
         }
     } else {
         if (isset($body['message'])) {
             $this->logger->info(sprintf('Accepted %s', $body['message']));
         }
         if (isset($body['url'])) {
             $this->logger->info(sprintf('You can see the build on %s', $body['url']));
         }
     }
 }
Example #25
0
 /**
  * @param Response
  */
 private function fetchRepos(Response $orgResponse)
 {
     foreach ($orgResponse->json() as $repo) {
         if (!$repo['permissions']['admin']) {
             $this->addNonImportableProject($repo['full_name'], 'no admin rights on the project');
             continue;
         }
         $this->cacheProjectInfo($repo);
         $this->addImportableProject($repo['full_name']);
     }
 }
Example #26
0
 function it_gets_rates(Client $client, Response $response)
 {
     $response->json()->shouldBeCalled()->willReturn(['currencyName' => 'HKD', 'deliverTime' => null]);
     $regions = $this->getRates('A000812000', 'A440300000', 2, 200000)->shouldReturn(['currencyName' => 'HKD', 'deliverTime' => null]);
 }
Example #27
0
 /**
  * @param array $entites
  * @return array
  */
 private function createEntityListFromResponse(\Guzzle\Http\Message\Response $response)
 {
     $connections = array();
     foreach ($response->json() as $entityId => $connectionMetadata) {
         if (static::MAX_CONNECTIONS_TO_TEST && count($connections) > static::MAX_CONNECTIONS_TO_TEST) {
             break;
         }
         $connections[] = array($entityId);
     }
     return $connections;
 }
Example #28
0
 /**
  * {@inheritdoc}
  */
 protected function createToken(Response $response)
 {
     $authData = $response->json();
     $this->raiseException($authData);
     return new AccessToken($authData['access_token'], null, array(), $authData['expires_in']);
 }
Example #29
0
 public function parseResult(Response $response)
 {
     try {
         $json = $response->json();
         if (array_key_exists('d', $json)) {
             if (array_key_exists('results', $json['d'])) {
                 if (count($json['d']['results']) == 1) {
                     return $json['d']['results'][0];
                 }
                 return $json['d']['results'];
             }
             return $json['d'];
         }
         return $json;
     } catch (\RuntimeException $e) {
         throw new ApiException($e->getMessage());
     }
 }
 /**
  * @param Response $rawResponse
  *
  * @return mixed
  */
 protected function parseResponse($rawResponse)
 {
     $formattedResponse = $rawResponse->json();
     return $formattedResponse;
 }