Completed
Pull Request — master (#10)
by
unknown
01:00
created

IPv4CIDR   A

Complexity

Total Complexity 2

Size/Duplication

Total Lines 21
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
wmc 2
lcom 1
cbo 1
dl 0
loc 21
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A validate() 0 4 1
A match() 0 11 1
1
<?php
2
3
namespace Safelist\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
        return (($ipDecimal & $netmaskDecimal) == ($rangeDecimal & $netmaskDecimal));
31
    }
32
}
33