Exemple #1
0
 private function processResponse(Response $response)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Status Code %s', $response->getStatusCode()));
         $this->logger->debug(var_export($response->getContent(), true));
     }
     if (500 <= $response->getStatusCode()) {
         throw new ApiServerException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (400 <= $response->getStatusCode()) {
         try {
             $error = $this->parser->parse($response->getContent());
             $error = $error instanceof Model\Error ? $error : new Model\Error();
         } catch (ApiParserException $e) {
             throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), null, $e);
         }
         throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), $error);
     }
     if (204 === $response->getStatusCode()) {
         return true;
     }
     $content = trim($response->getContent());
     if (empty($content)) {
         return true;
     }
     $object = $this->parser->parse($content);
     $object->setApi($this);
     return $object;
 }
 protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
 {
     $responseCode = $response->getStatusCode();
     if ($responseCode != $expected) {
         $errorMessageString = '';
         if ($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+xml') {
             $body = \simplexml_load_string($response->getContent());
             $errorMessageString = $body->errorDescription;
         } elseif ($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+json') {
             $body = json_decode($response->getContent());
             $errorMessageString = "Error message: {$body->ErrorMessage->errorDescription}";
         }
         self::assertEquals($expected, $responseCode, $errorMessageString);
     }
 }
 protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
 {
     $responseCode = $response->getStatusCode();
     if ($responseCode != $expected) {
         $errorMessageString = '';
         if (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+xml') !== false) {
             $body = \simplexml_load_string($response->getContent());
             $errorMessageString = $this->getHttpResponseCodeErrorMessage($body);
         } elseif (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+json') !== false) {
             $body = json_decode($response->getContent());
             $errorMessageString = $this->getHttpResponseCodeErrorMessage($body->ErrorMessage);
         }
         self::assertEquals($expected, $responseCode, $errorMessageString);
     }
 }
Exemple #4
0
 /**
  * Parse a response.
  *
  * @return \Tev\Bs\Contracts\ResponseInterface
  *
  * @throws \Exception
  * @throws \Tev\Bs\Exception\ErrorResponseException
  */
 public function getResponse()
 {
     $content = json_decode($this->response->getContent());
     if ($content === null) {
         throw new Exception('Failed to get response from server');
     }
     if (isset($content->error) && $content->error) {
         $excp = new ErrorResponseException($content->message, $this->response->getStatusCode());
         $excp->setResponse(new Response($content, $this->endpoint));
         throw $excp;
     }
     if (isset($content->per_page)) {
         return new PaginatedResponse($content, $this->endpoint);
     }
     return new Response($content, $this->endpoint);
 }
 /**
  * @param Response $curlResponse
  *
  * @throws HttpStatusParserException
  */
 public function parse(Response $curlResponse)
 {
     $statusCode = $curlResponse->getStatusCode();
     if ($this->shouldThrowException($statusCode)) {
         throw new HttpStatusParserException($curlResponse->getContent(), $statusCode);
     }
 }
 /**
  * This public method is also for other context(s) to process REST API call and inject response into this context.
  *
  * @param  \Buzz\Message\Response $response
  * @param  boolean                $asJson   Process the response as JSON or not.
  * @return void
  */
 public function processResponse(\Buzz\Message\Response $response = null, $asJson = true)
 {
     if (!empty($response)) {
         $this->response = $response;
     }
     return $this->processResponseBody($this->response->getContent(), $asJson);
 }
 public function it_can_search_with__query(Browser $client, Response $response)
 {
     $response->getContent()->shouldBeCalled();
     $client->get(sprintf('%s/search?%s', 'http://endpoint', http_build_query(['q' => 'pilkington avenue, birmingham', 'format' => 'json'])), ['User-Agent' => 'Nomatim PHP Library (https://github.com/nixilla/nominatim-consumer); email: not set'])->shouldBeCalled()->willReturn($response);
     $query = new Query();
     $query->setQuery('pilkington avenue, birmingham');
     $this->search($query)->shouldReturnAnInstanceOf('Nominatim\\Result\\Collection');
 }
Exemple #8
0
 public function _parse(Response $response, $mime = null)
 {
     $data = $this->decode($response->getContent(), $mime);
     if (isset($data->error)) {
         throw new RugException($data->error, $this->_error($data));
     }
     return $data;
 }
 /**
  * {@inheritDoc}
  */
 public function getContent()
 {
     $response = parent::getContent();
     $content = json_decode($response, true);
     if (JSON_ERROR_NONE !== json_last_error()) {
         return $response;
     }
     return $content;
 }
 /**
  * @param  Response $response
  *
  * @return string
  */
 private function processResponse(Response $response)
 {
     $matches = [];
     preg_match('/<input.*value="(.*)"/U', $response->getContent(), $matches);
     if (!isset($matches[1])) {
         throw new \RuntimeException('Screenshot upload failed');
     }
     return $matches[1];
 }
 /**
  * Lets us know if something went wrong
  *
  * @param Response $response
  * @throws \Twitter\Exception\TwitterApiException
  * @throws \Exception
  */
 protected function handleException(Response $response)
 {
     $json_string = $response->getContent();
     $output = json_decode($json_string, true);
     if (count($output['errors'])) {
         throw new TwitterApiException($output['errors'][0]['message'], $output['errors'][0]['code']);
     } else {
         throw new \Exception(sprintf('Unknown error: %s', $json_string));
     }
 }
 /**
  * @return mixed
  */
 public function getContent()
 {
     $response = parent::getContent();
     if ($this->getHeader('Content-Type') === 'application/json') {
         $content = json_decode($response, true);
         if (JSON_ERROR_NONE !== json_last_error()) {
             return $response;
         }
         return $content;
     }
     return $response;
 }
Exemple #13
0
 private function processResponse(Response $response)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Status Code %s', $response->getStatusCode()));
         $this->logger->debug(var_export($response->getContent(), true));
     }
     if (500 <= $response->getStatusCode()) {
         throw new ApiServerException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (400 <= $response->getStatusCode()) {
         throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (204 === $response->getStatusCode()) {
         return true;
     }
     if (null !== $response->getContent()) {
         $object = $this->parser->parse($response->getContent());
         $object->setApi($this);
         return $object;
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function validateResponse(Response $response)
 {
     $content = $response->getContent();
     $success = false;
     $xml = new \DOMDocument();
     if ($xml->loadXML($content)) {
         foreach ($xml->firstChild->childNodes as $child) {
             if ($child->nodeName === 'cas:authenticationSuccess') {
                 $root = $child;
                 $success = true;
                 break;
             } elseif ($child->nodeName === 'cas:authenticationFailure') {
                 $root = $child;
                 $success = false;
                 break;
             }
         }
         if ($success) {
             foreach ($root->childNodes as $child) {
                 switch ($child->nodeName) {
                     case 'cas:user':
                         $this->username = $child->textContent;
                         break;
                     case 'cas:attributes':
                         foreach ($child->childNodes as $attr) {
                             if ($attr->nodeName != '#text') {
                                 $this->attributes[$attr->nodeName] = $attr->textContent;
                             }
                         }
                         break;
                     case 'cas:attribute':
                         $name = $child->attributes->getNamedItem('name')->value;
                         $value = $child->attributes->getNamedItem('value')->value;
                         if ($name && $value) {
                             $this->attributes[$name] = $value;
                         }
                         break;
                     case '#text':
                         break;
                     default:
                         $this->attributes[substr($child->nodeName, 4)] = $child->textContent;
                 }
             }
         } else {
             $this->error = (string) $root->textContent;
         }
     } else {
         $success = false;
         $this->error = 'Invalid response';
     }
     return $success;
 }
 /**
  * {@inheritdoc}
  */
 protected function validateResponse(Response $response)
 {
     $content = $response->getContent();
     $data = explode("\n", str_replace("\n\n", "\n", str_replace("\r", "\n", $content)));
     $success = strtolower($data[0]) === 'yes';
     $message = count($data) > 1 && $data[1] ? $data[1] : null;
     if ($success) {
         $this->username = $message;
     } else {
         $this->error = $message;
     }
     return $success;
 }
Exemple #16
0
 private function decompressContent(\Buzz\Message\Response $response)
 {
     if (!($content_encoding = $response->getHeader('Content-Encoding'))) {
         return;
     }
     $content = $response->getContent();
     if (strpos($content_encoding, 'deflate') !== false) {
         $content = gzuncompress($content);
     }
     if (strpos($content_encoding, 'gzip') !== false) {
         $content = gzinflate(substr($content, 10));
     }
     $response->setContent($content);
 }
 protected function handleException(Response $response)
 {
     $json_string = $response->getContent();
     $output = json_decode($json_string, true);
     if (isset($output['error']['message']) && isset($output['error']['type']) && isset($output['error']['code'])) {
         $clazz = sprintf('Facebook\\Exception\\%s', $output['error']['type']);
         if (class_exists($clazz)) {
             throw new $clazz($output['error']['message'], $output['error']['code']);
         } else {
             throw new \Exception($output['error']['message'], $output['error']['code']);
         }
     } else {
         throw new \Exception(sprintf('Unknown error: %s', $json_string));
     }
 }
 /**
  * {@inheritdoc}
  */
 protected function validateResponse(Response $response)
 {
     $content = $response->getContent();
     $values = unserialize($content);
     $success = true;
     if (!empty($values) && is_array($values)) {
         $this->username = $values['user'];
         foreach ($values['attributes'] as $key => $value) {
             $this->attributes[$key] = $value;
         }
     } else {
         $success = false;
     }
     return $success;
 }
Exemple #19
0
 /**
  * Converts a buzz response to a pinterest response.
  *
  * @param Request      $request      The request.
  * @param BuzzResponse $buzzResponse The buzz response.
  *
  * @return Response The response.
  */
 private static function convertResponse(Request $request, BuzzResponse $buzzResponse)
 {
     $statusCode = $buzzResponse->getStatusCode();
     $rawBody = (string) $buzzResponse->getContent();
     $rawHeaders = $buzzResponse->getHeaders();
     $headers = array();
     foreach ($rawHeaders as $header) {
         if (stristr($header, 'HTTP/1.')) {
             continue;
         }
         list($key, $value) = explode(': ', $header);
         $headers[$key] = $value;
     }
     return new Response($request, $statusCode, $rawBody, $headers);
 }
 /**
  * @param Response $response
  * @return mixed
  * @throws BadAuthentificationException
  */
 public function handleResponse(Response $response)
 {
     $data = json_decode($response->getContent(), true);
     if ($response->getStatusCode() != 200) {
         if (!$data) {
             $e = new BadAuthentificationException("Authentification request has failed : {$response}");
             $e->setOAuthErrorName("undefined");
             $e->setOAuthErrorDescription("Can't handle API response.");
             throw $e;
         }
         $e = new BadAuthentificationException(sprintf("OAuth exception. %s : %s", $data['error'], $data['error_description']));
         $e->setOAuthErrorName($data['error']);
         $e->setOAuthErrorDescription($data['error_description']);
         throw $e;
     }
     return $data;
 }
Exemple #21
0
    public function testFromString()
    {
        $content = <<<EOF
This is the body.

More body!

EOF;
        $response = new Response();
        $response->fromString(<<<EOF
HTTP/1.0 200 OK
Content-Type: text/plain

{$content}
EOF
);
        $this->assertEquals(2, count($response->getHeaders()));
        $this->assertEquals($content, $response->getContent());
    }
 /**
  * @param Response $response
  * @return ProxyMediaInterface
  *
  * @throws MediaStorageClientManagerNotFoundException
  * @throws MediaStorageClientProxyMediaManagerException
  */
 public function createFromResponse(Response $response)
 {
     if ($response && $response->isOk()) {
         $content = json_decode($response->getContent(), true);
         if ($content && !json_last_error() && is_array($content)) {
             $content = new ArrayCollection($content);
         } else {
             throw new MediaStorageClientProxyMediaManagerException('Client not response new value');
         }
     } elseif ($response->getStatusCode() == 404) {
         throw new MediaStorageClientManagerNotFoundException(sprintf('Unable to find the object'));
     } else {
         throw new MediaStorageClientProxyMediaManagerException('Client response code: ' . $response->getStatusCode());
     }
     $proxyMedia = $this->create();
     $proxyMedia->setReferenceFull($content->get('reference_full'));
     $proxyMedia->setName($content->get('name'));
     $proxyMedia->setProviderMetadata($content->toArray());
     return $proxyMedia;
 }
Exemple #23
0
 /**
  * @param  Response $response
  * @param  string                $method
  * @param  array                 $arguments
  * @return \stdClass
  * @throws \RuntimeException
  */
 protected function validateResponse($response, $method, $arguments)
 {
     if (!in_array($response->getStatusCode(), array(200, 401, 409))) {
         throw new \RuntimeException('Unexpected response received from Transmission');
     }
     if ($response->getStatusCode() == 401) {
         throw new \RuntimeException('Access to Transmission requires authentication');
     }
     if ($response->getStatusCode() == 409) {
         $this->setToken($response->getHeader(self::TOKEN_HEADER));
         return $this->call($method, $arguments);
     }
     return json_decode($response->getContent());
 }
 /**
  * @param Response $response
  *
  * @return stdClass $json
  */
 protected function getContent(Response $response)
 {
     return json_decode($response->getContent());
 }
 /**
  * Parse and cache rest response for issue id
  *
  * @param  Response $response
  * @return array[Issue]
  */
 private function getIssuesFromResponse(Response $response)
 {
     $issues = array();
     $content = json_decode($response->getContent(), true);
     foreach ($content['issue'] as $issueData) {
         $issue = $this->parseIssueData($issueData['id'], $issueData);
         $issue->setProjectEntity($this->preFetchProject($issueData));
         // set prefetched project onto entity.
         try {
             $this->getWorkItemsForIssue($issue);
         } catch (APIException $E) {
             if (stripos($E->getMessage(), "is disabled") !== false) {
                 // catch "time tracking is disabled messages, handle silently."
                 // do nothing.
             } else {
                 throw $E;
             }
         }
         $this->issueCache[$issueData['id']] = $issue;
         $issues[] = $this->issueCache[$issueData['id']];
     }
     return $issues;
 }
Exemple #26
0
 /**
  * Converts a Buzz response into a PSR response.
  *
  * @param BuzzResponse $response
  *
  * @return ResponseInterface
  */
 private function createResponse(BuzzResponse $response)
 {
     $body = $response->getContent();
     return $this->responseFactory->createResponse($response->getStatusCode(), null, $this->getBuzzHeaders($response), $body, number_format($response->getProtocolVersion(), 1));
 }
Exemple #27
0
 /**
  * @param Response $response
  *
  * @throws HttpException
  */
 protected function handleError(Response $response)
 {
     $body = (string) $response->getContent();
     $code = (int) $response->getStatusCode();
     $content = json_decode($response->getContent());
     throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code);
 }
 /**
  * @param \Buzz\Message\Response $response
  *
  * @throws HttpException if status not OK
  * @throws HttpException if content not json
  *
  * @return \stdClass|\stdClass[]|null
  */
 protected function getResult(Response $response)
 {
     if (false == $response->isSuccessful()) {
         throw new HttpException($response->getStatusCode(), sprintf("The api call finished with status %s but it was expected 200. Response content:\n\n%s", $response->getStatusCode(), $response->getContent()));
     }
     $content = $response->getContent();
     $result = null;
     if (false == empty($content)) {
         $result = json_decode($response->getContent());
         if (null === $result) {
             throw new LogicException(sprintf("The response status is successful but the content is not a valid json object:\n\n%s", $response->getContent()));
         }
     }
     return $result;
 }
Exemple #29
0
 /**
  * @param \Buzz\Message\Response $response
  * @throws \InvalidArgumentException
  */
 private function assertRequestIsSuccessful(\Buzz\Message\Response $response)
 {
     $data = json_decode($response->getContent(), true);
     if (!$response->isSuccessful() || !isset($data['success']) || $data['success'] != "true") {
         //XXX Invent Exception fitting here
         throw new \InvalidArgumentException($response->getContent());
     }
 }
 /**
  * {@inheritDoc}
  */
 public function getContent()
 {
     $response = parent::getContent();
     return $response;
 }