1 | <?php |
||
34 | class IpWhitelist |
||
35 | { |
||
36 | /** The whitelist key for IPv4 addresses */ |
||
37 | const IPV4 = 'ipv4'; |
||
38 | |||
39 | /** The whitelist key for IPv6 addresses */ |
||
40 | const IPV6 = 'ipv6'; |
||
41 | |||
42 | /** an array of Ipv4Range items */ |
||
43 | private $ipv4Whitelist; |
||
44 | |||
45 | /** an array of Ipv6Range items */ |
||
46 | private $ipv6Whitelist; |
||
47 | |||
48 | /** |
||
49 | * Constructor for the class. |
||
50 | * @param array $whitelists An array with two keys ('ipv4' and 'ipv6') with |
||
51 | * each key mapping to an array of valid IP ranges. |
||
52 | */ |
||
53 | 12 | public function __construct(array $whitelists) |
|
54 | { |
||
55 | 12 | $this->ipv4Whitelist = $this->constructWhiteListForKey( |
|
56 | $whitelists, |
||
57 | 12 | self::IPV4, |
|
58 | 12 | 'Vectorface\\Whip\\IpRange\\Ipv4Range' |
|
59 | ); |
||
60 | 12 | $this->ipv6Whitelist = $this->constructWhiteListForKey( |
|
61 | $whitelists, |
||
62 | 12 | self::IPV6, |
|
63 | 12 | 'Vectorface\\Whip\\IpRange\\Ipv6Range' |
|
64 | ); |
||
65 | 12 | } |
|
66 | |||
67 | /** |
||
68 | * Returns whether or not the given IP address is within the whitelist. |
||
69 | * @param string $ipAddress A valid IPv4 or IPv6 address. |
||
70 | * @return boolean Returns true if the IP address matches one of the |
||
71 | * whitelisted IP ranges and false otherwise. |
||
72 | */ |
||
73 | 12 | public function isIpWhitelisted($ipAddress) |
|
74 | { |
||
75 | // determine whether this IP is IPv4 or IPv6 |
||
76 | 12 | $isIpv4Address = filter_var($ipAddress, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4); |
|
77 | 12 | return $this->isIpInWhitelist( |
|
78 | 12 | ($isIpv4Address) ? $this->ipv4Whitelist : $this->ipv6Whitelist, |
|
79 | $ipAddress |
||
80 | ); |
||
81 | } |
||
82 | |||
83 | /** |
||
84 | * Constructs the whitelist for the given key. Each element in the |
||
85 | * whitelist gets mapped from a string to an instance of an Ipv4Range or |
||
86 | * Ipv6Range. |
||
87 | * @param array $whitelist The input whitelist of ranges. |
||
88 | * @param string $key The key to use from the input whitelist ('ipv4' or |
||
89 | * 'ipv6'). |
||
90 | * @param string $class Each range string gets mapped to an instance of the |
||
91 | * specified $class. |
||
92 | * @return array Returns an array of Ipv4Range or Ipv6Range elements. |
||
93 | */ |
||
94 | 12 | private function constructWhiteListForKey(array $whitelist, $key, $class) |
|
104 | |||
105 | /** |
||
106 | * Returns whether or not the given IP address is in the given whitelist. |
||
107 | * @param array $whitelist The given whitelist. |
||
108 | * @param string $ipAddress The given IP address. |
||
109 | * @return boolean Returns true if the IP address is in the whitelist and |
||
110 | * false otherwise. |
||
111 | */ |
||
112 | 12 | private function isIpInWhitelist(array $whitelist, $ipAddress) |
|
121 | } |
||
122 |