IPv4CIDR   A
last analyzed

Complexity

Total Complexity 2

Size/Duplication

Total Lines 20
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 10
c 2
b 0
f 0
dl 0
loc 20
rs 10
wmc 2

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 3 1
A match() 0 11 1
1
<?php
2
3
namespace Whitelist\Definition;
4
5
/**
6
 * Represents an IPv4 CIDR notation definition
7
 *
8
 * @author Marc Seiler <[email protected]>
9
 * @copyright Copyright &copy; Marc Seiler 2015-
10
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
11
 */
12
class IPv4CIDR extends Definition
13
{
14
    private $regexp = "/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/([0-9]{1,2})?$/";
15
16
    public function validate()
17
    {
18
        return preg_match($this->regexp, $this->_definition) === 1;
19
    }
20
21
    public function match($value)
22
    {
23
        // Adapted from https://gist.github.com/tott/7684443
24
25
        list($range, $netmask) = explode('/', $this->_definition, 2);
26
        $rangeDecimal = ip2long($range);
27
        $ipDecimal = ip2long($value);
28
        $wildcardDecimal = pow(2, (32 - $netmask)) - 1;
29
        $netmaskDecimal = ~$wildcardDecimal;
30
31
        return (($ipDecimal & $netmaskDecimal) == ($rangeDecimal & $netmaskDecimal));
32
    }
33
}
34