Esempio n. 1
0
 /**
  * {@inheritDoc}
  */
 public function populateFromResponse(ResponseInterface $response)
 {
     $entries = $response->json()['access']['serviceCatalog'];
     foreach ($entries as $entry) {
         $this->entries[] = $this->model('Entry', $entry);
     }
 }
Esempio n. 2
0
 /**
  * Creates a response object
  * @param ResponseInterface $responseInterface
  * @throws ParseException
  */
 public function __construct(ResponseInterface $responseInterface)
 {
     $this->response = $responseInterface->json();
     $this->status = isset($this->response['meta']['code']) ? $this->response['meta']['code'] : 500;
     $this->errorCode = isset($this->response['meta']['error_code']) ? $this->response['meta']['error_code'] : null;
     $this->responseErrorCodes = new ResponseErrorCodes();
 }
 /**
  * @param ResponseInterface $response
  */
 private function handleResponse(ResponseInterface $response, Request $request)
 {
     $context = $this->prepareBaseContext($request);
     $data = $response->json();
     if (isset($data['results'])) {
         foreach ($data['results'] as $registrationIdIdx => $result) {
             $context['registrationId'] = $this->registrationIds[$registrationIdIdx];
             $context['result'] = var_export($result, true);
             switch (key($result)) {
                 case 'message_id':
                     if (isset($result['registration_id'])) {
                         $this->callback(EventsEnum::ON_PUSH_SUCCESS_BUT_NEED_NEW_ID, [$context]);
                     } else {
                         $this->callback(EventsEnum::ON_PUSH_SUCCESS, [$context]);
                     }
                     break;
                 case 'error':
                     $currentResult = current($result);
                     switch ($currentResult) {
                         case 'Unavailable':
                             $this->callback(EventsEnum::ON_PUSH_UNAVAILABLE, [$context]);
                             break;
                         case 'InvalidRegistration':
                             $this->callback(EventsEnum::ON_PUSH_INVALID_REGISTRATION, [$context]);
                             break;
                         case 'NotRegistered':
                             $this->callback(EventsEnum::ON_PUSH_NOT_REGISTERED, [$context]);
                             break;
                     }
                     break;
             }
         }
     }
     return ['success' => $data['success'], 'failure' => $data['failure']];
 }
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Google_Service_Exception
  * @param GuzzleHttp\Message\RequestInterface $response The http response to be decoded.
  * @param GuzzleHttp\Message\ResponseInterface $response
  * @return mixed|null
  */
 public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null)
 {
     $body = (string) $response->getBody();
     $code = $response->getStatusCode();
     $result = null;
     // return raw response when "alt" is "media"
     $isJson = !($request && 'media' == $request->getQuery()->get('alt'));
     // set the result to the body if it's not set to anything else
     if ($isJson) {
         try {
             $result = $response->json();
         } catch (ParseException $e) {
             $result = $body;
         }
     } else {
         $result = $body;
     }
     // retry strategy
     if (intVal($code) >= 300) {
         $errors = null;
         // Specific check for APIs which don't return error details, such as Blogger.
         if (isset($result['error']) && isset($result['error']['errors'])) {
             $errors = $result['error']['errors'];
         }
         throw new Google_Service_Exception($body, $code, null, $errors);
     }
     return $result;
 }
 public function it_handle_unexpected_oboom_response(Client $guzzleClient, ResponseInterface $response)
 {
     $url = 'http://example.com';
     $response->json()->shouldBeCalled()->willReturn([400]);
     $guzzleClient->get($url, ['query' => []])->willReturn($response);
     $this->shouldThrow(new RuntimeException('API error', 400))->during('call', [$url]);
 }
Esempio n. 6
0
 public function getCount($content, ResponseInterface $response = null)
 {
     $data = $response->json();
     if (empty($data)) {
         return false;
     }
     return (int) array_shift($data)['shares'];
 }
Esempio n. 7
0
 function it_should_return_results_as_an_object(ClientInterface $client, ResponseInterface $response)
 {
     $params = 'key=' . $this->test_key . '&hero_id=12345&skill=2';
     $expectedUrl = $this->test_base_url . 'IDOTA2Match_570/GetMatchDetails/v001/?' . $params;
     $responseReturn = json_decode('{"result": {"status": 1, "num_results": 0, "total_results": 407, "results_remaining": 307} }');
     $response->json(['object' => true])->shouldBeCalled()->willReturn($responseReturn);
     $client->get($expectedUrl)->shouldBeCalled()->willReturn($response);
     $this->endpoint('IDOTA2Match_570/GetMatchDetails/v001')->options(['hero_id' => 12345, 'skill' => 2])->get()->shouldReturn($responseReturn);
 }
Esempio n. 8
0
 public function before(CommandInterface $command, ResponseInterface $response, Parameter $model, &$result, array $context = [])
 {
     $this->json = $response->json() ?: [];
     // relocate named arrays, so that they have the same structure as
     //  arrays nested in objects and visit can work on them in the same way
     if ($model->getType() == 'array' && ($name = $model->getName())) {
         $this->json = [$name => $this->json];
     }
 }
Esempio n. 9
0
 /**
  * Populates the current resource from a response object.
  *
  * @param ResponseInterface $response
  *
  * @return $this|ResourceInterface
  */
 public function populateFromResponse(ResponseInterface $response)
 {
     if (strpos($response->getHeader('Content-Type'), 'application/json') === 0) {
         $json = $response->json();
         if (!empty($json)) {
             $this->populateFromArray($this->flatten($json));
         }
     }
     return $this;
 }
 public function __construct(ResponseInterface $response)
 {
     try {
         $this->details = $response->json();
         $message = isset($this->details['error']['message']) ? $this->details['error']['message'] : $response->getReasonPhrase();
     } 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());
 }
Esempio n. 11
0
 /**
  * Checks that response body contains JSON from PyString.
  *
  * Do not check that the response body /only/ contains the JSON from PyString,
  *
  * @param PyStringNode $jsonString
  *
  * @throws \RuntimeException
  *
  * @Then /^(?:the )?response should contain json:$/
  */
 public function theResponseShouldContainJson(PyStringNode $jsonString)
 {
     $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true);
     $actual = $this->response->json();
     if (null === $etalon) {
         throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw()));
     }
     $factory = new SimpleFactory();
     $matcher = $factory->createMatcher();
     Assertions::assertTrue($matcher->match($actual, $etalon));
 }
 /**
  * Asserts response match with the response schema.
  *
  * @param ResponseInterface $response
  * @param SchemaManager $schemaManager
  * @param string $path percent-encoded path used on the request.
  * @param string $httpMethod
  * @param string $message
  */
 public function assertResponseMatch(ResponseInterface $response, SchemaManager $schemaManager, $path, $httpMethod, $message = '')
 {
     $this->assertResponseMediaTypeMatch($response->getHeader('Content-Type'), $schemaManager, $path, $httpMethod, $message);
     $httpCode = $response->getStatusCode();
     $headers = $response->getHeaders();
     foreach ($headers as &$value) {
         $value = implode(', ', $value);
     }
     $this->assertResponseHeadersMatch($headers, $schemaManager, $path, $httpMethod, $httpCode, $message);
     $this->assertResponseBodyMatch($response->json(['object' => true]), $schemaManager, $path, $httpMethod, $httpCode, $message);
 }
Esempio n. 13
0
 public function __construct(RequestInterface $request, ResponseInterface $response)
 {
     $payload = $response->json();
     $this->id = $payload['id'];
     $result = $payload['result'];
     $this->status = [];
     if (isset($result['status'])) {
         $this->status = $result['status'];
         unset($result['status']);
     }
     parent::__construct($result);
 }
 /**
  * Checks that response body contains JSON from PyString.
  *
  * Do not check that the response body /only/ contains the JSON from PyString,
  *
  * @param PyStringNode $jsonString
  *
  * @throws \RuntimeException
  *
  * @Then /^(?:the )?response should contain json:$/
  */
 public function theResponseShouldContainJson(PyStringNode $jsonString)
 {
     $etalon = json_decode($this->replacePlaceHolder($jsonString->getRaw()), true);
     $actual = $this->response->json();
     if (null === $etalon) {
         throw new \RuntimeException("Can not convert etalon to json:\n" . $this->replacePlaceHolder($jsonString->getRaw()));
     }
     Assertions::assertGreaterThanOrEqual(count($etalon), count($actual));
     foreach ($etalon as $key => $needle) {
         Assertions::assertArrayHasKey($key, $actual);
         Assertions::assertEquals($etalon[$key], $actual[$key]);
     }
 }
Esempio n. 15
0
 /**
  * Creates a new Funnelback response.
  *
  * @param \GuzzleHttp\Message\ResponseInterface $http_response
  *   The http response.
  */
 public function __construct(ResponseInterface $http_response)
 {
     $this->httpResponse = $http_response;
     $this->responseJson = $http_response->json();
     $this->query = $this->responseJson['question']['query'];
     $response = $this->responseJson['response'];
     $this->returnCode = $response['returnCode'];
     $this->totalTimeMillis = $response['performanceMetrics']['totalTimeMillis'];
     $result_packet = $response['resultPacket'];
     $this->resultsSummary = new ResultSummary($result_packet['resultsSummary']);
     $this->results = $this->buildResults($result_packet['results']);
     $this->facets = $this->buildFacets($response['facets']);
 }
Esempio n. 16
0
 /**
  * Create Job Search for $subscriptionId
  *
  * @param $subscriptionId
  * @param $search
  * @param $location
  * @param $createTime
  *
  * @return bool|mixed
  */
 public function createJobSearch($subscriptionId, $search, $location, $createTime)
 {
     $request = ['search' => $search, 'location' => $location, 'create_time' => $createTime];
     $url = 'subscriber/' . $subscriptionId . '/searches';
     if ($this->isExpandedResults()) {
         $url .= '?expand_results=1';
     }
     $this->response = $this->client->post($url, ['body' => $request]);
     if (201 == $this->response->getStatusCode()) {
         return $this->response->json();
     }
     return false;
 }
Esempio n. 17
0
 /**
  * Sends a request with error handling
  *
  * @param RequestInterface $request
  */
 protected function send(RequestInterface $request)
 {
     try {
         $this->response = $this->client->send($request);
         $this->jsonResponse = $this->response->json();
     } catch (ClientException $e) {
         $this->response = $e->getResponse();
         //when 404 or 401 or 403 or something else
         $this->jsonResponse = $this->response->getBody()->getContents();
         if (null === $this->response) {
             throw $e;
         }
     }
 }
Esempio n. 18
0
 /**
  * @param CompleteEvent $event
  *
  * @throws \RuntimeException|ExceptionInterface
  */
 protected function handleResponse(CompleteEvent $event)
 {
     $this->response = $event->getResponse();
     if ($this->response->getStatusCode() >= 200 && $this->response->getStatusCode() <= 299) {
         return;
     }
     $body = $this->response->getBody();
     $code = $this->response->getStatusCode();
     if ($this->exception) {
         throw $this->exception->create($body, $code);
     }
     $content = $this->response->json();
     throw new \RuntimeException(sprintf('[%d] %s (%s)', $code, $content->message, $content->id), $code);
 }
Esempio n. 19
0
 /**
  * Formats a multi-level, JSON-formatted response.
  *
  * @param  ResponseInterface $response Guzzle response object.
  * @param  OutputInterface   $output   Symfony Console output object.
  * @param  string            $key      A response key to pull-out and highlight. Should be the most
  *                                     important identifier for the result.
  * @return void
  *
  * @SuppressWarnings(PHPMD.ElseExpression)
  */
 public static function handleArrayResponse(ResponseInterface $response, OutputInterface $output, $key = null)
 {
     $output->getFormatter()->setStyle('status', self::formatter()->info);
     if ($response->getBody()) {
         $data = $response->json();
         foreach ($data as $i => $d) {
             $output->writeln('');
             if ($key) {
                 $output->writeln(sprintf('<status> Result #%s (%s: %s) </status>', $i + 1, $key, $d[$key]));
             } else {
                 $output->writeln(sprintf('<status> Result #%s </status>', $i + 1));
             }
             self::asTable($d, $output);
         }
     }
 }
Esempio n. 20
0
 /**
  * Makes sure the Diffbot response has all the fields it needs to work properly
  *
  * @todo: remove error avoidance when issue 12 is fixed: https://github.com/Swader/diffbot-php-client/issues/12
  * @param Response $response
  * @throws DiffbotException
  */
 protected function checkResponseFormat(Response $response)
 {
     set_error_handler(function () {
         /* ignore errors */
     });
     $arr = $response->json(['big_int_strings' => true]);
     restore_error_handler();
     if (isset($arr['error'])) {
         throw new DiffbotException('Diffbot returned error ' . $arr['errorCode'] . ': ' . $arr['error']);
     }
     $required = ['objects' => 'Objects property missing - cannot extract entity values', 'request' => 'Request property not found in response!'];
     foreach ($required as $k => $v) {
         if (!isset($arr[$k])) {
             throw new DiffbotException($v);
         }
     }
 }
Esempio n. 21
0
 /**
  * Extract more detailed error message.
  *
  * @param Response $response
  * @return string
  */
 protected function getErrorMessage(Response $response)
 {
     // This is the default:
     $error = $response->getReasonPhrase();
     // e.g. "Bad Request"
     try {
         // We might be able to fetch an error message from the response
         $responseData = $response->json();
         if (isset($responseData['title'])) {
             $error = $responseData['title'];
         }
         if (isset($responseData['detail'])) {
             $error .= ': ' . $responseData['detail'];
         }
     } catch (ParseException $e) {
         // Do nothing
     }
     return (string) $error;
 }
Esempio n. 22
0
 /**
  * Decode an HTTP Response.
  * @static
  * @throws Google_Service_Exception
  * @param GuzzleHttp\Message\RequestInterface $response The http response to be decoded.
  * @param GuzzleHttp\Message\ResponseInterface $response
  * @return mixed|null
  */
 public static function decodeHttpResponse(ResponseInterface $response, RequestInterface $request = null)
 {
     $body = (string) $response->getBody();
     $code = $response->getStatusCode();
     // retry strategy
     if (intVal($code) >= 300) {
         $errors = null;
         $result = $response->json();
         // Specific check for APIs which don't return error details, such as Blogger.
         if (isset($result['error']) && isset($result['error']['errors'])) {
             $errors = $result['error']['errors'];
         }
         throw new Google_Service_Exception($body, $code, null, $errors);
     }
     // return raw response when "alt" is "media"
     if ($request && $request->getQuery()->get('alt') == 'media') {
         return $body;
     }
     return $response->json();
 }
Esempio n. 23
0
 /**
  * Extract more detailed error message.
  *
  * @param Response $response
  * @return string
  */
 protected function extractErrorMessage(Response $response)
 {
     // This is the default
     $error = $response->getReasonPhrase();
     // e.g. "Bad Request"
     try {
         // We might be able to fetch an error message from the response
         $responseData = $response->json();
         if (isset($responseData['results'])) {
             $result = $responseData['results'];
             if (isset($result['errors']) && is_array($result['errors']) && count($result['errors']) > 0) {
                 $error = current($result['errors']);
             } elseif (isset($result['error'])) {
                 $error = $result['error'];
             }
         }
     } catch (ParseException $e) {
         // Do nothing
     }
     return (string) $error;
 }
 public function normalize(ResponseInterface $response)
 {
     return $response->json();
 }
Esempio n. 25
0
 public function it_should_return_suggestedQueries(ResponseInterface $mockedResponse)
 {
     $mockedResponse->json()->shouldBeCalled()->willReturn('searchSuggestedQueries');
     $this->suggestedQueries('query')->shouldReturn('searchSuggestedQueries');
 }
Esempio n. 26
0
 /**
  * Returns the response in the configured format.
  *
  * @param ResponseInterface $response
  * @param string            $format
  *
  * @return mixed $response
  */
 private function responseFormat($response, $format)
 {
     if ($format == 'json') {
         return $response->json();
     } elseif ($format == 'xml') {
         return $response->xml();
     }
     return $response;
 }
Esempio n. 27
0
 /**
  * @return mixed
  */
 public function json()
 {
     return $this->response->json();
 }
Esempio n. 28
0
 function it_sends_post_and_returns_result(MethodInterface $method, Client $client, RequestInterface $request, ResponseInterface $response)
 {
     $response->json()->shouldBeCalled()->willReturn(['foo' => 'bar']);
     $client->send($request)->shouldBeCalled()->willReturn($response);
     $this->sendRequest($method, 'POST', 'https://api.cardinity.com/v1/', [])->shouldReturn(['foo' => 'bar']);
 }
Esempio n. 29
0
 public function getCount($content, ResponseInterface $response = null)
 {
     $data = $response->json();
     return (int) $data['count'];
 }
Esempio n. 30
0
 function it_creates_resource_with_body_for_a_specific_uri_with_uri_parameters($client, $adapterFactory, $paginatorFactory, ResponseInterface $response)
 {
     $this->beConstructedWith($client, 'parentUri/{parentId}/uri', $adapterFactory, $paginatorFactory);
     $response->getHeader('Content-Type')->willReturn('application/json');
     $response->json()->willReturn(['id' => 1, 'field1' => 'field1Value', 'field2' => 'field2Value']);
     $client->post('parentUri/2/uri/', ['field1' => 'field1Value', 'field2' => 'field2Value'], [])->willReturn($response)->shouldBeCalled();
     $this->create(['field1' => 'field1Value', 'field2' => 'field2Value'], ['parentId' => 2])->shouldReturn(['id' => 1, 'field1' => 'field1Value', 'field2' => 'field2Value']);
 }