Exemplo n.º 1
0
 /**
  * @param Response $response
  * @return array
  */
 public static function parseQuery(Response $response)
 {
     $responseBody = $response->getBody();
     $params = [];
     parse_str($responseBody, $params);
     return $params;
 }
Exemplo n.º 2
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);
 }
Exemplo n.º 3
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']];
 }
Exemplo n.º 4
0
 /**
  * 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;
 }
Exemplo n.º 5
0
 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());
 }
Exemplo n.º 6
0
Arquivo: Client.php Projeto: reliv/git
 protected function getMessages(Response $response)
 {
     $body = (string) $response->getBody();
     if (empty($body)) {
         throw new InvalidResponseException('There was no messages returned from the server at: ' . $this->uri);
     }
     $messages = array();
     $messageCounter = 0;
     while ($body) {
         $lineLengthHex = substr($body, 0, 4);
         if (strlen($lineLengthHex) != 4) {
             throw new InvalidResponseException('A corrupt package was received from the server.  Uri: ' . $this->uri);
         }
         if ($lineLengthHex == '0000') {
             $messageCounter++;
             $body = substr_replace($body, '', 0, 4);
             continue;
         }
         $lineLength = hexdec($lineLengthHex);
         $line = substr($body, 4, $lineLength - 4);
         $body = substr_replace($body, '', 0, $lineLength);
         $messages[$messageCounter][] = trim($line);
     }
     return $messages;
 }
Exemplo n.º 7
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
 }
 protected function getResponse($body)
 {
     $stream = Stream::factory($body);
     $response = new Response(200);
     $response->setBody($stream);
     return $response;
 }
Exemplo n.º 9
0
 /**
  * Create a Response object from a stub.
  *
  * @param $stub
  * @return \GuzzleHttp\Message\Response
  */
 private function makeResponse($stub)
 {
     $response = new Response(200);
     $response->setHeader('Content-Type', 'application/json');
     $responseBody = Stream::factory(fopen('./tests/Destiny/stubs/' . $stub . '.txt', 'r+'));
     $response->setBody($responseBody);
     return $response;
 }
Exemplo n.º 10
0
 private function getMockWithCode($code, $body = null)
 {
     $response = new Response($code, array());
     if (isset($body) === true) {
         $response->setBody(Stream::factory(json_encode($body)));
     }
     $this->mockResponse = new Mock(array($response));
 }
Exemplo n.º 11
0
 /**
  * Response constructor
  *
  * @param  HttpResponse $httpResponse
  * @return self
  */
 public function __construct(HttpResponse $httpResponse)
 {
     if (stripos($httpResponse->getHeader('Content-Type'), 'text/javascript') !== false) {
         $this->_response = $this->processJson($httpResponse->getBody());
     } else {
         $this->_response = $this->processXml($httpResponse->getBody());
     }
 }
 /**
  * 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;
 }
 /**
  * Adds a mock repsonse to the response queue
  *
  * @param \GuzzleHttp\Stream\Stream $data Stream data object
  * @param int $response_code desired response code
  */
 protected function addClientMock($data, $response_code = 200)
 {
     //create a response with the data and response code
     $api_response = new Response($response_code);
     $api_response->setBody($data);
     $mock_response = $this->getMockObject();
     $mock_response->addResponse($api_response);
 }
 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);
 }
 protected function saveResponseToFile(Response &$response)
 {
     $fileName = __DIR__ . '\\json\\' . sizeof($this->fileHandles) . '.json';
     $reponseSavedToFile = file_put_contents($fileName, $response->getBody());
     if ($reponseSavedToFile != false) {
         $this->fileHandles[] = $fileName;
     }
     unset($response);
 }
Exemplo n.º 16
0
 public function validateBody(Response $response, Spec\Response $responseSpec)
 {
     $actualBody = (string) $response->getBody();
     $actualBodyData = json_decode($actualBody, true);
     if ($actualBodyData !== $responseSpec->getBody()) {
         $message = sprintf("\t\t<error>JSON in body of the response is invalid, actual:</error>\n%s\n\t\t<error>Expected:</error>\n%s", $this->getOutput()->formatArray($actualBodyData, 3), $this->getOutput()->formatArray($responseSpec->getBody(), 3));
         $this->addViolation($message);
     }
 }
Exemplo n.º 17
0
 public static function parse(\GuzzleHttp\Message\Response $response)
 {
     $body = (string) $response->getBody();
     $params = json_decode($body, true);
     if ($params !== NULL) {
         return $params;
     }
     parse_str($body, $params);
     return $params;
 }
Exemplo n.º 18
0
 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());
 }
 private function getResponse(HttpResponse $httpResponse)
 {
     $response = new Response();
     if ($httpResponse->getBody()) {
         $resp = (string) $httpResponse->getBody();
         $decoded = json_decode($resp, true);
         $response->setBody($decoded);
     }
     return $response;
 }
Exemplo n.º 20
0
 /**
  * @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;
 }
 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');
 }
Exemplo n.º 22
0
 /**
  * @test
  * @expectedException \PHPSC\PagSeguro\Client\PagSeguroException
  */
 public function handleErrorShouldRaiseExceptionWhenHostIsFromPagSeguro()
 {
     $client = new Client($this->httpClient);
     $transaction = new Transaction($this->httpClient, $this->request);
     $transaction->response = $this->response;
     $event = new Event($transaction);
     $this->request->expects($this->any())->method('getHost')->willReturn(Production::WS_HOST);
     $this->response->expects($this->any())->method('getStatusCode')->willReturn(401);
     $this->response->expects($this->any())->method('getBody')->willReturn('Unauthorized');
     $client->handleError($event);
 }
 /**
  * @return array
  */
 private function getDecodedJson()
 {
     if (!$this->decoded) {
         try {
             $this->decoded = $this->response->json();
         } catch (ParseException $e) {
             return array();
         }
     }
     return $this->decoded;
 }
Exemplo n.º 24
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);
 }
Exemplo n.º 25
0
 /**
  * @dataProvider dataUpdateUrl
  */
 public function testUpdateUrl($url, $expected)
 {
     $client = new Client();
     $response = new Response(200, []);
     $response->setEffectiveUrl($expected);
     $mock = new Mock([new Response(200, [])]);
     $client->getEmitter()->attach($mock);
     $nothing = new Nothing($client);
     $this->assertEquals($expected, $nothing->updateUrl($url));
     $this->assertEquals('', $nothing->updateContent(''));
 }
Exemplo n.º 26
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);
         }
     }
 }
Exemplo n.º 27
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());
 }
Exemplo n.º 28
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());
 }
 /**
  * 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}]");
 }
 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');
 }