123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125 |
- <?php
- namespace GuzzleHttp;
- use GuzzleHttp\Promise as P;
- use GuzzleHttp\Promise\EachPromise;
- use GuzzleHttp\Promise\PromiseInterface;
- use GuzzleHttp\Promise\PromisorInterface;
- use Psr\Http\Message\RequestInterface;
- class Pool implements PromisorInterface
- {
-
- private $each;
-
- public function __construct(ClientInterface $client, $requests, array $config = [])
- {
- if (!isset($config['concurrency'])) {
- $config['concurrency'] = 25;
- }
- if (isset($config['options'])) {
- $opts = $config['options'];
- unset($config['options']);
- } else {
- $opts = [];
- }
- $iterable = P\Create::iterFor($requests);
- $requests = static function () use ($iterable, $client, $opts) {
- foreach ($iterable as $key => $rfn) {
- if ($rfn instanceof RequestInterface) {
- yield $key => $client->sendAsync($rfn, $opts);
- } elseif (\is_callable($rfn)) {
- yield $key => $rfn($opts);
- } else {
- throw new \InvalidArgumentException('Each value yielded by the iterator must be a Psr7\Http\Message\RequestInterface or a callable that returns a promise that fulfills with a Psr7\Message\Http\ResponseInterface object.');
- }
- }
- };
- $this->each = new EachPromise($requests(), $config);
- }
-
- public function promise(): PromiseInterface
- {
- return $this->each->promise();
- }
-
- public static function batch(ClientInterface $client, $requests, array $options = []): array
- {
- $res = [];
- self::cmpCallback($options, 'fulfilled', $res);
- self::cmpCallback($options, 'rejected', $res);
- $pool = new static($client, $requests, $options);
- $pool->promise()->wait();
- \ksort($res);
- return $res;
- }
-
- private static function cmpCallback(array &$options, string $name, array &$results): void
- {
- if (!isset($options[$name])) {
- $options[$name] = static function ($v, $k) use (&$results) {
- $results[$k] = $v;
- };
- } else {
- $currentFn = $options[$name];
- $options[$name] = static function ($v, $k) use (&$results, $currentFn) {
- $currentFn($v, $k);
- $results[$k] = $v;
- };
- }
- }
- }
|