本文整理汇总了PHP中GuzzleHttp\HandlerStack::push方法的典型用法代码示例。如果您正苦于以下问题:PHP HandlerStack::push方法的具体用法?PHP HandlerStack::push怎么用?PHP HandlerStack::push使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GuzzleHttp\HandlerStack
的用法示例。
在下文中一共展示了HandlerStack::push方法的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: 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]);
}
示例3: getHttpClient
/**
* Getter for the HTTP client.
*
* @return Client
*/
protected function getHttpClient()
{
if ($this->client === null) {
if ($this->logger instanceof LoggerInterface) {
$this->handlerStack->push(Middleware::log($this->logger, $this->messageFormatter, $this->logLevel));
}
$this->options['handler'] = $this->handlerStack;
$this->client = new Client($this->options);
}
return $this->client;
}
示例4: 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");
}
}
示例5: testRegisterPlugin
public function testRegisterPlugin()
{
$middleware = $this->getMiddleware();
$container = [];
$history = Middleware::history($container);
$stack = new HandlerStack();
$stack->setHandler(new MockHandler([new Response(200)]));
$stack->push($middleware);
$stack->push($history);
$client = new Client(['base_url' => 'http://example.com', 'handler' => $stack]);
$client->get('/resource/1');
$transaction = reset($container);
$request = $transaction['request'];
$authorization = $request->getHeaderLine('Authorization');
$this->assertRegExp('@Acquia 1:([a-zA-Z0-9+/]+={0,2})$@', $authorization);
}
示例6: 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();
}
示例7: configureResponseHandler
private function configureResponseHandler(HandlerStack $handlerStack)
{
$handlerStack->remove('wechatClient:response');
$handlerStack->push(function (callable $handler) {
return function (RequestInterface $request, array $options = []) use($handler) {
return $handler($request, $options)->then(function (ResponseInterface $response) use($request) {
// Non-success page, so we won't attempt to parse.
if ($response->getStatusCode() >= 300) {
return $response;
}
// Check if the response should be JSON decoded
$parse = ['application/json', 'text/json', 'text/plain'];
if (preg_match('#' . implode('|', $parse) . '#', $response->getHeaderLine('Content-Type')) < 1) {
return $response;
}
// Begin parsing JSON body.
$body = (string) $response->getBody();
$json = json_decode($body);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new BadResponseFormatException(json_last_error_msg(), json_last_error());
}
if (isset($json->errcode) && $json->errcode != 0) {
$message = isset($json->errmsg) ? $json->errmsg : '';
$code = $json->errcode;
throw new APIErrorException($message, $code, $request, $response);
}
return $response;
});
};
}, 'wechatClient:response');
}
示例8: 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);
}
示例9: 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);
}
示例10: 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);
}
}
示例11: attachMiddleware
/**
* @inheritdoc
* @SuppressWarnings(PHPMD.StaticAccess)
*/
public function attachMiddleware(HandlerStack $stack)
{
$stack->push(Middleware::mapRequest(function (RequestInterface $request) {
$this->onRequestBeforeSend($request);
return $request;
}));
$stack->push(function (callable $handler) {
return function (RequestInterface $request, array $options) use($handler) {
$promise = $handler($request, $options);
return $promise->then(function (ResponseInterface $response) use($request) {
$this->onRequestComplete($request, $response);
return $response;
});
};
});
return $stack;
}
示例12: __construct
/**
* @param string $apiKey
* @param string $secret
* @param string $url
* @param ClientInterface|null $client
* @param BucketManager $bucketManager
* @param FileManager $fileManager
* @param array $connectionConfig
*/
public function __construct($apiKey, $secret, $url = 'https://myracloud-upload.local/v2/', ClientInterface $client = null, BucketManager $bucketManager = null, FileManager $fileManager = null, array $connectionConfig = [])
{
$this->apiKey = $apiKey;
$this->secret = $secret;
$this->url = $url;
if ($client === null) {
$stack = new HandlerStack();
$stack->setHandler(new CurlHandler());
$stack->push(Middleware::prepareBody());
$stack->push(Middleware::mapRequest(function (RequestInterface $request) use($secret, $apiKey) {
return $request->withHeader('Authorization', "MYRA {$apiKey}:" . new Authentication\Signature($request->getMethod(), $request->getRequestTarget(), $secret, $request->getHeaders(), $request->getBody()));
}));
$client = new Client(array_merge(['base_uri' => $this->url, 'handler' => $stack], $connectionConfig));
}
$this->client = $client;
$this->bucketManager = $bucketManager ?: new BucketManager($this->client);
$this->fileManager = $fileManager ?: new FileManager($this->client);
}
示例13: 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]);
}
示例14: __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;
}
示例15: __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]);
}