本文整理汇总了PHP中GuzzleHttp\HandlerStack::create方法的典型用法代码示例。如果您正苦于以下问题:PHP HandlerStack::create方法的具体用法?PHP HandlerStack::create怎么用?PHP HandlerStack::create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GuzzleHttp\HandlerStack
的用法示例。
在下文中一共展示了HandlerStack::create方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: testDownloaderDownloadsData
public function testDownloaderDownloadsData()
{
$handler = HandlerStack::create(new MockHandler([new Response(200, [], file_get_contents(__DIR__ . '/data/example-response.json'))]));
$downloader = new Downloader('validToken', new Client(['handler' => $handler]));
$transactionList = $downloader->downloadSince(new \DateTime('-1 week'));
$this->assertInstanceOf('\\FioApi\\TransactionList', $transactionList);
}
示例2: 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);
}
示例3: getClient
/**
*
* @return Client
*/
protected function getClient(array $responseQueue = [])
{
$mock = new MockHandler($responseQueue);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
return $client;
}
示例4: __construct
/**
* TestClient constructor.
*
* @param MockHandler $mock
* @param IdGeneratorInterface $idGenerator
*/
public function __construct(MockHandler $mock, IdGeneratorInterface $idGenerator)
{
$handler = HandlerStack::create($mock);
$this->idGenerator = $idGenerator;
$guzzle = new Client(['handler' => $handler]);
$this->client = new JsonRpcClient($guzzle, new Uri('http://localhost/'), $this->idGenerator);
}
示例5: getMockClient
private function getMockClient(array $response)
{
$mock = new MockHandler($response);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
return $client;
}
示例6: setUpBeforeClass
public static function setUpBeforeClass()
{
$mock = new MockHandler([new Response(200, [], file_get_contents(__DIR__ . '/SomeApiResponse.json')), new Response(200, [], file_get_contents(__DIR__ . '/SomeEmptyApiResponse.json')), new Response(200, [], file_get_contents(__DIR__ . '/SomeEmptyApiResponseWithUnsupportedEvents.json'))]);
$handler = HandlerStack::create($mock);
$client = new Client(['handler' => $handler]);
self::$apiEventStore = new GuzzleApiEventStore($client, new SomeSerializer());
}
示例7: getClient
/**
* Constructs a Solr client from input params.
*
* @return Client
*/
protected function getClient(InputInterface $input, OutputInterface $output)
{
if (isset($this->client)) {
return $this->client;
}
$baseURL = $input->getOption('url');
$username = $input->getOption('username');
$password = $input->getOption('password');
// Add trailing slash if one doesn't exist
if ($baseURL[strlen($baseURL) - 1] !== '/') {
$baseURL .= '/';
}
$output->writeln("Solr URL: <info>{$baseURL}</info>");
if (!empty($username)) {
$output->writeln("Basic auth: <info>{$username}</info>");
}
// Middleware which logs requests
$before = function (Request $request, $options) use($output) {
$url = $request->getUri();
$method = $request->getMethod();
$output->writeln(sprintf("<info>%s</info> %s ", $method, $url));
};
// Setup the default handler stack and add the logging middleware
$stack = HandlerStack::create();
$stack->push(Middleware::tap($before));
// Guzzle options
$options = ['base_uri' => $baseURL, 'handler' => $stack];
if (isset($username)) {
$options['auth'] = [$username, $password];
}
$guzzle = new GuzzleClient($options);
return new Client($guzzle);
}
示例8: initClient
private function initClient()
{
$handlerStack = HandlerStack::create();
$handlerStack->push(MiddlewareBuilder::factoryForPing($this->logger, self::MAX_RETRIES));
$handlerStack->push(Middleware::log($this->logger, new MessageFormatter('{hostname} {req_header_User-Agent} - [{ts}] \\"{method} {resource} {protocol}/{version}\\" {code} {res_header_Content-Length}')));
$this->client = new \GuzzleHttp\Client(['base_uri' => $this->storageApi->getApiUrl(), 'handler' => $handlerStack]);
}
示例9: register
public function register(Application $app)
{
$app['guzzle.base_url'] = '/';
$app['guzzle.api_version'] = $app->share(function () use($app) {
return version_compare(Client::VERSION, '6.0.0', '>=') ? 6 : 5;
});
if (!isset($app['guzzle.handler_stack'])) {
$app['guzzle.handler_stack'] = $app->share(function () {
return HandlerStack::create();
});
}
/** @deprecated Remove when Guzzle 5 support is dropped */
if (!isset($app['guzzle.plugins'])) {
$app['guzzle.plugins'] = [];
}
// Register a simple Guzzle Client object (requires absolute URLs when guzzle.base_url is unset)
$app['guzzle.client'] = $app->share(function () use($app) {
if ($app['guzzle.api_version'] === 5) {
$options = ['base_url' => $app['guzzle.base_url']];
$client = new Client($options);
foreach ($app['guzzle.plugins'] as $plugin) {
$client->addSubscriber($plugin);
}
} else {
$options = ['base_uri' => $app['guzzle.base_url'], 'handler' => $app['guzzle.handler_stack']];
$client = new Client($options);
}
return $client;
});
}
示例10: initClient
protected function initClient()
{
$handlerStack = HandlerStack::create();
/** @noinspection PhpUnusedParameterInspection */
$handlerStack->push(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) {
return $response && $response->getStatusCode() == 503;
}, function ($retries) {
return rand(60, 600) * 1000;
}));
/** @noinspection PhpUnusedParameterInspection */
$handlerStack->push(Middleware::retry(function ($retries, RequestInterface $request, ResponseInterface $response = null, $error = null) {
if ($retries >= self::RETRIES_COUNT) {
return false;
} elseif ($response && $response->getStatusCode() > 499) {
return true;
} elseif ($error) {
return true;
} else {
return false;
}
}, function ($retries) {
return (int) pow(2, $retries - 1) * 1000;
}));
$handlerStack->push(Middleware::cookies());
if ($this->logger) {
$handlerStack->push(Middleware::log($this->logger, $this->loggerFormatter));
}
$this->guzzle = new \GuzzleHttp\Client(array_merge(['handler' => $handlerStack, 'cookies' => true], $this->guzzleOptions));
}
示例11: testSend
public function testSend()
{
$container = [];
$history = Middleware::history($container);
$mockResponseData = json_encode(['ok' => true, 'foo' => 'bar']);
$mock = new MockHandler([new Response(200, [], $mockResponseData)]);
$stack = HandlerStack::create($mock);
$stack->push($history);
$client = new Client(['handler' => $stack]);
$mockPayload = new MockPayload();
$foo = 'who:(search+query+OR+other+search+query)';
$mockPayload->setFoo($foo);
$apiClient = new ApiClient(self::API_KEY, $client);
$payloadResponse = $apiClient->send($mockPayload);
$transaction = array_pop($container);
// Assert response is of type MockPayloadResponse
$this->assertInstanceOf('Colada\\Europeana\\Tests\\Test\\Payload\\MockPayloadResponse', $payloadResponse);
// Assert if the responses match up.
$transaction['response']->getBody();
$this->assertEquals($mockResponseData, $transaction['response']->getBody());
// Assert if the URL is unfuddled.
$expectedRequestUri = sprintf('http://europeana.eu/api/v2/mock.json?foo=%s&wskey=%s', $foo, self::API_KEY);
$requestUri = $transaction['request']->getUri();
$this->assertEquals($expectedRequestUri, $requestUri);
}
示例12: testBasicClient
public function testBasicClient()
{
$mock = new MockHandler([new Response(200, ['X-Foo' => 'Bar'], "{\"foo\":\"bar\"}")]);
$container = [];
$history = Middleware::history($container);
$stack = HandlerStack::create($mock);
$stack->push($history);
$http_client = new Client(['handler' => $stack]);
$client = new BuuyersClient('u', 'p');
$client->setClient($http_client);
$client->companies->getCompany(1);
foreach ($container as $transaction) {
$basic = $transaction['request']->getHeaders()['Authorization'][0];
$this->assertTrue($basic == "Basic dTpw");
$method = $transaction['request']->getMethod();
$this->assertEquals($method, 'GET');
//> GET
if ($transaction['response']) {
$statusCode = $transaction['response']->getStatusCode();
$this->assertEquals(200, $statusCode);
//> 200, 200
} elseif ($transaction['error']) {
echo $transaction['error'];
//> exception
}
}
}
示例13: get
public static function get(array $options, Oauth1 $oauth1)
{
$stack = HandlerStack::create();
$stack->unshift($oauth1);
$options['handler'] = $stack;
return new Client($options);
}
示例14: getHandlerStack
/**
* @return \GuzzleHttp\HandlerStack
*/
public function getHandlerStack()
{
$stack = HandlerStack::create();
$stack->setHandler(new CurlHandler());
$stack->push(signature_middleware_factory($this->ctx));
return $stack;
}
示例15: setUp
public function setUp()
{
// Create default HandlerStack
$stack = HandlerStack::create(function (RequestInterface $request, array $options) {
switch ($request->getUri()->getPath()) {
case '/etag':
if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') {
return new FulfilledPromise(new Response(304));
}
return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash'));
case '/etag-changed':
if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') {
return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash2'));
}
return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash'));
case '/stale-while-revalidate':
if ($request->getHeaderLine("If-None-Match") == 'MyBeautifulHash') {
return new FulfilledPromise((new Response(304))->withHeader("Cache-Control", 'max-age=10'));
}
return new FulfilledPromise((new Response())->withHeader("Etag", 'MyBeautifulHash')->withHeader("Cache-Control", 'max-age=1')->withAddedHeader("Cache-Control", 'stale-while-revalidate=60'));
}
throw new \InvalidArgumentException();
});
// Add this middleware to the top with `push`
$stack->push(CacheMiddleware::getMiddleware(), 'cache');
// Initialize the client with the handler option
$this->client = new Client(['handler' => $stack]);
CacheMiddleware::setClient($this->client);
}