本文整理汇总了PHP中GuzzleHttp\Middleware::tap方法的典型用法代码示例。如果您正苦于以下问题:PHP Middleware::tap方法的具体用法?PHP Middleware::tap怎么用?PHP Middleware::tap使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类GuzzleHttp\Middleware
的用法示例。
在下文中一共展示了Middleware::tap方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: handle
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$config = app('Illuminate\\Contracts\\Config\\Repository');
$client = app(Client::class);
$logging = $config->get('captain_hook.log.active') && $config->get('queue.driver') != 'sync';
foreach ($this->webhooks as $webhook) {
if ($logging) {
if ($config->get('captain_hook.log.storage_quantity') != -1 && $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
$webhook->logs()->orderBy('updated_at', 'desc')->first()->delete();
}
$log = new WebhookLog(['webhook_id' => $webhook['id'], 'url' => $webhook['url']]);
$middleware = Middleware::tap(function (RequestInterface $request, $options) use($log) {
$log->payload_format = isset($request->getHeader('Content-Type')[0]) ? $request->getHeader('Content-Type')[0] : null;
$log->payload = $request->getBody()->getContents();
}, function ($request, $options, Promise $response) use($log) {
$response->then(function (ResponseInterface $response) use($log) {
$log->status = $response->getStatusCode();
$log->response = $response->getBody()->getContents();
$log->response_format = $log->payload_format = isset($response->getHeader('Content-Type')[0]) ? $response->getHeader('Content-Type')[0] : null;
$log->save();
});
});
$client->post($webhook['url'], ['body' => $this->eventData, 'handler' => $middleware($client->getConfig('handler'))]);
} else {
$client->postAsync($webhook['url'], ['body' => $this->eventData, 'verify' => false, 'future' => true]);
}
}
}
示例2: 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);
}
示例3: post
public function post($full_url, array $multi_parts = [], array $headers = [])
{
$options = ['debug' => GUZZLE_DEBUG];
// Grab the client's handler instance.
$clientHandler = $this->client->getConfig('handler');
// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
echo $request->getHeader('Content-Type');
// application/json
echo $request->getBody();
// {"foo":"bar"}
});
//$options['handler'] = $tapMiddleware($clientHandler);
$multi_part_vars = array();
foreach ($multi_parts as $name => $data) {
if (is_array($data)) {
$data['name'] = $name;
} else {
$data = ['name' => $name, 'contents' => $data];
}
$multi_part_vars[] = $data;
}
$options['multipart'] = $multi_part_vars;
//$options['headers'] = ['Referer' => $full_url];
if (!empty($headers)) {
$options['headers'] = $headers;
}
$this->response = $this->client->post($full_url, $options);
return $this;
}
示例4: toApi
public function toApi(Request $request)
{
$client = new \GuzzleHttp\Client();
$input = $request::all();
$command = 'request';
$api_key = 'MjuhMtfAAfvJqzbnWFLA';
// $api_key = 'mysendykey';
$api_username = 'chris-stop';
// $api_username = 'mysendyusername';
$from_name = 'Chris Munialo';
$from_lat = $input['lat'];
$from_long = $input['lng'];
$from_description = '';
$to_name = 'TRM';
$to_lat = $input['lat1'];
$to_long = $input['lng1'];
$to_description = '';
$recepient_name = 'John';
$recepient_phone = '0710000000';
$recepient_email = 'John@doe.com';
$pick_up_date = '2016-04-20 12:12:12';
$status = false;
$pay_method = 0;
$amount = 10;
$return = true;
$note = 'Sample note';
$note_status = true;
$request_type = 'quote';
$info = ['command' => $command, 'data' => ['api_key' => $api_key, 'api_username' => $api_username, 'from' => ['from_name' => $from_name, 'from_lat' => floatval($from_lat), 'from_long' => floatval($from_long), 'from_description' => $from_description], 'to' => ['to_name' => $to_name, 'to_lat' => floatval($to_lat), 'to_long' => floatval($to_long), 'to_description' => $to_description], 'recepient' => ['recepient_name' => $recepient_name, 'recepient_phone' => $recepient_phone, 'recepient_email' => $recepient_email], 'delivery_details' => ['pick_up_date' => $pick_up_date, 'collect_payment' => ['status' => $status, 'pay_method' => $pay_method, 'amount' => $amount], 'return' => $return, 'note' => $note, 'note_status' => $note_status, 'request_type' => $request_type]]];
$clientHandler = $client->getConfig('handler');
// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
$request->getHeader('Content-Type');
// application/json
$request->getBody();
// {"foo":"bar"}
});
$endpoint = 'https://developer.sendyit.com/v1/api/#request';
// $info = json_encode($info);
$client = new \GuzzleHttp\Client();
$res = $client->request('POST', $endpoint, ['json' => $info, 'handler' => $tapMiddleware($clientHandler), 'headers' => ['Accept' => 'application/json']]);
// $res->getStatusCode();
// "200"
// $res->getHeader('content-type');
// 'application/json; charset=utf8'
$pns = json_decode($res->getBody(), true);
// var_dump($pns);
// echo $pns;
// echo $pns;
// $pns= $res->getBody();
// {"type":"User"...
// Send an asynchronous request.
// $request = new \GuzzleHttp\Psr7\Request('POST', $endpoint );
// $promise = $client->sendAsync($request)->then(function ($response) {
// $response->getBody();
// });
// $promise->wait();
return view('orders.new', ['pns' => $pns]);
}
示例5: registerPanel
public function registerPanel(Panel $panel)
{
$handler = $this->client->getConfig('handler');
if ($handler instanceof HandlerStack) {
$handler->push(Middleware::tap(NULL, function (Request $request) use($panel) {
$panel->addRequest(Json::decode($request->getBody()));
}));
}
return $this;
}
示例6: logMiddleware
/**
* Log the request.
*
* @return \GuzzleHttp\Middleware
*/
public function logMiddleware()
{
return Middleware::tap(function (RequestInterface $request) {
Log::debug("Request: {$request->getMethod()} {$request->getUri()}");
Log::debug("Request Body: {$request->getBody()}");
});
}
示例7: testTapsBeforeAndAfter
public function testTapsBeforeAndAfter()
{
$calls = [];
$m = function ($handler) use(&$calls) {
return function ($request, $options) use($handler, &$calls) {
$calls[] = '2';
return $handler($request, $options);
};
};
$m2 = Middleware::tap(function (RequestInterface $request, array $options) use(&$calls) {
$calls[] = '1';
}, function (RequestInterface $request, array $options, PromiseInterface $p) use(&$calls) {
$calls[] = '3';
});
$h = new MockHandler([new Response()]);
$b = new HandlerStack($h);
$b->push($m2);
$b->push($m);
$comp = $b->resolve();
$p = $comp(new Request('GET', 'http://foo.com'), []);
$this->assertEquals('123', implode('', $calls));
$this->assertInstanceOf(PromiseInterface::class, $p);
$this->assertEquals(200, $p->wait()->getStatusCode());
}
示例8: testSetPendingModifications
/**
* @vcr FamilySearchClientTests/testSetPendingModifications.json
*/
public function testSetPendingModifications()
{
$features = $this->createAuthenticatedFamilySearchClient()->getAvailablePendingModifications();
$modifications = array_map(function (Feature $feature) {
return $feature->getName();
}, $features);
$featuresHeader = null;
$client = $this->createAuthenticatedFamilySearchClient(['pendingModifications' => $modifications, 'middleware' => [Middleware::tap(function (RequestInterface $request, $options) use(&$featuresHeader) {
$featuresHeader = $request->getHeader('X-FS-Feature-Tag')[0];
})]]);
$person = PersonBuilder::buildPerson('');
$responseState = $client->familytree()->addPerson($person);
$this->queueForDelete($responseState);
// Ensure a response came back
$this->assertNotNull($responseState);
$check = array();
// Ensure each requested feature was found in the request headers
foreach ($features as $feature) {
$this->assertTrue(strpos($featuresHeader, $feature->getName()) !== false, $feature->getName() . " was not found in the requested features.");
}
}
示例9: logMiddleware
/**
* Log the request.
*
* @return \Closure
*/
protected function logMiddleware()
{
return Middleware::tap(function (RequestInterface $request, $options) {
Log::debug("Request: {$request->getMethod()} {$request->getUri()} " . json_encode($options));
Log::debug('Request headers:' . json_encode($request->getHeaders()));
});
}
示例10: handle
/**
* Execute the job.
*
* @return void
*/
public function handle()
{
$config = app('Illuminate\\Contracts\\Config\\Repository');
$client = app(Client::class);
if ($config->get('captain_hook.log.max_attempts', -1) !== -1 && $this->attempts() > $config->get('captain_hook.log.max_attempts')) {
return;
}
$logging = $config->get('captain_hook.log.active');
$transformer = $this->resolveCallable($config->get('captain_hook.transformer'), 'transform');
$responseCallback = $this->resolveCallable($config->get('captain_hook.response_callback'), 'handle');
foreach ($this->webhooks as $webhook) {
if ($logging) {
if ($config->get('captain_hook.log.storage_quantity') != -1 && $webhook->logs()->count() >= $config->get('captain_hook.log.storage_quantity')) {
$webhook->logs()->orderBy('updated_at', 'asc')->first()->delete();
}
$log = new WebhookLog(['webhook_id' => $webhook['id'], 'url' => $webhook['url']]);
$middleware = Middleware::tap(function (RequestInterface $request, $options) use($log) {
$log->payload_format = isset($request->getHeader('Content-Type')[0]) ? $request->getHeader('Content-Type')[0] : null;
$log->payload = $request->getBody()->getContents();
}, function ($request, $options, PromiseInterface $response) use($log, $webhook, $responseCallback) {
$response->then(function (ResponseInterface $response) use($log, $webhook, $responseCallback) {
$log->status = $response->getStatusCode();
$log->response = $response->getBody()->getContents();
$log->response_format = $log->payload_format = isset($response->getHeader('Content-Type')[0]) ? $response->getHeader('Content-Type')[0] : null;
$log->save();
// Retry this job if the webhook response didn't give us a HTTP 200 OK
if ($response->getStatusCode() >= 300 || $response->getStatusCode() < 200) {
$this->release(30);
}
$responseCallback($webhook, $response);
});
});
$client->post($webhook['url'], ['exceptions' => false, 'body' => $transformer($this->eventData, $webhook), 'verify' => false, 'handler' => $middleware($client->getConfig('handler'))]);
} else {
$client->post($webhook['url'], ['exceptions' => false, 'body' => $transformer($this->eventData, $webhook), 'verify' => false, 'timeout' => 10]);
}
}
}
示例11: array
$spider->getDownloader()->getDispatcher()->addListener(SpiderEvents::SPIDER_CRAWL_PRE_REQUEST, array($politenessPolicyEventListener, 'onCrawlPreRequest'));
$spider->getDispatcher()->addSubscriber($statsHandler);
$spider->getDispatcher()->addSubscriber($LogHandler);
// Let's add something to enable us to stop the script
$spider->getDispatcher()->addListener(SpiderEvents::SPIDER_CRAWL_USER_STOPPED, function (Event $event) {
echo "\nCrawl aborted by user.\n";
exit;
});
// Let's add a CLI progress meter for fun
echo "\nCrawling";
$spider->getDownloader()->getDispatcher()->addListener(SpiderEvents::SPIDER_CRAWL_POST_REQUEST, function (Event $event) {
echo '.';
});
// Set up some caching, logging and profiling on the HTTP client of the spider
$guzzleClient = $spider->getDownloader()->getRequestHandler()->getClient();
$tapMiddleware = Middleware::tap([$timerMiddleware, 'onRequest'], [$timerMiddleware, 'onResponse']);
$guzzleClient->getConfig('handler')->push($tapMiddleware, 'timer');
// Execute the crawl
$result = $spider->crawl();
// Report
echo "\n\nSPIDER ID: " . $statsHandler->getSpiderId();
echo "\n ENQUEUED: " . count($statsHandler->getQueued());
echo "\n SKIPPED: " . count($statsHandler->getFiltered());
echo "\n FAILED: " . count($statsHandler->getFailed());
echo "\n PERSISTED: " . count($statsHandler->getPersisted());
// With the information from some of plugins and listeners, we can determine some metrics
$peakMem = round(memory_get_peak_usage(true) / 1024 / 1024, 2);
$totalTime = round(microtime(true) - $start, 2);
$totalDelay = round($politenessPolicyEventListener->totalDelay / 1000 / 1000, 2);
echo "\n\nMETRICS:";
echo "\n PEAK MEM USAGE: " . $peakMem . 'MB';
示例12: post
/**
*
* @return \Illuminate\Routing\Route
*/
public function post()
{
// $response = $this->client->post($this->endpoint, $this->getRequestVars());
// return new NvpResponse($result);
try {
// Grab the client's handler instance.
$clientHandler = $this->client->getConfig('handler');
// Create a middleware that echoes parts of the request.
$tapMiddleware = Middleware::tap(function ($request) {
print_r($request->getHeader('Content-Type'));
// application/json
echo $request->getBody() . "\n";
echo $request->getUri() . "\n";
// {"foo":"bar"}
});
$response = $this->client->post($this->endpoint, ['json' => $this->getRequestVars(), 'handler' => $tapMiddleware($clientHandler)]);
} catch (GuzzleHttp\Exception\BadResponseException $e) {
echo 'Uh oh! ' . $e->getMessage();
}
return $response;
}