testing promises with php

This commit is contained in:
Sergio Álvarez 2019-11-22 20:34:10 +01:00
commit 3a4b04c1ec
5 changed files with 93 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
vendor/
composer.lock

8
promises/composer.json Normal file
View File

@ -0,0 +1,8 @@
{
"require": {
"guzzlehttp/guzzle": "^6.4"
},
"autoload": {
"files": ["lib.php"]
}
}

53
promises/index.php Normal file
View File

@ -0,0 +1,53 @@
<?php
// https://xrg.io/tests/promises
require_once(dirname(__FILE__) .'/vendor/autoload.php');
// lib.php, helper functions
Lib\plain();
Lib\printf('load');
use GuzzleHttp\Client;
use GuzzleHttp\Promise;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Promise\EachPromise;
Lib\printf('client');
$client = new Client();
Lib\printf('requests');
$requests = function ($n) use ($client) {
$uri = 'https://xrg.io/tests/promises/sleep.php?';
for ($i = 0; $i < $n; $i++) {
yield function() use ($client, $uri, $i) {
return $client->getAsync($uri . http_build_query(['o' => $i, 's' => random_int(1, 5)]));
};
}
};
Lib\printf('pool');
$pool = new Pool($client, $requests(3), [
'concurrency' => 5,
'fulfilled' => function ($response, $index) {
Lib\printf(' i='. $index .' '. $response->getBody());
},
'rejected' => function ($reason, $index) {
Lib\printf(' '. $index .' '. $reason);
},
]);
Lib\printf('promise');
// Initiate the transfers and create a promise
$promise = $pool->promise();
Lib\printf('wait');
// Force the pool of requests to complete.
$promise->wait();
Lib\printf('end');

24
promises/lib.php Normal file
View File

@ -0,0 +1,24 @@
<?php
namespace Lib;
function microtime_calc(): array
{
static $last = null; // 1st time
static $sum = 0.0; // 1st time
$mt = microtime(true);
$diff = is_null($last)? 0.0: bcsub($mt, $last);
$sum = bcadd($sum, $diff);
$last = $mt;
return [$sum, $diff];
}
function printf(string $str, ...$args): int
{
return \printf("∑%.6f +%.6f | ". $str."\n", ...microtime_calc(), ...$args);
}
function plain(): void
{
header('Content-Type: text/plain');
}

6
promises/sleep.php Normal file
View File

@ -0,0 +1,6 @@
<?php
$s = ((int)$_GET['s']?: random_int(2, 5));// * 1000000;
sleep($s);
//printf("\$µs=%d", $s);
printf("\$s=%d", $s);