1 | <?php |
||
12 | final class Rfc1918 implements Rule |
||
13 | { |
||
14 | const RFC1918_RANGES = [ |
||
15 | '10.0.0.0/8', |
||
16 | '172.16.0.0/21', |
||
17 | '192.168.0.0/16', |
||
18 | ]; |
||
19 | |||
20 | /** |
||
21 | * Determine if the validation rule passes. |
||
22 | * |
||
23 | * @param string $attribute |
||
24 | * @param mixed $value |
||
25 | * @return bool |
||
26 | */ |
||
27 | public function passes($attribute, $value) |
||
28 | { |
||
29 | $parts = explode('/', $value); |
||
30 | |||
31 | if (! filter_var($parts[0], FILTER_VALIDATE_IP)) { |
||
32 | return false; |
||
33 | } |
||
34 | |||
35 | $ip = inet_pton($parts[0]); |
||
36 | |||
37 | $range = $this->calculateRange($ip, count($parts) > 1 ? $parts[1] : 32); |
||
38 | |||
39 | foreach (static::RFC1918_RANGES as $rfc1918Range) { |
||
40 | list($privateIp, $privateMask) = explode('/', $rfc1918Range); |
||
41 | $privateRange = $this->calculateRange(inet_pton($privateIp), $privateMask); |
||
42 | |||
43 | if ($range[1] >= $privateRange[0] && $range[0] <= $privateRange[1]) { |
||
44 | return false; |
||
45 | } |
||
46 | } |
||
47 | |||
48 | return true; |
||
49 | } |
||
50 | |||
51 | /** |
||
52 | * @param string $address Packed representation of the address used to define the range. |
||
53 | * @param int $mask |
||
54 | * @return string[] Packed representations of the starting and ending addresses in this range. |
||
55 | */ |
||
56 | private function calculateRange(string $address, int $mask): array |
||
77 | |||
78 | /** |
||
79 | * Get the validation error message. |
||
80 | * |
||
81 | * @return string |
||
82 | */ |
||
83 | public function message() |
||
87 | } |
||
88 |
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: