1 | <?php |
||
15 | class IPv4NetworkMask |
||
16 | { |
||
17 | /** |
||
18 | * @var string |
||
19 | */ |
||
20 | const CIDR = '(3[0-2]|[1-2]?[0-9])'; // 0-32 |
||
21 | |||
22 | /** |
||
23 | * @var string |
||
24 | */ |
||
25 | private $ip = ''; |
||
26 | |||
27 | /** |
||
28 | * @var int |
||
29 | */ |
||
30 | private $long = 0; |
||
31 | |||
32 | /** |
||
33 | * @var int |
||
34 | */ |
||
35 | private $cidr = 0; |
||
36 | |||
37 | /** |
||
38 | * @param string $ip |
||
39 | * @param int $cidr |
||
40 | */ |
||
41 | 29 | private function __construct($ip, $cidr) |
|
47 | |||
48 | /** |
||
49 | * @param string $ip |
||
50 | * |
||
51 | * @return self |
||
52 | */ |
||
53 | 3 | public static function fromIP($ip) |
|
54 | { |
||
55 | 3 | if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) === false) { |
|
56 | throw InvalidPointTypeException::point('IPv4', $ip); |
||
57 | } |
||
58 | |||
59 | // get CIDR from IP mask |
||
60 | 3 | $mask = ''; |
|
61 | 3 | foreach (explode('.', $ip) as $octet) { |
|
62 | 3 | $mask .= str_pad(decbin($octet), 8, '0', STR_PAD_LEFT); |
|
63 | } |
||
64 | |||
65 | // check mask |
||
66 | 3 | if (strpos('01', $mask) !== false) { |
|
67 | // valid 11111111111111111111111100000000 -> 255.255.255.0 |
||
68 | // invalid 11111111111111111111111100000001 -> 255.255.255.1 |
||
69 | throw InvalidMaskException::ip($ip); |
||
70 | } |
||
71 | |||
72 | 3 | return new self($ip, substr_count($mask, '1')); |
|
73 | } |
||
74 | |||
75 | /** |
||
76 | * @param int $cidr |
||
77 | * |
||
78 | * @return self |
||
79 | */ |
||
80 | 26 | public static function fromCIDR($cidr) |
|
89 | |||
90 | /** |
||
91 | * @return int |
||
92 | */ |
||
93 | 6 | public function ip() |
|
97 | |||
98 | /** |
||
99 | * @return int |
||
100 | */ |
||
101 | 29 | public function cidr() |
|
105 | |||
106 | /** |
||
107 | * @param IPv4NetworkMask $mask |
||
108 | * |
||
109 | * @return bool |
||
110 | */ |
||
111 | public function equal(IPv4NetworkMask $mask) |
||
115 | |||
116 | /** |
||
117 | * @return string |
||
118 | */ |
||
119 | 16 | public function __toString() |
|
123 | } |
||
124 |