Skip to content

Commit 5831a21

Browse files
Support comma-separated IP addresses (X-Forwarded-For)
1 parent 02199ab commit 5831a21

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/ValueObject/IpAddress.php

+5-1
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,18 @@ class IpAddress
1717
/**
1818
* @var string
1919
*/
20-
private $ipAddress = '';
20+
private $ipAddress;
2121

2222
/**
2323
* Country constructor.
2424
* @param string $ipAddress
2525
*/
2626
public function __construct(string $ipAddress)
2727
{
28+
// Clean up in case of comma-separated IPs
29+
$ipAddressList = explode(',', $ipAddress);
30+
$ipAddress = trim(reset($ipAddressList));
31+
2832
if (filter_var($ipAddress, FILTER_VALIDATE_IP) === false) {
2933
throw new InvalidArgumentException('Value "' . $ipAddress . '" is not a valid IP address');
3034
}

tests/Unit/ValueObject/IpAddressTest.php

+10
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,14 @@ public function testWhetherWrongValueCanNotBeSetAndUsed()
2929
$this->expectException(InvalidArgumentException::class);
3030
new IpAddress('foobar');
3131
}
32+
33+
/**
34+
* Test whether comma-separated values could be set and used
35+
* @link https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For#examples
36+
*/
37+
public function testWhetherCommaSeparatedValuesCanBeSetAndUsed()
38+
{
39+
$ipAddress = new IpAddress('203.0.113.195, 70.41.3.18, 150.172.238.178');
40+
$this->assertEquals('203.0.113.195', $ipAddress->get());
41+
}
3242
}

0 commit comments

Comments
 (0)