31 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
37 protected function __construct( array $restrictions =
null ) {
38 if ( $restrictions !==
null ) {
39 $this->loadFromArray( $restrictions );
56 return new self( $restrictions );
65 $restrictions = FormatJson::decode( $json,
true );
66 if ( !is_array( $restrictions ) ) {
67 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
69 return new self( $restrictions );
72 private function loadFromArray( array $restrictions ) {
73 static $validKeys = [
'IPAddresses' ];
74 static $neededKeys = [
'IPAddresses' ];
76 $keys = array_keys( $restrictions );
77 $invalidKeys = array_diff( $keys, $validKeys );
79 throw new InvalidArgumentException(
80 'Array contains invalid keys: ' . implode(
', ', $invalidKeys )
83 $missingKeys = array_diff( $neededKeys, $keys );
85 throw new InvalidArgumentException(
86 'Array is missing required keys: ' . implode(
', ', $missingKeys )
90 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
91 throw new InvalidArgumentException(
'IPAddresses is not an array' );
93 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
94 if ( !IPUtils::isIPAddress( $ip ) ) {
95 throw new InvalidArgumentException(
"Invalid IP address: $ip" );
98 $this->ipAddresses = $restrictions[
'IPAddresses'];
107 'IPAddresses' => $this->ipAddresses,
116 public function toJson( $pretty =
false ) {
117 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
133 $status = Status::newGood();
134 $status->setResult( $ok === array_filter( $ok ), $ok );
144 $set =
new IPSet( $this->ipAddresses );
145 return $set->match( $ip );