Skip to content

Commit d8c6106

Browse files
committed
Support ipv6 in host config
1 parent ad79fb1 commit d8c6106

File tree

2 files changed

+49
-3
lines changed

2 files changed

+49
-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: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,44 @@ 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 and port' => [
85+
'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]:1234',
86+
'expectedDatabaseName' => 'tests',
87+
'config' => [
88+
'host' => '2001:db8:3333:4444:5555:6666:7777:8888',
89+
'port' => 1234,
90+
'database' => 'tests',
91+
],
92+
];
93+
94+
yield 'IPv6' => [
95+
'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]',
96+
'expectedDatabaseName' => 'tests',
97+
'config' => [
98+
'host' => '2001:db8:3333:4444:5555:6666:7777:8888',
99+
'database' => 'tests',
100+
],
101+
];
102+
65103
yield 'Port in host name takes precedence' => [
66104
'expectedUri' => 'mongodb://some-host:12345',
67105
'expectedDatabaseName' => 'tests',

0 commit comments

Comments
 (0)