HttpClientPool.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Http\Client\Common;
  3. use Http\Client\Common\Exception\HttpClientNotFoundException;
  4. use Http\Client\HttpAsyncClient;
  5. use Http\Client\HttpClient;
  6. use Psr\Http\Client\ClientInterface;
  7. use Psr\Http\Message\RequestInterface;
  8. /**
  9. * A http client pool allows to send requests on a pool of different http client using a specific strategy (least used,
  10. * round robin, ...).
  11. */
  12. abstract class HttpClientPool implements HttpAsyncClient, HttpClient
  13. {
  14. /**
  15. * @var HttpClientPoolItem[]
  16. */
  17. protected $clientPool = [];
  18. /**
  19. * Add a client to the pool.
  20. *
  21. * @param HttpClient|HttpAsyncClient|HttpClientPoolItem|ClientInterface $client
  22. */
  23. public function addHttpClient($client)
  24. {
  25. if (!$client instanceof HttpClientPoolItem) {
  26. $client = new HttpClientPoolItem($client);
  27. }
  28. $this->clientPool[] = $client;
  29. }
  30. /**
  31. * Return an http client given a specific strategy.
  32. *
  33. * @throws HttpClientNotFoundException When no http client has been found into the pool
  34. *
  35. * @return HttpClientPoolItem Return a http client that can do both sync or async
  36. */
  37. abstract protected function chooseHttpClient();
  38. /**
  39. * {@inheritdoc}
  40. */
  41. public function sendAsyncRequest(RequestInterface $request)
  42. {
  43. return $this->chooseHttpClient()->sendAsyncRequest($request);
  44. }
  45. /**
  46. * {@inheritdoc}
  47. */
  48. public function sendRequest(RequestInterface $request)
  49. {
  50. return $this->chooseHttpClient()->sendRequest($request);
  51. }
  52. }