Completed
Push — master ( 9c21b6...43c791 )
by David
04:48
created

LeastUsedClientPool::chooseHttpClient()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4.074

Importance

Changes 0
Metric Value
dl 0
loc 24
ccs 10
cts 12
cp 0.8333
rs 9.536
c 0
b 0
f 0
cc 4
nc 2
nop 0
crap 4.074
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Http\Client\Common\HttpClientPool;
6
7
use Http\Client\Common\Exception\HttpClientNotFoundException;
8
9
/**
10
 * LeastUsedClientPool will choose the client with the less current request in the pool.
11
 *
12
 * This strategy is only useful when doing async request
13
 *
14
 * @author Joel Wurtz <[email protected]>
15
 */
16
final class LeastUsedClientPool extends HttpClientPool
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21 6
    protected function chooseHttpClient(): HttpClientPoolItem
22
    {
23
        $clientPool = array_filter($this->clientPool, function (HttpClientPoolItem $clientPoolItem) {
24 5
            return !$clientPoolItem->isDisabled();
25 6
        });
26
27 6
        if (0 === count($clientPool)) {
28 2
            throw new HttpClientNotFoundException('Cannot choose a http client as there is no one present in the pool');
29
        }
30
31
        usort($clientPool, function (HttpClientPoolItem $clientA, HttpClientPoolItem $clientB) {
32 1
            if ($clientA->getSendingRequestCount() === $clientB->getSendingRequestCount()) {
33
                return 0;
34
            }
35
36 1
            if ($clientA->getSendingRequestCount() < $clientB->getSendingRequestCount()) {
37
                return -1;
38
            }
39
40 1
            return 1;
41 5
        });
42
43 5
        return reset($clientPool);
44
    }
45
}
46