本文整理汇总了PHP中GuzzleHttp\HandlerStack类的典型用法代码示例。如果您正苦于以下问题:PHP HandlerStack类的具体用法?PHP HandlerStack怎么用?PHP HandlerStack使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了HandlerStack类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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]);
}
示例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();
}
示例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());
}
}
示例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);
}
示例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);
}
}
示例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");
}
}
示例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);
}
示例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;
}
示例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]);
}
示例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]);
}
示例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]);
}
示例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);
}
示例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;
}
}
示例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);
}
示例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);
}