Completed
Pull Request — master (#49)
by Joel
04:06
created

HttpClientPool::addHttpClient()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 8
ccs 6
cts 6
cp 1
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 4
nc 2
nop 1
crap 2
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 13
    public function addHttpClient($client)
25
    {
26 13
        if (!$client instanceof HttpClientPoolItem) {
27 10
            $client = new HttpClientPoolItem($client);
28 11
        }
29
30 13
        $this->clientPool[] = $client;
31 13
    }
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 6
    public function sendAsyncRequest(RequestInterface $request)
46
    {
47 6
        return $this->chooseHttpClient()->sendAsyncRequest($request);
48
    }
49
50
    /**
51
     * {@inheritdoc}
52
     */
53 13
    public function sendRequest(RequestInterface $request)
54
    {
55 13
        return $this->chooseHttpClient()->sendRequest($request);
56
    }
57
}
58