1 | <?php |
||
26 | class IPAddress |
||
27 | { |
||
28 | |||
29 | /** @var false|string presentation form of ip address, or false if invalid */ |
||
30 | protected $ip; |
||
31 | |||
32 | /** |
||
33 | * IPAddress constructor. |
||
34 | * @param string $ip IP address |
||
35 | */ |
||
36 | 1 | public function __construct($ip) |
|
44 | |||
45 | /** |
||
46 | * Get IP address from the request server data |
||
47 | * |
||
48 | * @return IPAddress |
||
49 | */ |
||
50 | 1 | public static function fromRequest() |
|
57 | |||
58 | /** |
||
59 | * convert IP address into a normalized condensed notation |
||
60 | * |
||
61 | * @param string $ip ip address to normalize |
||
62 | * |
||
63 | * @return string|false normalized address or false on failure |
||
64 | */ |
||
65 | protected function normalize($ip) |
||
70 | |||
71 | /** |
||
72 | * return presentation form of address |
||
73 | * |
||
74 | * @return string|false |
||
75 | */ |
||
76 | 1 | public function asReadable() |
|
80 | |||
81 | /** |
||
82 | * get network (binary) form of address |
||
83 | * |
||
84 | * @return string|false |
||
85 | */ |
||
86 | 1 | public function asBinary() |
|
94 | |||
95 | /** |
||
96 | * get the ip version, 4 or 6, of address |
||
97 | * |
||
98 | * @return int|false integer 4 for IPV4, 6 for IPV6, or false if invalid |
||
99 | */ |
||
100 | 1 | public function ipVersion() |
|
111 | |||
112 | /** |
||
113 | * Is this IP in the same subnet as the supplied address? |
||
114 | * |
||
115 | * Accepts net masks for both IPV4 and IPV6 and will select the appropriate one, to |
||
116 | * allow checking policy against request input with minimal method calls. |
||
117 | * |
||
118 | * @param string $matchIp presentation form ip address to compare |
||
119 | * @param int $netMask4 network mask, bits to match <= 32 for IPV4 |
||
120 | * @param int $netMask6 network mask, bits to match <=128 for IPV6 |
||
121 | * |
||
122 | * @return bool true if $this->ip and $matchIp are both in the specified subnet |
||
123 | */ |
||
124 | 1 | public function sameSubnet($matchIp, $netMask4, $netMask6) |
|
144 | |||
145 | /** |
||
146 | * Convert an IP address to a binary character string (i.e. "01111111000000000000000000000001") |
||
147 | * |
||
148 | * @param IPAddress $ip address object |
||
149 | * |
||
150 | * @return string |
||
151 | */ |
||
152 | protected function asBinaryString(IPAddress $ip) |
||
163 | } |
||
164 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: