Completed
Push — master ( 5d4ec2...9ce45d )
by Nicolas
02:08
created

LoadLimitChooser   A

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