Ip::isAllowed()   A
last analyzed

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 12
ccs 6
cts 6
cp 1
rs 9.2
c 0
b 0
f 0
cc 4
eloc 6
nc 3
nop 1
crap 4
1
<?php
2
/**
3
 * Handles IP whitelisting
4
 *
5
 * PHP version 5.5
6
 *
7
 * @category   OpCacheGUI
8
 * @package    Auth
9
 * @author     Pieter Hordijk <[email protected]>
10
 * @copyright  Copyright (c) 2014 Pieter Hordijk <https://github.com/PeeHaa>
11
 * @license    http://www.opensource.org/licenses/mit-license.html  MIT License
12
 * @version    1.0.0
13
 */
14
namespace OpCacheGUI\Auth;
15
16
/**
17
 * Handles IP whitelisting
18
 *
19
 * @category   OpCacheGUI
20
 * @package    Auth
21
 * @author     Pieter Hordijk <[email protected]>
22
 */
23
class Ip implements Whitelist
24
{
25
    /**
26
     * @var \OpCacheGUI\Network\Ip\Converter[] List of address to range converters
27
     */
28
    private $converters = [];
29
30
    /**
31
     * @var array List of whitelist ranges
32
     */
33
    private $whitelists = [];
34
35
    /**
36
     * Creates instance
37
     *
38
     * @param \OpCacheGUI\Network\Ip\Converter[] $converters List of address to range converters
39
     */
40 7
    public function __construct(array $converters)
41
    {
42 7
        $this->converters = $converters;
43 7
    }
44
45
    /**
46
     * Builds the whitelist
47
     *
48
     * @param array $addresses List of addresses which form the whitelist
49
     */
50 6
    public function buildWhitelist(array $addresses)
51
    {
52 6
        foreach ($addresses as $address) {
53 5
            $this->addWhitelist($address);
54
        }
55 6
    }
56
57
    /**
58
     * Adds a range to the whitelist
59
     *
60
     * @param string $address The address(range) to add to the whitelist
61
     */
62 5
    private function addWhitelist($address)
63
    {
64 5
        foreach ($this->converters as $converter) {
65 4
            if (!$converter->isValid($address)) {
66 1
                continue;
67
            }
68
69 3
            $this->whitelists[] = $converter->convert($address);
70
        }
71 5
    }
72
73
    /**
74
     * Checks whether the ip is allowed access
75
     *
76
     * @param string $ip The IP address to check
77
     *
78
     * @return boolean True when the IP is allowed access
79
     */
80 2
    public function isAllowed($ip)
81
    {
82 2
        $ip = (float) sprintf('%u', ip2long($ip));
83
84 2
        foreach ($this->whitelists as $whitelist) {
85 2
            if ($ip >= $whitelist[0] && $ip <= $whitelist[1]) {
86 2
                return true;
87
            }
88
        }
89
90 1
        return false;
91
    }
92
}
93