Completed
Pull Request — master (#25)
by Joel
06:53
created

LeastUsedClientPool   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 34
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 2
Bugs 0 Features 2
Metric Value
wmc 6
c 2
b 0
f 2
lcom 1
cbo 3
dl 0
loc 34
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
B chooseHttpClient() 0 28 6
1
<?php
2
3
namespace Http\Client\Common\HttpClientPool;
4
5
use Http\Client\Common\Exception\NotFoundHttpClientException;
6
use Http\Client\Common\HttpClientPool;
7
use Http\Client\Common\HttpClientPoolItem;
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
class LeastUsedClientPool extends HttpClientPool
17
{
18
    /**
19
     * {@inheritdoc}
20
     */
21
    public function chooseHttpClient()
22
    {
23
        $clientPool = [];
24
25
        foreach ($this->clientPool as $clientPoolItem) {
26
            if (!$clientPoolItem->isDisabled()) {
27
                $clientPool[] = $clientPoolItem;
28
            }
29
        }
30
31
        if (0 === count($clientPool)) {
32
            throw new NotFoundHttpClientException('Cannot choose a http client as there is no one present in the pool');
33
        }
34
35
        usort($clientPool, function (HttpClientPoolItem $clientA, HttpClientPoolItem $clientB) {
36
            if ($clientA->getSendingRequestCount() === $clientB->getSendingRequestCount()) {
37
                return 0;
38
            }
39
40
            if ($clientA->getSendingRequestCount() < $clientB->getSendingRequestCount()) {
41
                return -1;
42
            }
43
44
            return 1;
45
        });
46
47
        return reset($clientPool);
48
    }
49
}
50