/**
  * Create new response.
  *
  * @param int $statusCode Response status code.
  * @param array $headers Response headers.
  * @param mixed $body Response body.
  * @param array $options Options.
  *
  * @return Response
  */
 public function createResponse($statusCode, array $headers = array(), $body = null, array $options = array())
 {
     if (null !== $body) {
         $body = Stream::factory($body);
     }
     return new Response($statusCode, $headers, $body, $options);
 }
Beispiel #2
0
function buildResponse($code, array $headers = [], $body = null)
{
    if (class_exists('GuzzleHttp\\HandlerStack')) {
        return new \GuzzleHttp\Psr7\Response($code, $headers, $body);
    }
    return new \GuzzleHttp\Message\Response($code, $headers, \GuzzleHttp\Stream\Stream::factory((string) $body));
}
 /**
  * {@inheritdoc}
  */
 public function request(RequestInterface $request)
 {
     $url = (string) $request->getUri();
     $body = $request->getBody();
     $body->seek(0);
     $headers = $request->getHeaders();
     $headers['Accept'] = 'application/json';
     $headers['Content-Type'] = 'application/json';
     $req = $this->guzzle->createRequest($request->getMethod(), $url);
     $req->setHeaders($headers);
     $req->setBody(GStream::factory($body->getContents()));
     try {
         $res = $this->guzzle->send($req);
     } catch (RequestException $e) {
         // Guzzle will throw exceptions for 4xx and 5xx responses, so we catch
         // them here and quietly get the response object.
         $res = $e->getResponse();
         if (!$res) {
             throw $e;
         }
     }
     $response = (new Response(new Stream('php://memory', 'w')))->withStatus($res->getStatusCode(), $res->getReasonPhrase());
     $response->getBody()->write((string) $res->getBody());
     return $response;
 }
 protected function getClientWithBody($body)
 {
     $client = new Client();
     $mock = new Mock([new Response(200, [], Stream::factory($body))]);
     $client->getEmitter()->attach($mock);
     return $client;
 }
Beispiel #5
0
 public function testCastsToString()
 {
     $m = new Request('GET', 'http://foo.com');
     $m->setHeader('foo', 'bar');
     $m->setBody(Stream::factory('baz'));
     $this->assertEquals("GET / HTTP/1.1\r\nHost: foo.com\r\nfoo: bar\r\n\r\nbaz", (string) $m);
 }
 public function after(GuzzleCommandInterface $command, RequestInterface $request, Operation $operation, array $context)
 {
     foreach ($this->buffered as $param) {
         $this->visitWithValue($command[$param->getName()], $param, $command);
     }
     $this->buffered = array();
     $additional = $operation->getAdditionalParameters();
     if ($additional && $additional->getLocation() == $this->locationName) {
         foreach ($command->toArray() as $key => $value) {
             if (!$operation->hasParam($key)) {
                 $additional->setName($key);
                 $this->visitWithValue($value, $additional, $command);
             }
         }
         $additional->setName(null);
     }
     // If data was found that needs to be serialized, then do so
     $xml = null;
     if ($this->writer) {
         $xml = $this->finishDocument($this->writer);
     } elseif ($operation->getData('xmlAllowEmpty')) {
         // Check if XML should always be sent for the command
         $writer = $this->createRootElement($operation);
         $xml = $this->finishDocument($writer);
     }
     if ($xml) {
         $request->setBody(Stream::factory($xml));
         // Don't overwrite the Content-Type if one is set
         if ($this->contentType && !$request->hasHeader('Content-Type')) {
             $request->setHeader('Content-Type', $this->contentType);
         }
     }
     $this->writer = null;
 }
 public function testRoomInstallCallbackSuccess()
 {
     $this->createTestConfig();
     $data = ['oauthId' => '__oauthId__', 'oauthSecret' => '__oauthSecret__', 'groupId' => '34531', 'roomId' => '986531'];
     $authResponse = new Response(200, [], Stream::factory(json_encode(['access_token' => '__authToken__', 'expires_in' => 3600])));
     $httpClientMock = $this->getMock('GuzzleHttp\\Client', ['send']);
     $httpClientMock->expects($this->once())->method('send')->will($this->returnValue($authResponse));
     $clientMock = $this->getMock('Venyii\\HipChatCommander\\Api\\Client', null, ['__clientId__', $this->app['hc.config'], $this->app['hc.api_registry'], $httpClientMock, $this->app['logger']]);
     $this->app['hc.api_client'] = $this->app->protect(function () use($clientMock) {
         return $clientMock;
     });
     $client = $this->createClient();
     $client->request('POST', '/cb/install', [], [], [], json_encode($data));
     $response = $client->getResponse();
     $this->assertLoggerHasRecord('Got authToken "__authToken__"', Logger::DEBUG);
     $this->assertEquals(200, $response->getStatusCode());
     $creds = $this->app['hc.api_registry']->getClient('__oauthId__');
     $installDate = $creds['date'];
     $expiresDate = $creds['credentials']['expires'];
     unset($creds['date']);
     unset($creds['credentials']['expires']);
     $this->assertEquals(['groupId' => 34531, 'roomId' => 986531, 'credentials' => ['oauthId' => '__oauthId__', 'oauthSecret' => '__oauthSecret__', 'authToken' => '__authToken__']], $creds);
     $this->assertInstanceOf('DateTime', $installDate);
     $this->assertInstanceOf('DateTime', $expiresDate);
 }
 public function testSuccessfulTranslate()
 {
     $client = new Client();
     $content = Stream::factory('{"access_token":"123"}');
     $mock = new Mock([new Response(200, [], $content), new Response(200, [], Stream::factory($this->xmlResponse))]);
     $client->getEmitter()->attach($mock);
     $translator = new \badams\MicrosoftTranslator\MicrosoftTranslator($client);
     $translator->setClient('client_id', 'client_secret');
     $results = $translator->getTranslationsArray(['Hello', 'World'], 'de', 'en');
     $this->assertTrue(is_array($results));
     $this->assertEquals(2, count($results));
     $this->assertInstanceOf('\\badams\\MicrosoftTranslator\\Responses\\GetTranslationsResponse', $results[0]);
     $this->assertInstanceOf('\\badams\\MicrosoftTranslator\\Language', $results[0]->getFrom());
     $this->assertEquals('en', (string) $results[0]->getFrom());
     $translations = $results[0]->getTranslations();
     $this->assertEquals(2, count($translations));
     $this->assertInstanceOf('\\badams\\MicrosoftTranslator\\Responses\\TranslationMatch', $translations[0]);
     $this->assertEquals('Hallo', $translations[0]->getTranslatedText());
     $this->assertEquals(5, $translations[0]->getRating());
     $this->assertEquals(100, $translations[0]->getMatchDegree());
     $this->assertEquals(null, $translations[0]->getError());
     $this->assertEquals(0, $translations[0]->getCount());
     $this->assertEquals('', $translations[0]->getMatchedOriginalText());
     $this->assertEquals('Hello', $translations[1]->getTranslatedText());
     $this->assertEquals(4, $translations[1]->getRating());
     $this->assertEquals(70, $translations[1]->getMatchDegree());
     $this->assertEquals(null, $translations[1]->getError());
     $this->assertEquals(1, $translations[1]->getCount());
     $this->assertEquals('Hello', $translations[1]->getMatchedOriginalText());
 }
 public function testHandlesClose()
 {
     $s = Stream::factory('foo');
     $wrapped = new NoSeekStream($s);
     $wrapped->close();
     $this->assertFalse($wrapped->write('foo'));
 }
Beispiel #10
0
 public function setUp()
 {
     $this->mock = new Mock([new Response(200, ['Content-Type' => 'javascript'], Stream::factory('{"status":"success"}')), new Response(200, ['Content-Type' => 'javascript'], Stream::factory('{"status":"error"}'))]);
     $this->submail = new Submail('key', 'secret');
     $client = Sender::getHttpClient();
     $client->getEmitter()->attach($this->mock);
 }
Beispiel #11
0
 public function testGetRequestContent()
 {
     $putRequest = new PutRequest();
     $stream = Stream::factory('[1,1,1]');
     $query = $this->getMock('GuzzleHttp\\Query');
     $httpRequest = $this->getMock('GuzzleHttp\\Message\\RequestInterface');
     $httpResponse = $this->getMock('GuzzleHttp\\Message\\ResponseInterface');
     $this->client->expects($this->once())->method('createRequest')->with($this->equalTo('PUT'), $this->equalTo('/types/default/buckets/test_bucket/keys/1'))->willReturn($httpRequest);
     $this->client->expects($this->once())->method('send')->with($this->equalTo($httpRequest))->willReturn($httpResponse);
     $httpRequest->expects($this->once())->method('getQuery')->willReturn($query);
     $httpResponse->expects($this->any())->method('getStatusCode')->willReturn(200);
     $httpResponse->expects($this->once())->method('getBody')->willReturn($stream);
     $httpResponse->expects($this->once())->method('getHeader')->with($this->equalTo('X-Riak-Vclock'))->willReturn('vclock-hash');
     $httpRequest->expects($this->exactly(3))->method('setHeader')->will($this->returnValueMap([['Accept', ['multipart/mixed', '*/*'], $query], ['Content-Type', 'application/json', $query], ['X-Riak-Vclock', 'vclock-hash', $query]]));
     $httpRequest->expects($this->once())->method('setBody')->with($this->equalTo('[1,1,1]'));
     $httpResponse->method('getHeaders')->willReturn(['Content-Type' => 'application/json', 'Last-Modified' => 'Sat, 03 Jan 2015 01:46:34 GMT']);
     $content = new Content();
     $putRequest->bucket = 'test_bucket';
     $putRequest->type = 'default';
     $putRequest->key = '1';
     $putRequest->returnBody = true;
     $putRequest->content = $content;
     $putRequest->vClock = 'vclock-hash';
     $content->contentType = 'application/json';
     $content->value = '[1,1,1]';
     $response = $this->instance->send($putRequest);
     $this->assertInstanceOf('Riak\\Client\\Core\\Message\\Kv\\PutResponse', $response);
     $this->assertEquals('vclock-hash', $response->vClock);
     $this->assertCount(1, $response->contentList);
     $this->assertEquals('[1,1,1]', $response->contentList[0]->value);
     $this->assertEquals(1420249594, $response->contentList[0]->lastModified);
     $this->assertEquals('application/json', $response->contentList[0]->contentType);
 }
 /**
  * @inheritdoc
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $platformId = $input->getOption('platform_id');
     /** @var Callable $clientFactory */
     $clientFactory = $this->getContainer()['client_factory'];
     /** @var Client $client */
     $client = $clientFactory($platformId);
     try {
         $request = $client->createRequest($input->getOption('http_verb'), 'api/rest/' . ltrim($input->getArgument('http_resource'), '/'));
         $output->writeln('Sending: ' . $request->getUrl());
         if ($input->getOption('request_content')) {
             if (!is_string($input->getOption('request_type'))) {
                 throw new Exception('request_type (-t) is a required parameter when request_content (-c) is used');
             }
             $body = Stream::factory($input->getOption('request_content'));
             $request->setBody($body);
             $request->setHeader('Content-Type', $this->parseContentType($input->getOption('request_type')));
             $output->writeln('Request body: ' . $body);
         }
         /** @var ResponseInterface $response */
         $response = $client->send($request);
         $output->writeln(json_encode($response->json(), JSON_PRETTY_PRINT));
     } catch (RequestException $e) {
         $output->writeln('Request failed: ' . (string) $e->getResponse()->getBody());
         throw $e;
     } catch (Exception $e) {
         $output->writeln('Invalid request: ' . (string) $e->getMessage());
     }
 }
 private function sendRequest($uri, $postData = null)
 {
     try {
         $fullUrl = $this->url . '/v3' . $uri;
         // more info: https://curl.haxx.se/docs/caextract.html
         $verify = __DIR__ . '/../../cacert.pem';
         if (!file_exists($verify)) {
             throw new RuntimeException('cacert.pem not found: ' . $verify);
         }
         $headers = array();
         if ($postData) {
             $stream = \GuzzleHttp\Stream\Stream::factory($postData);
             $res = $this->httpClient->post($fullUrl, ['headers' => $headers, 'body' => $stream, 'auth' => [$this->username, $this->password], 'verify' => $verify]);
         } else {
             $res = $this->httpClient->get($fullUrl, ['headers' => $headers, 'auth' => [$this->username, $this->password], 'verify' => $verify]);
         }
         if ($res->getStatusCode() == 200) {
             return (string) $res->getBody();
         }
     } catch (\GuzzleHttp\Exception\RequestException $e) {
         if (!$e->getResponse()) {
             throw new NoResponseException('NO_RESPONSE', 'No response / connection error requesting ' . $fullUrl);
         }
         ErrorResponseHandler::handle($e->getResponse());
     }
 }
Beispiel #14
0
 /**
  * @param IpnEntity $ipn
  * @return bool
  */
 public function forwardIpn(IpnEntity $ipn)
 {
     $urls = $ipn->getForwardUrls();
     if (!empty($urls)) {
         $requests = [];
         foreach ($urls as $url) {
             $request = $this->guzzle->createRequest('post', $url);
             $request->setHeader($this->customHeader, $this->getKey());
             if (in_array($url, $this->disabledJsonFormatting)) {
                 $request->getQuery()->merge($ipn->toArray());
             } else {
                 $request->setHeader('content-type', 'application/json');
                 if ($this->formatter) {
                     $response = $this->formatter->formatJsonResponse($ipn);
                 } else {
                     $response = ['ipn' => $ipn->toArray()];
                 }
                 $request->setBody(Stream::factory(json_encode($response)));
             }
             $requests[] = $request;
         }
         $this->guzzle->sendAll($requests, ['parallel' => $this->maxRequests]);
         return true;
     }
     return false;
 }
 /**
  * @param string $url
  * @param mixed[]|null $body
  * @return \SlevomatZboziApi\Response\ZboziApiResponse
  */
 public function sendPostRequest($url, array $body = null)
 {
     TypeValidator::checkString($url);
     $options = ['allow_redirects' => false, 'verify' => true, 'decode_content' => true, 'expect' => false, 'timeout' => $this->timeoutInSeconds];
     $request = $this->client->createRequest('POST', $url, $options);
     $request->setHeaders([static::HEADER_PARTNER_TOKEN => $this->partnerToken, static::HEADER_API_SECRET => $this->apiSecret]);
     if ($body !== null) {
         $request->setBody(\GuzzleHttp\Stream\Stream::factory(json_encode($body)));
     }
     try {
         try {
             $response = $this->client->send($request);
             $this->log($request, $response);
             return $this->getZboziApiResponse($response);
         } catch (\GuzzleHttp\Exception\RequestException $e) {
             $response = $e->getResponse();
             $this->log($request, $response);
             if ($response !== null) {
                 return $this->getZboziApiResponse($response);
             }
             throw new \SlevomatZboziApi\Request\ConnectionErrorException('Connection to Slevomat API failed.', $e->getCode(), $e);
         }
     } catch (\GuzzleHttp\Exception\ParseException $e) {
         $this->log($request, isset($response) ? $response : null, true);
         throw new \SlevomatZboziApi\Response\ResponseErrorException('Slevomat API invalid response: invalid JSON data.', $e->getCode(), $e);
     }
 }
Beispiel #16
0
 /**
  * @param \Riak\Client\Core\Message\DataType\PutRequest $putRequest
  *
  * @return \GuzzleHttp\Message\RequestInterface
  */
 private function createHttpRequest(PutRequest $putRequest)
 {
     $request = $this->createRequest('POST', $putRequest->type, $putRequest->bucket, $putRequest->key);
     $data = $this->opConverter->convert($putRequest->op);
     $query = $request->getQuery();
     if ($putRequest->context !== null && is_array($data)) {
         $data['context'] = $putRequest->context;
     }
     if ($putRequest->w !== null) {
         $query->add('w', $putRequest->w);
     }
     if ($putRequest->dw !== null) {
         $query->add('dw', $putRequest->dw);
     }
     if ($putRequest->pw !== null) {
         $query->add('pw', $putRequest->pw);
     }
     if ($putRequest->returnBody !== null) {
         $query->add('returnbody', $putRequest->returnBody ? 'true' : 'false');
     }
     if ($putRequest->includeContext !== null) {
         $query->add('include_context', $putRequest->includeContext ? 'true' : 'false');
     }
     $request->setHeader('Accept', 'application/json');
     $request->setHeader('Content-Type', 'application/json');
     $request->setBody(Stream::factory(json_encode($data)));
     return $request;
 }
Beispiel #17
0
 public function testInflatesStreams()
 {
     $content = gzencode('test');
     $a = Stream::factory($content);
     $b = new InflateStream($a);
     $this->assertEquals('test', (string) $b);
 }
Beispiel #18
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']];
 }
Beispiel #19
0
 /**
  * @internal
  *
  * @param array $request
  *
  * @return array
  */
 public function _invokeAsArray(array $request)
 {
     $factory = $this->factory;
     // Ensure headers are by reference. They're updated elsewhere.
     $result = $factory($request, curl_init());
     $h = $result[0];
     $hd =& $result[1];
     $body = $result[2];
     Core::doSleep($request);
     try {
         // override the default body stream with the request response
         $safecurl = new SafeCurl($h);
         $body = $safecurl->execute(Core::url($request));
     } catch (Exception $e) {
         // URL wasn't safe, return empty content
         $body = '';
         $safeCurlError = $e->getMessage();
     }
     $response = ['transfer_stats' => curl_getinfo($h)];
     $response['curl']['error'] = curl_error($h);
     $response['curl']['errno'] = curl_errno($h);
     $response['transfer_stats'] = array_merge($response['transfer_stats'], $response['curl']);
     curl_close($h);
     // override default error message in case of SafeCurl error
     if (isset($safeCurlError)) {
         $response['err_message'] = $safeCurlError;
     }
     return CurlFactory::createResponse([$this, '_invokeAsArray'], $request, $response, $hd, Stream::factory($body));
 }
 public function testCastsToString()
 {
     $m = new Message();
     $m->setHeader('foo', 'bar');
     $m->setBody(Stream::factory('baz'));
     $this->assertEquals("Foo!\r\nfoo: bar\r\n\r\nbaz", (string) $m);
 }
Beispiel #21
0
 /**
  * @param  string $uri
  * @param  string $method
  * @param  array $data
  * @param  array $query_params
  * @param  string $resource
  * @param  string $action
  * @return mixed
  * @throws StreamFeedException
  */
 public function makeHttpRequest($uri, $method, $data = [], $query_params = [], $resource = '', $action = '')
 {
     $query_params['api_key'] = $this->api_key;
     $client = $this->getHttpClient();
     foreach ($this->guzzleOptions as $key => $value) {
         $client->setDefaultOption($key, $value);
     }
     $request = $client->createRequest($method, $this->client->buildRequestUrl($uri), ['timeout' => $this->client->timeout]);
     $request->setHeaders($this->getHttpRequestHeaders($resource, $action));
     $query = $request->getQuery();
     foreach ($query_params as $key => $value) {
         $query[$key] = $value;
     }
     if ($method === 'POST' || $method === 'POST') {
         $json_data = json_encode($data);
         $request->setBody(Stream::factory($json_data));
     }
     try {
         $response = $client->send($request);
     } catch (Exception $e) {
         if ($e instanceof ClientException) {
             throw new StreamFeedException($e->getResponse()->getBody());
         } else {
             throw $e;
         }
     }
     return $response->json();
 }
Beispiel #22
0
 /**
  * Method to handle the Subscribe Request to the Hub
  */
 public function subscribe()
 {
     // Start empty $hubUrl variable
     $hubUrl = '';
     // Check if the Hub URL finishes with a / or not to be able to create the correct subscribe URL
     if (preg_match("/\\/\$/", $this->current_options['hub_url'])) {
         $hubUrl = $this->current_options['hub_url'] . 'subscribe';
     } else {
         $hubUrl = $this->current_options['hub_url'] . '/subscribe';
     }
     // Json Data needed to send to the Hub for Subscription
     $subscribeJson = json_encode(array("callbackUrl" => esc_url($this->callbackUrl), "topicId" => esc_url($this->current_options['topic_url'])), JSON_UNESCAPED_SLASHES);
     $subscribeRequest = $this->guzzleClient->createRequest('POST', $hubUrl);
     $subscribeRequest->setHeader('Content-Type', 'application/json');
     $subscribeRequest->setBody(Stream::factory($subscribeJson));
     $subscribeResponse = $this->guzzleClient->send($subscribeRequest);
     // Check if Response is 200, 202 or 204 and add a log message otherwise log error message
     if (in_array($subscribeResponse->getStatusCode(), array(200, 202, 204))) {
         HubLogger::log('Your Subscription request is being processed. Check back later to see if you are fully Subscribed', $subscribeResponse->getStatusCode());
         return true;
     } else {
         HubLogger::error('Error issuing Subscribe request to the Hub. Please make sure all your details are correct', $subscribeResponse->getStatusCode());
         return false;
     }
 }
 public function testCanSendNormalRequest()
 {
     $request = new Request('GET', 'http://foo.com');
     $body = Stream::factory($this->fakeRawBody);
     $response = new Response(200, $this->fakeHeadersAsArray, $body);
     $this->guzzleMock->shouldReceive('createRequest')->once()->with('GET', 'http://foo.com/', m::on(function ($arg) {
         // array_diff_assoc() will sometimes trigger error on child-arrays
         if (['X-foo' => 'bar'] !== $arg['headers']) {
             return false;
         }
         unset($arg['headers']);
         $caInfo = array_diff_assoc($arg, ['body' => 'foo_body', 'timeout' => 123, 'connect_timeout' => 10]);
         if (count($caInfo) !== 1) {
             return false;
         }
         if (1 !== preg_match('/.+\\/certs\\/DigiCertHighAssuranceEVRootCA\\.pem$/', $caInfo['verify'])) {
             return false;
         }
         return true;
     }))->andReturn($request);
     $this->guzzleMock->shouldReceive('send')->once()->with($request)->andReturn($response);
     $response = $this->guzzleClient->send('http://foo.com/', 'GET', 'foo_body', ['X-foo' => 'bar'], 123);
     $this->assertInstanceOf('Facebook\\Http\\GraphRawResponse', $response);
     $this->assertEquals($this->fakeRawBody, $response->getBody());
     $this->assertEquals($this->fakeHeadersAsArray, $response->getHeaders());
     $this->assertEquals(200, $response->getHttpResponseCode());
 }
Beispiel #24
0
 /**
  * Queues a mock response to be returned by guzzle
  * @param int    $code Return code to be returned by mock api
  * @param string $body Http body to be returned by mock api
  */
 private function getsData($code, $body)
 {
     if (!$this->mockData) {
         throw new Exception('Can\'t have individual mocks when data is set to always return');
     }
     $this->mockData->addResponse(new Response($code, [], Stream::factory($body)));
 }
    public function testRepresentation()
    {
        $stream = Stream::factory('{
			"errors": {
				"contact": [
					{
						"error": {
							"code": "E0001",
							"field": "last_name",
							"description": "Please provide contact\'s last name."
						}
					}
				]
			}
		}');
        $response = new Response(422, [], $stream);
        $exception = new RepresentationErrorException('', new Request('POST', ''), $response);
        $this->assertTrue($exception->hasErrors());
        $this->assertTrue($exception->hasErrors('last_name'));
        $this->assertFalse($exception->hasErrors('non_existing'));
        $this->assertCount(1, $exception->getErrors());
        $this->assertCount(1, $exception->getErrors('last_name'));
        $this->assertCount(0, $exception->getErrors('non_existing'));
        $this->assertEquals('E0001', $exception->getErrors()[0]->getCode());
        $this->assertEquals('last_name', $exception->getErrors()[0]->getField());
        $this->assertEquals('Please provide contact\'s last name.', $exception->getErrors()[0]->getDescription());
    }
    /**
     * @test
     */
    public function createShouldParseAsXmlWhenStatusCodeIs400()
    {
        $xml = <<<'XML'
<?xml version="1.0" encoding="UTF-8"?>
<errors>
    <error>
        <code>11004</code>
        <message>Currency is required.</message>
    </error>
    <error>
        <code>11005</code>
        <message>Currency invalid value: 100</message>
    </error>
</errors>
XML;
        $message = <<<'MESSAGE'
Some errors occurred:
[11004] Currency is required.
[11005] Currency invalid value: 100
MESSAGE;
        $response = new Response(400, [], Stream::factory($xml));
        $exception = PagSeguroException::create($response);
        $this->assertInstanceOf(PagSeguroException::class, $exception);
        $this->assertEquals($message, $exception->getMessage());
    }
 public function testReadsFromRequestBody()
 {
     $body = Stream::factory('foo');
     $t = new Transaction(new Client(), new Request('PUT', 'http://httbin.org', [], $body));
     $m = new RequestMediator($t, new MessageFactory());
     $this->assertEquals('foo', $m->readRequestBody(null, null, 3));
 }
Beispiel #28
0
 /**
  * @param \Riak\Client\Core\Message\Kv\PutRequest $putRequest
  *
  * @return \GuzzleHttp\Message\RequestInterface
  */
 public function createHttpRequest(PutRequest $putRequest)
 {
     $method = $putRequest->key ? 'PUT' : 'POST';
     $request = $this->createRequest($method, $putRequest->type, $putRequest->bucket, $putRequest->key);
     $query = $request->getQuery();
     $content = $putRequest->content;
     $contentType = $content->contentType;
     $value = $content->value;
     foreach ($content->indexes as $name => $indexes) {
         $request->addHeader("X-Riak-Index-{$name}", $indexes);
     }
     foreach ($content->metas as $name => $meta) {
         $request->addHeader("X-Riak-Meta-{$name}", $meta);
     }
     $request->setHeader('Accept', ['multipart/mixed', '*/*']);
     $request->setHeader('Content-Type', $contentType);
     $request->setBody(Stream::factory($value));
     if ($putRequest->w !== null) {
         $query->add('w', $putRequest->w);
     }
     if ($putRequest->dw !== null) {
         $query->add('dw', $putRequest->dw);
     }
     if ($putRequest->pw !== null) {
         $query->add('pw', $putRequest->pw);
     }
     if ($putRequest->returnBody !== null) {
         $query->add('returnbody', $putRequest->returnBody ? 'true' : 'false');
     }
     if ($putRequest->vClock !== null) {
         $request->setHeader('X-Riak-Vclock', $putRequest->vClock);
     }
     return $request;
 }
Beispiel #29
0
 public function testHasStream()
 {
     $s = Stream::factory('foo');
     $e = new SeekException($s, 10);
     $this->assertSame($s, $e->getStream());
     $this->assertContains('10', $e->getMessage());
 }
Beispiel #30
0
 /**
  *
  */
 public function call($verb, $host, $port, $uri, $headers = null, $query = null, $body = null, $statusCode = null)
 {
     // Fix headers, query and body
     $headers = \z\conf($headers);
     $query = \z\conf($query);
     if (is_null($body) === true) {
         $body = '';
     }
     // Body must be a string
     if (is_string($body) === false) {
         \z\e(EXCEPTION_HTTP_BODY_NOT_VALID, ['body' => json_encode($body, true), 'type' => gettype($body)]);
     }
     // Build the HTTP client
     $client = new \GuzzleHttp\Client(['base_url' => $host]);
     // Build the request
     $request = $client->createRequest($verb, $uri, ['exceptions' => false]);
     // Setup the request
     $request->setPort($port);
     $request->setHeaders($headers);
     $request->setQuery($query);
     $request->setBody(\GuzzleHttp\Stream\Stream::factory($body));
     // Log
     \z\logger()->debug($request);
     // Send the request
     $response = $client->send($request);
     // Log
     \z\logger()->debug($response);
     // Did it succeed?
     if (is_null($statusCode) === false && (int) $statusCode !== (int) $response->getStatusCode()) {
         \z\e(EXCEPTION_HTTP_STATUS_CODE_NOT_VALID, ['expected' => $statusCode, 'actual' => $response->getStatusCode(), 'request' => $request->__toString(), 'response' => $response->__toString()]);
     }
     // Build the result
     $result = $response->getBody();
     return $result;
 }