From fb6420414676fbae1aad3368b25c57553afa6d2e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Mon, 4 Sep 2023 09:33:08 +0200 Subject: [PATCH] Support ipv6 in host config --- src/Connection.php | 14 +++++++++--- tests/ConnectionTest.php | 48 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 3 deletions(-) diff --git a/src/Connection.php b/src/Connection.php index 9b12575f0..99bfbd04a 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -234,9 +234,17 @@ protected function getHostDsn(array $config): string $hosts = is_array($config['host']) ? $config['host'] : [$config['host']]; foreach ($hosts as &$host) { - // Check if we need to add a port to the host - if (strpos($host, ':') === false && ! empty($config['port'])) { - $host = $host.':'.$config['port']; + // ipv6 + if (filter_var($host, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV6)) { + $host = '['.$host.']'; + if (! empty($config['port'])) { + $host = $host.':'.$config['port']; + } + } else { + // Check if we need to add a port to the host + if (! str_contains($host, ':') && ! empty($config['port'])) { + $host = $host.':'.$config['port']; + } } } diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index de1c329eb..77a2dce78 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -62,6 +62,54 @@ public function dataConnectionConfig(): Generator ], ]; + yield 'IPv4' => [ + 'expectedUri' => 'mongodb://1.2.3.4', + 'expectedDatabaseName' => 'tests', + 'config' => [ + 'host' => '1.2.3.4', + 'database' => 'tests', + ], + ]; + + yield 'IPv4 and port' => [ + 'expectedUri' => 'mongodb://1.2.3.4:1234', + 'expectedDatabaseName' => 'tests', + 'config' => [ + 'host' => '1.2.3.4', + 'port' => 1234, + 'database' => 'tests', + ], + ]; + + yield 'IPv6' => [ + 'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]', + 'expectedDatabaseName' => 'tests', + 'config' => [ + 'host' => '2001:db8:3333:4444:5555:6666:7777:8888', + 'database' => 'tests', + ], + ]; + + yield 'IPv6 and port' => [ + 'expectedUri' => 'mongodb://[2001:db8:3333:4444:5555:6666:7777:8888]:1234', + 'expectedDatabaseName' => 'tests', + 'config' => [ + 'host' => '2001:db8:3333:4444:5555:6666:7777:8888', + 'port' => 1234, + 'database' => 'tests', + ], + ]; + + yield 'multiple IPv6' => [ + 'expectedUri' => 'mongodb://[::1],[2001:db8::1:0:0:1]', + 'expectedDatabaseName' => 'tests', + 'config' => [ + 'host' => ['::1', '2001:db8::1:0:0:1'], + 'port' => null, + 'database' => 'tests', + ], + ]; + yield 'Port in host name takes precedence' => [ 'expectedUri' => 'mongodb://some-host:12345', 'expectedDatabaseName' => 'tests',