| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Http\Client\Common\HttpClientPool; |
| 6 |
|
| 7 |
use Http\Client\Common\Exception\HttpClientNotFoundException; |
| 8 |
use Http\Client\Common\HttpClientPool as HttpClientPoolInterface; |
| 9 |
use Http\Client\HttpAsyncClient; |
| 10 |
use Psr\Http\Client\ClientInterface; |
| 11 |
use Psr\Http\Message\RequestInterface; |
| 12 |
use Psr\Http\Message\ResponseInterface; |
| 13 |
|
| 14 |
/** |
| 15 |
* A http client pool allows to send requests on a pool of different http client using a specific strategy (least used, |
| 16 |
* round robin, ...). |
| 17 |
*/ |
| 18 |
abstract class HttpClientPool implements HttpClientPoolInterface |
| 19 |
{ |
| 20 |
/** |
| 21 |
* @var HttpClientPoolItem[] |
| 22 |
*/ |
| 23 |
protected $clientPool = []; |
| 24 |
|
| 25 |
/** |
| 26 |
* Add a client to the pool. |
| 27 |
* |
| 28 |
* @param ClientInterface|HttpAsyncClient $client |
| 29 |
*/ |
| 30 |
public function addHttpClient($client): void |
| 31 |
{ |
| 32 |
// no need to check for HttpClientPoolItem here, since it extends the other interfaces |
| 33 |
if (!$client instanceof ClientInterface && !$client instanceof HttpAsyncClient) { |
| 34 |
throw new \TypeError( |
| 35 |
sprintf('%s::addHttpClient(): Argument #1 ($client) must be of type %s|%s, %s given', self::class, ClientInterface::class, HttpAsyncClient::class, get_debug_type($client)) |
| 36 |
); |
| 37 |
} |
| 38 |
|
| 39 |
if (!$client instanceof HttpClientPoolItem) { |
| 40 |
$client = new HttpClientPoolItem($client); |
| 41 |
} |
| 42 |
|
| 43 |
$this->clientPool[] = $client; |
| 44 |
} |
| 45 |
|
| 46 |
/** |
| 47 |
* Return an http client given a specific strategy. |
| 48 |
* |
| 49 |
* @return HttpClientPoolItem Return a http client that can do both sync or async |
| 50 |
* |
| 51 |
* @throws HttpClientNotFoundException When no http client has been found into the pool |
| 52 |
*/ |
| 53 |
abstract protected function chooseHttpClient(): HttpClientPoolItem; |
| 54 |
|
| 55 |
/** |
| 56 |
* {@inheritdoc} |
| 57 |
*/ |
| 58 |
public function sendAsyncRequest(RequestInterface $request) |
| 59 |
{ |
| 60 |
return $this->chooseHttpClient()->sendAsyncRequest($request); |
| 61 |
} |
| 62 |
|
| 63 |
/** |
| 64 |
* {@inheritdoc} |
| 65 |
*/ |
| 66 |
public function sendRequest(RequestInterface $request): ResponseInterface |
| 67 |
{ |
| 68 |
return $this->chooseHttpClient()->sendRequest($request); |
| 69 |
} |
| 70 |
} |
| 71 |
|