本文整理汇总了PHP中GuzzleHttp\HandlerStack类的典型用法代码示例。如果您正苦于以下问题:PHP HandlerStack类的具体用法?PHP HandlerStack怎么用?PHP HandlerStack使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HandlerStack类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: __construct
public function __construct()
{
static::init();
$Stack = new HandlerStack();
$Stack->setHandler(new CurlHandler());
/**
* Здесь ставим ловушку, чтобы с помощью редиректов
* определить адрес сервера, который сможет отсылать сообщения
*/
$Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
$code = $Response->getStatusCode();
if ($code >= 301 && $code <= 303 || $code == 307 || $code == 308) {
$location = $Response->getHeader('Location');
preg_match('/https?://([^-]*-)client-s/', $location, $matches);
if (array_key_exists(1, $matches)) {
$this->cloud = $matches[1];
}
}
return $Response;
}));
/**
* Ловушка для отлова хедера Set-RegistrationToken
* Тоже нужен для отправки сообщений
*/
$Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
$header = $Response->getHeader("Set-RegistrationToken");
if (count($header) > 0) {
$this->regToken = trim(explode(';', $header[0])[0]);
}
return $Response;
}));
//$cookieJar = new FileCookieJar('cookie.txt', true);
$this->client = new Client(['handler' => $Stack, 'cookies' => true]);
}
开发者ID:tafint,项目名称:skype,代码行数:34,代码来源:Transport.php
示例2: performTestRequest
private function performTestRequest($logger, $request, $response)
{
$stack = new HandlerStack(new MockHandler([$response]));
$stack->push(LoggingMiddleware::forLogger($logger));
$handler = $stack->resolve();
return $handler($request, [])->wait();
}
开发者ID:jberkel,项目名称:tool,代码行数:7,代码来源:LoggingMiddlewareTest.php
示例3: __construct
/**
* Create the Stack and set a default handler
*/
public function __construct()
{
if (!self::$stack) {
self::$stack = HandlerStack::create();
self::$stack->setHandler(\GuzzleHttp\choose_handler());
}
}
开发者ID:rbadillap,项目名称:twitterstreaming,代码行数:10,代码来源:BaseStack.php
示例4: withDoctrineCache
public static function withDoctrineCache(Cache $doctrineCache)
{
$stack = new HandlerStack(new CurlMultiHandler());
$stack->push(new CacheMiddleware(new PublicCacheStrategy(new DoctrineCacheStorage($doctrineCache))), 'cache');
$client = new Client(['handler' => $stack]);
return new self($client);
}
开发者ID:robertlemke,项目名称:php-eventstore-client,代码行数:7,代码来源:GuzzleHttpClient.php
示例5: configure
/**
* Configures the stack using services tagged as http_client_middleware.
*
* @param \GuzzleHttp\HandlerStack $handler_stack
* The handler stack
*/
public function configure(HandlerStack $handler_stack)
{
$this->initializeMiddlewares();
foreach ($this->middlewares as $middleware_id => $middleware) {
$handler_stack->push($middleware, $middleware_id);
}
}
开发者ID:ddrozdik,项目名称:dmaps,代码行数:13,代码来源:HandlerStackConfigurator.php
示例6: testQueueLimitsNumberOfProcessingRequests
/**
* @dataProvider requestList
*/
public function testQueueLimitsNumberOfProcessingRequests(array $queueData, $expectedDuration, $throttleLimit, $threshold = 0.05)
{
$handler = new HandlerStack(new LoopHandler());
$handler->push(ThrottleMiddleware::create());
$client = new \GuzzleHttp\Client(['handler' => $handler, 'base_uri' => Server::$url, 'timeout' => 10]);
$queueEnd = $promises = $responses = $expectedStart = [];
Server::start();
Server::enqueue(array_fill(0, count($queueData), new Response()));
foreach ($queueData as $queueItem) {
list($queueId, $requestDuration, $expectedStartTime) = $queueItem;
$options = [RequestOptions::HTTP_ERRORS => false, RequestOptions::HEADERS => ['duration' => $requestDuration], 'throttle_id' => $queueId, 'throttle_limit' => $throttleLimit];
$expectedStart[$queueId] = $expectedStartTime;
$promises[] = $client->getAsync('', $options)->then(function () use($queueId, &$queueStart, &$queueEnd) {
if (!isset($queueStart[$queueId])) {
$queueStart[$queueId] = microtime(true);
}
$queueEnd[$queueId] = microtime(true);
});
}
$start = microtime(true);
$GLOBALS['s'] = microtime(1);
\GuzzleHttp\Promise\all($promises)->wait();
$duration = microtime(true) - $start;
$this->assertGreaterThan($expectedDuration - $threshold, $duration);
$this->assertLessThan($expectedDuration + $threshold, $duration);
foreach ($queueEnd as $i => $endedAt) {
$duration = $endedAt - $start;
// $this->assertGreaterThan($expectedDuration - $threshold, $endedAt - $start, "Queue #$i started too soon");
// $this->assertLessThan($queueInfo->getExpectedDuration() + $threshold, $queueInfo->getDuration(), "Queue #$i started too late");
//
// $this->assertGreaterThan($started + $queueInfo->getExpectedDelay() - $threshold, $queueInfo->getStartedAt(), "Queue #$i popped too early");
// $this->assertLessThan($started + $queueInfo->getExpectedDelay() + $threshold, $queueInfo->getStartedAt(), "Queue #$i popped too late");
}
}
开发者ID:Briareos,项目名称:Undine,代码行数:37,代码来源:LoopHandlerTest.php
示例7: buildClient
/**
* Build the guzzle client instance.
*
* @param array $config Additional configuration
*
* @return GuzzleClient
*/
private static function buildClient(array $config = [])
{
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
$handlerStack->push(Middleware::prepareBody(), 'prepare_body');
$config = array_merge(['handler' => $handlerStack], $config);
return new GuzzleClient($config);
}
开发者ID:lhas,项目名称:pep,代码行数:14,代码来源:Client.php
示例8: __construct
/**
* @param ClientInterface|null $client
*/
public function __construct(ClientInterface $client = null)
{
if (!$client) {
$handlerStack = new HandlerStack(\GuzzleHttp\choose_handler());
$handlerStack->push(Middleware::prepareBody(), 'prepare_body');
$client = new Client(['handler' => $handlerStack]);
}
$this->client = $client;
}
开发者ID:jdrieghe,项目名称:guzzle6-adapter,代码行数:12,代码来源:Guzzle6HttpAdapter.php
示例9: testExceptionWhileNewIdentity
/**
* @expectedException \GuzzleTor\TorNewIdentityException
*/
public function testExceptionWhileNewIdentity()
{
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::tor('127.0.0.1:9050', 'not-existed-host:9051'));
$client = new Client(['handler' => $stack]);
// Throw TorNewIdentityException because of wrong tor control host
$client->get('https://check.torproject.org/', ['tor_new_identity' => true, 'tor_new_identity_exception' => true]);
}
开发者ID:megahertz,项目名称:guzzle-tor,代码行数:12,代码来源:MiddlewareTest.php
示例10: setUp
public function setUp()
{
$this->context = new Context(['keys' => ['pda' => 'secret'], 'algorithm' => 'hmac-sha256', 'headers' => ['(request-target)', 'date']]);
$stack = new HandlerStack();
$stack->setHandler(new MockHandler([new Response(200, ['Content-Length' => 0])]));
$stack->push(GuzzleHttpSignatures::middlewareFromContext($this->context));
$stack->push(Middleware::history($this->history));
$this->client = new Client(['handler' => $stack]);
}
开发者ID:99designs,项目名称:http-signatures-guzzlehttp,代码行数:9,代码来源:GuzzleHttpSignerTest.php
示例11: __construct
public function __construct($bucket, $pub_key, $sec_key, $suffix = '.ufile.ucloud.cn', $https = false, $debug = false)
{
$this->bucket = $bucket;
$this->pub_key = $pub_key;
$this->sec_key = $sec_key;
$this->host = ($https ? 'https://' : 'http://') . $bucket . $suffix;
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(static::auth($bucket, $pub_key, $sec_key));
$this->httpClient = new Client(['base_uri' => $this->host, 'handler' => $stack, 'debug' => $debug]);
}
开发者ID:xujif,项目名称:ucloud-ufile-sdk,代码行数:11,代码来源:UfileSdk.php
示例12: __construct
/**
* HttpClient constructor.
*
* @param string $key
* @param string $secret
* @param array $options
*/
public function __construct($key, $secret, array $options = [])
{
$options = array_merge($this->options, $options);
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) use($key, $secret, $options) {
$date = new \DateTime('now', new \DateTimeZone('UTC'));
return $request->withHeader('User-Agent', $options['user_agent'])->withHeader('Apikey', $key)->withHeader('Date', $date->format('Y-m-d H:i:s'))->withHeader('Signature', sha1($secret . $date->format('Y-m-d H:i:s')));
}));
$this->options = array_merge($this->options, $options, ['handler' => $stack]);
$this->options['base_uri'] = sprintf($this->options['base_uri'], $this->options['api_version']);
$this->client = new Client($this->options);
}
开发者ID:worldia,项目名称:textmaster-api,代码行数:20,代码来源:HttpClient.php
示例13: get_tor_ip
function get_tor_ip()
{
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::tor());
$client = new Client(['handler' => $stack]);
$response = $client->get('https://check.torproject.org/');
if (preg_match('/<strong>([\\d.]+)<\\/strong>/', $response->getBody(), $matches)) {
return $matches[1];
} else {
return null;
}
}
开发者ID:megahertz,项目名称:guzzle-tor,代码行数:13,代码来源:example.php
示例14: testSubscriberDoesNotDoAnythingForNonGigyaAuthRequests
public function testSubscriberDoesNotDoAnythingForNonGigyaAuthRequests()
{
$handler = new MockHandler([function (RequestInterface $request) {
$query = $request->getUri()->getQuery();
$this->assertNotRegExp('/client_id=/', $query);
$this->assertNotRegExp('/client_secret=/', $query);
return new Response(200);
}]);
$stack = new HandlerStack($handler);
$stack->push(CredentialsAuthMiddleware::middleware('key', 'secret', 'user'));
$comp = $stack->resolve();
$promise = $comp(new Request('GET', 'https://example.com'), ['auth' => 'oauth']);
$this->assertInstanceOf(PromiseInterface::class, $promise);
}
开发者ID:graze,项目名称:gigya-client,代码行数:14,代码来源:CredentialsAuthMiddlewareTest.php
示例15: testNullStopwatch
/**
* @dataProvider expectProvider
*
* @param int $duration The expected duration.
*/
public function testNullStopwatch($duration)
{
// HandlerStack
$response = new Response(200);
$stack = new HandlerStack(new MockHandler([$response]));
// Middleware
$middleware = new StopwatchMiddleware();
$stack->push($middleware);
$handler = $stack->resolve();
// Request
$request = new Request('GET', 'http://example.com');
$promise = $handler($request, []);
$response = $promise->wait();
$this->assertNotEquals($response->getHeaderLine('X-Duration'), $duration);
}
开发者ID:bmancone,项目名称:guzzle-stopwatch-middleware,代码行数:20,代码来源:StopwatchMiddlewareTest.php
示例16: testSend
public function testSend()
{
$self = $this;
$mockRequestData = ['foo' => 'bar', 'token' => self::TOKEN];
$mockResponseData = ['ok' => true, 'foo' => 'bar'];
$handler = HandlerStack::create(new MockHandler([new Response(200, [], json_encode($mockResponseData))]));
$historyContainer = [];
$history = Middleware::history($historyContainer);
$handler->push($history);
$apiClient = new ApiClient(self::TOKEN, new Client(['handler' => $handler]));
$apiClient->addRequestListener(function (RequestEvent $event) use(&$eventsDispatched, $mockRequestData, $self) {
$eventsDispatched[ApiClient::EVENT_REQUEST] = true;
$self->assertEquals($mockRequestData, $event->getRawPayload());
});
$apiClient->addResponseListener(function (ResponseEvent $event) use(&$eventsDispatched, $mockResponseData, $self) {
$eventsDispatched[ApiClient::EVENT_RESPONSE] = true;
$self->assertEquals($mockResponseData, $event->getRawPayloadResponse());
});
$mockPayload = new MockPayload();
$mockPayload->setFoo('bar');
$apiClient->send($mockPayload);
$transaction = $historyContainer[0];
$requestUrl = (string) $transaction['request']->getUri();
$requestContentType = $transaction['request']->getHeader('content-type')[0];
parse_str($transaction['request']->getBody(), $requestBody);
$responseBody = json_decode($transaction['response']->getBody(), true);
$this->assertEquals(ApiClient::API_BASE_URL . 'mock', $requestUrl);
$this->assertEquals('application/x-www-form-urlencoded', $requestContentType);
$this->assertEquals($mockRequestData, $requestBody);
$this->assertEquals($mockResponseData, $responseBody);
$this->assertArrayHasKey(ApiClient::EVENT_REQUEST, $eventsDispatched);
$this->assertArrayHasKey(ApiClient::EVENT_RESPONSE, $eventsDispatched);
}
开发者ID:billhance,项目名称:slack,代码行数:33,代码来源:ApiClientTest.php
示例17: __construct
public function __construct($authKeys = array())
{
$opts = array("headers" => array("User-Agent" => "twitter-wrapi"), "query" => array("stringify_ids" => "true"), 'auth' => 'oauth');
$handler = HandlerStack::create();
$handler->push(new Oauth1($authKeys));
function build(&$obj, $prefix, $apiList)
{
$path = $prefix;
if ($prefix !== '') {
$path .= '/';
}
foreach ($apiList as $name) {
$json = file_get_contents(__DIR__ . '/api/' . $path . $name . '.json');
$endpoint = json_decode($json, true);
$pre = $prefix === '' ? $name : $prefix . '.' . $name;
foreach ($endpoint as $sub => $ep) {
$obj[$pre . '.' . $sub] = $ep;
}
}
}
$all = [];
build($all, '', ['statuses', 'media', 'direct_messages', 'search', 'friendships', 'friends', 'followers', 'account', 'blocks', 'users', 'favorites', 'lists', 'saved_searches', 'geo', 'trends', 'application', 'help']);
build($all, 'users', ['suggestions']);
build($all, 'lists', ['members', 'subscribers']);
parent::__construct('https://api.twitter.com/1.1/', $all, $opts, ['handler' => $handler]);
}
开发者ID:palanik,项目名称:twitter-php,代码行数:26,代码来源:twitter.php
示例18: getMockClient
private function getMockClient(array $response)
{
$mock = new MockHandler($response);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
return $client;
}
开发者ID:snicksnk,项目名称:ouroboros,代码行数:7,代码来源:Dialog.php
示例19: buildHttpMockClient
/**
* @return GuzzleClient
*/
public function buildHttpMockClient($body)
{
// Create a mock and queue two responses.
$mock = new MockHandler([new Response(200, array(), $body), new Response(200, array(), $body), new Response(400, array(), 'fault{'), new Response(400, array(), $body), new Response(400, array(), $body)]);
$handler = HandlerStack::create($mock);
return new GuzzleClient(['handler' => $handler]);
}
开发者ID:greggcz,项目名称:librenms,代码行数:10,代码来源:AbstractTest.php
示例20: getClient
/**
*
* @return Client
*/
protected function getClient(array $responseQueue = [])
{
$mock = new MockHandler($responseQueue);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
return $client;
}
开发者ID:ThaDafinser,项目名称:UserAgentParser,代码行数:11,代码来源:AbstractProviderTestCase.php
注:本文中的GuzzleHttp\HandlerStack类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论