Skip to content

Instantly share code, notes, and snippets.

@puckbag
Last active November 1, 2019 23:06
Show Gist options
  • Save puckbag/c49f0cbe19574942dd17 to your computer and use it in GitHub Desktop.
Save puckbag/c49f0cbe19574942dd17 to your computer and use it in GitHub Desktop.
Custom Guzzle CurlFactory
<?php
require __DIR__ . '/vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\Handler\CurlFactory;
use GuzzleHttp\Handler\CurlHandler;
use GuzzleHttp\Handler\CurlMultiHandler;
use GuzzleHttp\Handler\EasyHandle;
use GuzzleHttp\Handler\Proxy;
use GuzzleHttp\Handler\StreamHandler;
use GuzzleHttp\Promise;
class MyCurlFactory extends CurlFactory {
public function release(EasyHandle $easy)
{
$easy->response->curl['info'] = curl_getinfo($easy->handle);
return parent::release($easy);
}
}
function my_choose_handler()
{
$handler = null;
if (extension_loaded('curl')) {
$curl_multi_handler = new CurlMultiHandler([
'handle_factory' => new MyCurlFactory(50),
]);
$curl_handler = new CurlHandler([
'handle_factory' => new MyCurlFactory(3),
]);
$handler = Proxy::wrapSync($curl_multi_handler, $curl_handler);
}
if (ini_get('allow_url_fopen')) {
$handler = $handler
? Proxy::wrapStreaming($handler, new StreamHandler())
: new StreamHandler();
} elseif (!$handler) {
throw new \RuntimeException('GuzzleHttp requires cURL, the '
. 'allow_url_fopen ini setting, or a custom HTTP handler.');
}
return $handler;
}
function test_factory()
{
$stack = HandlerStack::create(my_choose_handler());
$client = new Client(['handler' => $stack]);
$response = $client->get('http://thecatapi.com/api/images/get?format=src&type=gif');
print_r($response->curl);
}
function test_promises()
{
$stack = HandlerStack::create(my_choose_handler());
$client = new Client(['handler' => $stack]);
// Initiate each request but do not block
$promises = [
'gif' => $client->getAsync('http://thecatapi.com/api/images/get?format=src&type=gif'),
'jpg' => $client->getAsync('http://thecatapi.com/api/images/get?format=src&type=jpg'),
'png' => $client->getAsync('http://thecatapi.com/api/images/get?format=src&type=png'),
];
// Wait on all of the requests to complete.
$responses = Promise\unwrap($promises);
// You can access each result using the key provided to the unwrap
// function.
foreach ($responses as $key => $response)
{
echo "$key: ";
print_r($response->curl);
}
}
function main () {
echo 'test_factory...', PHP_EOL;
test_factory();
echo 'test_promises...', PHP_EOL;
test_promises();
return 0;
}
exit(main());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment