LoadLimitChooser   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 45
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 3
B getAvailableHost() 0 22 6
1
<?php
2
3
namespace NBN\LoadBalancer\Chooser;
4
5
use NBN\LoadBalancer\Exception\NoRegisteredHostException;
6
use Symfony\Component\HttpFoundation\Request;
7
8
/**
9
 * @author Nicolas Bastien <[email protected]>
10
 */
11
class LoadLimitChooser implements ChooserInterface
12
{
13
    /**
14
     * @var float
15
     */
16
    protected $loadLimit;
17
18
    /**
19
     * @param float $loadLimit
20
     */
21
    public function __construct($loadLimit)
22
    {
23
        if ($loadLimit < 0 || $loadLimit > 1) {
24
            throw new \BadMethodCallException('Load limit should be between 0 and 1');
25
        }
26
27
        $this->loadLimit = $loadLimit;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function getAvailableHost(Request $request, array $hosts)
34
    {
35
        if (count($hosts) == 0) {
36
            throw new NoRegisteredHostException();
37
        }
38
39
        $currentLoad = 1;
40
        $currentHost = null;
41
42
        foreach ($hosts as $host) {
43
            $load = $host->getLoad();
44
            if ($load < $this->loadLimit) {
45
                return $host;
46
            }
47
            if ($currentHost === null || $load < $currentLoad) {
48
                $currentLoad = $load;
49
                $currentHost = $host;
50
            }
51
        }
52
53
        return $currentHost;
54
    }
55
}
56