-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathNetworkCalculator.php
40 lines (33 loc) · 1.03 KB
/
NetworkCalculator.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?php
namespace Unleash\Client\Helper;
use Unleash\Client\Exception\InvalidIpAddressException;
/**
* @internal
*/
final class NetworkCalculator
{
public function __construct(
private readonly string $ipAddress,
private readonly int $networkSize
) {
}
public static function fromString(string $ipAddressAndNetwork): self
{
$regex = '@([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})(?:/([0-9]{1,2}))?@';
if (!preg_match($regex, $ipAddressAndNetwork, $matches)) {
throw new InvalidIpAddressException("{$ipAddressAndNetwork} is not a valid IP or CIDR block");
}
$ipAddress = $matches[1];
$networkSize = $matches[2] ?? 32;
return new self($ipAddress, (int) $networkSize);
}
public function isInRange(string $ipAddress): bool
{
return substr_compare(
sprintf('%032b', ip2long($ipAddress)),
sprintf('%032b', ip2long($this->ipAddress)),
0,
$this->networkSize,
) === 0;
}
}