Skip to content

Commit 51bbdf7

Browse files
authored
Support ipv6 in host config (#2595)
1 parent ad79fb1 commit 51bbdf7

File tree

2 files changed

+59
-3
lines changed

2 files changed

+59
-3
lines changed

src/Connection.php

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -234,9 +234,17 @@ protected function getHostDsn(array $config): string
234234
$hosts = is_array($config['host']) ? $config['host'] : [$config['host']];
235235

236236
foreach ($hosts as &$host) {
237-
// Check if we need to add a port to the host
238-
if (strpos($host, ':') === false && ! empty($config['port'])) {
239-
$host = $host.':'.$config['port'];
237+
// ipv6
238+
if (filter_var($host, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) {
239+
$host = '['.$host.']';
240+
if (! empty($config['port'])) {
241+
$host = $host.':'.$config['port'];
242+
}
243+
} else {
244+
// Check if we need to add a port to the host
245+
if (! str_contains($host, ':') && ! empty($config['port'])) {
246+
$host = $host.':'.$config['port'];
247+
}
240248
}
241249
}
242250

tests/ConnectionTest.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,54 @@ public function dataConnectionConfig(): Generator
6262
],
6363
];
6464

65+
yield 'IPv4' => [
66+
'expectedUri' => 'mongodb://1.2.3.4',
67+
'expectedDatabaseName' => 'tests',
68+
'config' => [
69+
'host' => '1.2.3.4',
70+
'database' => 'tests',
71+
],
72+
];
73+
74+
yield 'IPv4 and port' => [
75+
'expectedUri' => 'mongodb://1.2.3.4:1234',
76+
'expectedDatabaseName' => 'tests',
77+
'config' => [
78+
'host' => '1.2.3.4',
79+
'port' => 1234,
80+
'database' => 'tests',
81+
],
82+
];
83+
84+
yield 'IPv6' => [
85+
'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]',
86+
'expectedDatabaseName' => 'tests',
87+
'config' => [
88+
'host' => '2001:db8:3333:4444:5555:6666:7777:8888',
89+
'database' => 'tests',
90+
],
91+
];
92+
93+
yield 'IPv6 and port' => [
94+
'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]:1234',
95+
'expectedDatabaseName' => 'tests',
96+
'config' => [
97+
'host' => '2001:db8:3333:4444:5555:6666:7777:8888',
98+
'port' => 1234,
99+
'database' => 'tests',
100+
],
101+
];
102+
103+
yield 'multiple IPv6' => [
104+
'expectedUri' => 'mongodb://[::1],[2001:db8::1:0:0:1]',
105+
'expectedDatabaseName' => 'tests',
106+
'config' => [
107+
'host' => ['::1', '2001:db8::1:0:0:1'],
108+
'port' => null,
109+
'database' => 'tests',
110+
],
111+
];
112+
65113
yield 'Port in host name takes precedence' => [
66114
'expectedUri' => 'mongodb://some-host:12345',
67115
'expectedDatabaseName' => 'tests',

0 commit comments

Comments
 (0)