Skip to content

Commit c5c7e6b

Browse files
committed
IPRange::matches() accepts a list of CIDR #9573
1 parent b978c0f commit c5c7e6b

File tree

3 files changed

+24
-9
lines changed

3 files changed

+24
-9
lines changed

src/Middleware/SignedQueryMiddleware.php

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -124,12 +124,6 @@ private function isAllowedIp(ServerRequestInterface $request): bool
124124
return false;
125125
}
126126

127-
foreach ($this->allowedIps as $allowedIp) {
128-
if (IPRange::matches($remoteAddress, $allowedIp)) {
129-
return true;
130-
}
131-
}
132-
133-
return false;
127+
return IPRange::matches($remoteAddress, $this->allowedIps);
134128
}
135129
}

src/Validator/IPRange.php

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,23 @@
66

77
abstract class IPRange
88
{
9-
final public static function matches(string $ip, string $cidr): bool
9+
/**
10+
* Whether the given IP address matches at least one of the given CIDR.
11+
*
12+
* @param string[] $cidrs
13+
*/
14+
final public static function matches(string $ip, array $cidrs): bool
15+
{
16+
foreach ($cidrs as $cidr) {
17+
if (self::matchesOne($ip, $cidr)) {
18+
return true;
19+
}
20+
}
21+
22+
return false;
23+
}
24+
25+
private static function matchesOne(string $ip, string $cidr): bool
1026
{
1127
if (str_contains($ip, ':')) {
1228
return self::matchesIPv6($ip, $cidr);

tests/Validator/IPRangeTest.php

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ class IPRangeTest extends TestCase
1515
*/
1616
public function testMatches(bool $result, string $remoteAddr, string $cidr): void
1717
{
18-
self::assertSame($result, IPRange::matches($remoteAddr, $cidr));
18+
self::assertSame($result, IPRange::matches($remoteAddr, [$cidr]));
1919
}
2020

2121
public static function IPv4Data(): iterable
@@ -52,4 +52,9 @@ public static function IPv6Data(): iterable
5252
'invalid - empty IP address' => [false, '', '::1'],
5353
];
5454
}
55+
56+
public function testMultiplesWillMatchesIfAtLeastOne(): void
57+
{
58+
self::assertTrue(IPRange::matches('192.168.1.1', ['255.255.255.255', '192.168.1.1']));
59+
}
5560
}

0 commit comments

Comments
 (0)