Example #1
0
 /**
  * @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());
 }
 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());
 }
 /**
  * @param Response $response
  *
  * @return string
  */
 protected static function createMessage(Response $response)
 {
     if ($response->getStatusCode() != 400) {
         return '[' . $response->getStatusCode() . '] A HTTP error has occurred: ' . $response->getBody(true);
     }
     $message = 'Some errors occurred:';
     foreach ($response->xml()->error as $error) {
         $message .= PHP_EOL . '[' . (string) $error->code . '] ' . (string) $error->message;
     }
     return $message;
 }
Example #4
0
 protected function handleResponse(Response $response)
 {
     $code = $response->getStatusCode();
     if ($code == 200) {
         return json_decode($response->getBody()->getContents(), true);
     }
     if ($code == 401 && $this->requiresToken) {
         // Unauthorized, invalidate token
         $this->tokenStore->storeToken(null);
     }
     throw new ApiException('Request failed, received the following status: ' . $response->getStatusCode() . ' Body: ' . $response->getBody()->getContents());
 }
Example #5
0
 /**
  * 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();
 }
Example #6
0
 /**
  * @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;
 }
Example #7
0
 /**
  * @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;
 }
Example #8
0
 public function formatProvider()
 {
     $request = new Request('PUT', '/', ['x-test' => 'abc'], Stream::factory('foo'));
     $response = new Response(200, ['X-Baz' => 'Bar'], Stream::factory('baz'));
     $err = new RequestException('Test', $request, $response);
     return [['{request}', [$request], (string) $request], ['{response}', [$request, $response], (string) $response], ['{request} {response}', [$request, $response], $request . ' ' . $response], ['{request} {response}', [$request], $request . ' '], ['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"], ['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"], ['{res_headers}', [$request], 'NULL'], ['{req_body}', [$request], 'foo'], ['{res_body}', [$request, $response], 'baz'], ['{res_body}', [$request], 'NULL'], ['{method}', [$request], $request->getMethod()], ['{url}', [$request], $request->getUrl()], ['{resource}', [$request], $request->getResource()], ['{req_version}', [$request], $request->getProtocolVersion()], ['{res_version}', [$request, $response], $response->getProtocolVersion()], ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHost()], ['{hostname}', [$request, $response], gethostname()], ['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()], ['{code}', [$request, $response], $response->getStatusCode()], ['{code}', [$request], 'NULL'], ['{phrase}', [$request, $response], $response->getReasonPhrase()], ['{phrase}', [$request], 'NULL'], ['{error}', [$request, $response, $err], 'Test'], ['{error}', [$request], 'NULL'], ['{req_header_x-test}', [$request], 'abc'], ['{req_header_x-not}', [$request], ''], ['{res_header_X-Baz}', [$request, $response], 'Bar'], ['{res_header_x-not}', [$request, $response], ''], ['{res_header_X-Baz}', [$request], 'NULL']];
 }
Example #9
0
 /**
  * Taken from Mink\BrowserKitDriver
  *
  * @param Response $response
  *
  * @return \Symfony\Component\BrowserKit\Response
  */
 protected function createResponse(Response $response)
 {
     $contentType = $response->getHeader('Content-Type');
     $matches = null;
     if (!$contentType or strpos($contentType, 'charset=') === false) {
         $body = $response->getBody(true);
         if (preg_match('/\\<meta[^\\>]+charset *= *["\']?([a-zA-Z\\-0-9]+)/i', $body, $matches)) {
             $contentType .= ';charset=' . $matches[1];
         }
         $response->setHeader('Content-Type', $contentType);
     }
     $headers = $response->getHeaders();
     $status = $response->getStatusCode();
     $matchesMeta = null;
     $matchesHeader = null;
     $isMetaMatch = preg_match('/\\<meta[^\\>]+http-equiv="refresh" content="(\\d*)\\s*;?\\s*url=(.*?)"/i', $response->getBody(true), $matchesMeta);
     $isHeaderMatch = preg_match('~(\\d*);?url=(.*)~', (string) $response->getHeader('Refresh'), $matchesHeader);
     $matches = $isMetaMatch ? $matchesMeta : $matchesHeader;
     if (!empty($matches) && (empty($matches[1]) || $matches[1] < $this->refreshMaxInterval)) {
         $uri = $this->getAbsoluteUri($matches[2]);
         $partsUri = parse_url($uri);
         $partsCur = parse_url($this->getHistory()->current()->getUri());
         foreach ($partsCur as $key => $part) {
             if ($key === 'fragment') {
                 continue;
             }
             if (!isset($partsUri[$key]) || $partsUri[$key] !== $part) {
                 $status = 302;
                 $headers['Location'] = $uri;
                 break;
             }
         }
     }
     return new BrowserKitResponse($response->getBody(), $status, $headers);
 }
 protected function handleResponse(Response $response)
 {
     if ($response->getStatusCode() == 200) {
         return $response->getBody()->getContents();
     }
     throw new ApiException('Request failed, received the following status: ' . $response->getStatusCode() . ' Body: ' . $response->getBody()->getContents());
 }
Example #11
0
 function debug(\GuzzleHttp\Message\Response $response)
 {
     $this->dump_respuesta = 'status: ' . $response->getStatusCode() . "<br/>body: <br/>" . $response->getBody();
     //un string encodeado utf-8
     $this->dump_url = $response->getEffectiveUrl();
     //un string encodeado utf-8
 }
Example #12
0
 /**
  * {@inheritdoc}
  */
 public function status()
 {
     if ($this->response) {
         return $this->response->getStatusCode();
     }
     return false;
 }
Example #13
0
 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);
 }
Example #14
0
 /**
  * @param Response $response
  * @return \GuzzleHttp\Stream\StreamInterface|mixed|null|string
  * @throws ApiException
  */
 protected function handleResponse(Response $response)
 {
     if ($response->getStatusCode() == 200) {
         $stream = $response->getBody();
         if ($this->returnStream == true) {
             return $stream;
         } else {
             return parent::handleResponse($response);
         }
     }
     throw new ApiException('Request failed, received the following status: ' . $response->getStatusCode() . ' Body: ' . $response->getBody()->getContents());
 }
Example #15
0
 private function validateStatusCode(\GuzzleHttp\Message\Response $response, Spec\Response $responseSpec, UseCaseValidationReport $report)
 {
     if ($responseSpec->getStatusCode()) {
         $expectedCode = $responseSpec->getStatusCode();
         $actualCode = $response->getStatusCode();
         if ($expectedCode !== $actualCode) {
             $message = sprintf("\t\t<error>Response code should be %s actual value is %s</error>", $expectedCode, $actualCode);
             $this->addViolation($message);
             $report->setStatusCodeViolation($message);
         }
     }
 }
Example #16
0
 /**
  * @param \GuzzleHttp\Message\Response $response
  */
 function __construct($response)
 {
     parent::__construct($response->getStatusCode(), $response->getHeaders(), $response->getBody());
     $jsonBody = $this->json();
     if (array_key_exists("code", $jsonBody)) {
         $this->internal_code = $jsonBody["code"];
         $this->internal_message = $jsonBody["message"];
         $this->internal_type = $jsonBody["type"];
     }
     if (array_key_exists("atoken", $jsonBody) || array_key_exists("uid", $jsonBody)) {
         $this->internal_code = 200;
         $this->internal_type = $jsonBody["type"] = "oauthResponse";
     }
 }
Example #17
0
 /**
  * @param GuzzleResponse $guzzleResponse
  *
  * @return Response
  */
 protected function createResponseFromGuzzleResponse(GuzzleResponse $guzzleResponse)
 {
     $content = null;
     if ($guzzleResponse->getBody() !== null) {
         $content = $guzzleResponse->getBody()->getContents();
     }
     $response = new Response($content, $guzzleResponse->getStatusCode());
     $response->setHeaders($guzzleResponse->getHeaders());
     $deniedHeaders = array('transfer-encoding', 'x-powered-by', 'content-length', 'content-encoding');
     foreach ($deniedHeaders as $headerName) {
         $response->removeHeader($headerName);
     }
     return $response;
 }
Example #18
0
File: Client.php Project: reliv/git
 protected function checkStatusCodes(Response $response)
 {
     $statusCode = $response->getStatusCode();
     switch ($statusCode) {
         case 400:
             throw new NotFoundException('There was no Git server found at: ' . $this->uri);
         case 403:
             throw new NotAuthorizedException('Unable to login to Git at: ' . $this->uri . '  Please check your login credentials and try again.');
         case 301:
         case 200:
             return true;
         default:
             throw new InvalidResponseException('The server returned an unknown response. Uri: ' . $this->uri);
     }
 }
Example #19
0
 /**
  * Construct a Ping response from an HTTP response.
  *
  * @param Response $response
  */
 public function __construct(Response $response)
 {
     $this->response = $response;
     $this->status = $response->getStatusCode();
     $this->error = null;
     $this->xml = null;
     $this->body = $response->getBody();
     try {
         $this->xml = $response->xml();
     } catch (Exception $ex) {
         $this->error = $ex->getMessage();
     } catch (XmlParseException $ex) {
         $this->error = $ex->getMessage();
     }
 }
Example #20
0
 /**
  * Taken from Mink\BrowserKitDriver
  *
  * @param Response $response
  *
  * @return \Symfony\Component\BrowserKit\Response
  */
 protected function createResponse(Response $response)
 {
     $contentType = $response->getHeader('Content-Type');
     if (!$contentType or strpos($contentType, 'charset=') === false) {
         $body = $response->getBody(true);
         if (preg_match('/\\<meta[^\\>]+charset *= *["\']?([a-zA-Z\\-0-9]+)/i', $body, $matches)) {
             $contentType .= ';charset=' . $matches[1];
         }
         $response->setHeader('Content-Type', $contentType);
     }
     $headers = $response->getHeaders();
     $status = $response->getStatusCode();
     if (preg_match('/\\<meta[^\\>]+http-equiv="refresh" content=".*?url=(.*?)"/i', $response->getBody(true), $matches)) {
         $status = 302;
         $headers['Location'] = $matches[1];
     }
     if (preg_match('~url=(.*)~', (string) $response->getHeader('Refresh'), $matches)) {
         $status = 302;
         $headers['Location'] = $matches[1];
     }
     return new BrowserKitResponse($response->getBody(), $status, $headers);
 }
 /**
  * @param $response HttpResponse
  *
  * @throws ServerException
  */
 private function getGuzzleResponseData($response)
 {
     if (!is_a($response, 'GuzzleHttp\\Message\\Response')) {
         $this->splitResponseToHeadersArrayAndBody($response);
         $response = new Response($this->status, $this->headers, null, []);
         $this->body = (string) $this->body;
         //            $this->status = (int) explode(' ', $this->status)[1];
         $statusLineArray = explode(" ", trim($this->headers['status'][0]));
         $this->status = (int) $statusLineArray[1];
     } else {
         $this->status = $response->getStatusCode();
         $this->body = (string) $response->getBody();
         $response->requestHandler = $this->request->requestHandler;
     }
     $this->headers = $response->getHeaders();
     if ($this->verboseExtractStatusLine === true) {
         $this->getVerboseStatusLine($response);
     }
     if (in_array(intval($this->status), $this->enabledHttpServerExceptions)) {
         $this->getVerboseStatusLine($response);
         throw new ServerException($this->statusPhrase, $this->status);
     }
 }
 /**
  * Transfoms the response body (json) into an array we can more easily
  * work with.
  *
  * @param \GuzzleHttp\Message\Response|false $response
  *
  * @return array
  */
 public function getResponseArray($response)
 {
     $return = [];
     if (!$response instanceof \GuzzleHttp\Message\Response) {
         $this->errors[] = ['source' => 'client', 'attribute' => null, 'kind' => 'networking', 'message' => 'no response'];
         return $return;
     }
     /**
      * add error for bad status codes
      */
     $code = $response->getStatusCode();
     $errorCodes = [404, 401, 500];
     if (in_array($code, $errorCodes)) {
         $this->errors[] = ['source' => 'client', 'attribute' => null, 'kind' => 'status_code', 'message' => 'Bad status code: ' . $code];
     }
     $body = $response->getBody();
     $body = trim((string) $body);
     /**
      * Return early if we have an empty body, which we can't turn into an array
      * anyway. This happens in cases where the API returns a 404, and possibly
      * other status codes.
      */
     if (empty($body)) {
         return $return;
     }
     $return = json_decode($body, true);
     // set errors, if any
     if (!empty($return['result']['errors'])) {
         foreach ($return['result']['errors'] as $error) {
             $this->errors[] = $error;
         }
     }
     /**
      * NOTE: There is also, maybe, an errors array nested in $return['meta']['errors']
      *       Why is this API so inconsistent???!!!!!
      */
     return $return;
 }
Example #23
0
 protected function createResponse(GuzzleResponse $response)
 {
     $headers = $response->getHeaders();
     return new Response($response->getBody(true), $response->getStatusCode(), $headers);
 }
Example #24
0
 /**
  * Given: A developer API key
  * When: API is queried for AreAnyGamesInProgress
  * Then: Expect a 200 response with an array of 1 entry, that entry containing the string true or false
  *
  * @group Unit
  * @small
  */
 public function testAreAnyGamesInProgressSuccessfulResponse()
 {
     $this->assertEquals('200', static::$sResponse->getStatusCode());
 }
Example #25
0
 /**
  * Given: A developer API key
  * When: API is queried for ActiveBoxScores
  * Then: Expect a 200 response
  *
  * @group Unit
  * @small
  */
 public function testSuccessfulResponse()
 {
     $this->assertEquals('200', static::$sResponse->getStatusCode());
 }
Example #26
0
 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"]);
     }
 }
 /**
  * @param Response $response
  *
  * @return UnexpectedStatusCodeException
  */
 public static function fromResponse(Response $response)
 {
     return new self($response->getStatusCode(), trim((string) $response->getBody()));
 }
Example #28
0
 /**
  * @return int
  */
 public function getStatusCode()
 {
     return $this->response->getStatusCode();
 }
 /**
  * @Then I should get a status code of :status
  */
 public function iShouldGetAStatusCodeOf($status)
 {
     PHPUnit_Framework_Assert::assertEquals($status, $this->response->getStatusCode());
 }
Example #30
-1
 public function evaluateResponse(Response $response)
 {
     $errors = [];
     try {
         // Test response code
         if (array_key_exists('response.statusCode', $this->expectations)) {
             $this->expectations['response.statusCode']->evaluate((int) $response->getStatusCode(), 'Status code was expected to be `%s` but was actually `' . $response->getStatusCode() . '`');
         }
     } catch (AssertionFailedException $e) {
         $errors[] = $e->getMessage();
     }
     // Test headers
     foreach ($this->expectations as $name => $expectation) {
         try {
             if (substr($name, 0, 8) === 'headers.') {
                 $headerName = substr($name, 8);
                 $headerValue = $response->getHeader($headerName);
                 $this->expectations['headers.' . strtolower($headerName)]->evaluate($headerValue, 'Header `' . $headerName . '` expected to be `%s` but was `%s`');
             }
         } catch (AssertionFailedException $e) {
             $errors[] = $e->getMessage();
         }
     }
     // Test body
     $body = json_decode($response->getBody(), true);
     foreach ($this->expectations as $name => $expectation) {
         try {
             if (substr($name, 0, 5) === 'body.') {
                 $keyName = substr($name, 5);
                 $keyValue = array_get($body, $keyName);
                 $this->expectations['body.' . strtolower($keyName)]->evaluate($keyValue, 'Body key `' . $keyName . '` expected to be `%s` but was `%s`');
             }
         } catch (AssertionFailedException $e) {
             $errors[] = $e->getMessage();
         }
     }
     return $errors;
 }