本文整理汇总了PHP中GuzzleHttp\Stream\Stream::factory方法的典型用法代码示例。如果您正苦于以下问题:PHP Stream::factory方法的具体用法?PHP Stream::factory怎么用?PHP Stream::factory使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GuzzleHttp\Stream\Stream
的用法示例。
在下文中一共展示了Stream::factory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: createResponse
/**
* 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);
}
示例2: buildResponse
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));
}
示例3: request
/**
* {@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;
}
示例4: getClientWithBody
protected function getClientWithBody($body)
{
$client = new Client();
$mock = new Mock([new Response(200, [], Stream::factory($body))]);
$client->getEmitter()->attach($mock);
return $client;
}
示例5: testCastsToString
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);
}
示例6: after
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;
}
示例7: testRoomInstallCallbackSuccess
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);
}
示例8: testSuccessfulTranslate
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());
}
示例9: testHandlesClose
public function testHandlesClose()
{
$s = Stream::factory('foo');
$wrapped = new NoSeekStream($s);
$wrapped->close();
$this->assertFalse($wrapped->write('foo'));
}
示例10: setUp
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);
}
示例11: testGetRequestContent
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);
}
示例12: execute
/**
* @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());
}
}
示例13: sendRequest
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());
}
}
示例14: forwardIpn
/**
* @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;
}
示例15: sendPostRequest
/**
* @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);
}
}