29 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
35 protected function __construct( array $restrictions =
null ) {
36 if ( $restrictions !==
null ) {
37 $this->loadFromArray( $restrictions );
54 return new self( $restrictions );
63 $restrictions = FormatJson::decode( $json,
true );
64 if ( !is_array( $restrictions ) ) {
65 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
67 return new self( $restrictions );
70 private function loadFromArray( array $restrictions ) {
71 static $validKeys = [
'IPAddresses' ];
72 static $neededKeys = [
'IPAddresses' ];
74 $keys = array_keys( $restrictions );
75 $invalidKeys = array_diff(
$keys, $validKeys );
77 throw new InvalidArgumentException(
78 'Array contains invalid keys: ' . implode(
', ', $invalidKeys )
81 $missingKeys = array_diff( $neededKeys,
$keys );
83 throw new InvalidArgumentException(
84 'Array is missing required keys: ' . implode(
', ', $missingKeys )
88 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
89 throw new InvalidArgumentException(
'IPAddresses is not an array' );
91 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
92 if ( !IPUtils::isIPAddress( $ip ) ) {
93 throw new InvalidArgumentException(
"Invalid IP address: $ip" );
96 $this->ipAddresses = $restrictions[
'IPAddresses'];
105 'IPAddresses' => $this->ipAddresses,
114 public function toJson( $pretty =
false ) {
115 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
131 $status = Status::newGood();
132 $status->setResult( $ok === array_filter( $ok ), $ok );
142 $set =
new IPSet( $this->ipAddresses );
143 return $set->match( $ip );