Completed
Pull Request — master (#25)
by Joel
08:51
created

HttpClientPool::addHttpClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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