From 51bee37cee10b28300a5f4bf194893f28397da1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 23 May 2024 14:45:38 +0200 Subject: [PATCH 1/2] Improve error message for invalid configuration --- CHANGELOG.md | 1 + src/Connection.php | 12 +++++++++--- tests/ConnectionTest.php | 8 ++++++++ 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 500f1ee46..6870b75b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to this project will be documented in this file. * Fix memory leak when filling nested fields using dot notation by @GromNaN in [#2962](https://github.com/mongodb/laravel-mongodb/pull/2962) * Fix PHP error when accessing the connection after disconnect by @SanderMuller in [#2967](https://github.com/mongodb/laravel-mongodb/pull/2967) +* Improve error message for invalid configuration by @GromNaN in [#2975](https://github.com/mongodb/laravel-mongodb/pull/2975) ## [4.3.0] - 2024-04-26 diff --git a/src/Connection.php b/src/Connection.php index ec337d524..b29b1c0e0 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -261,9 +261,15 @@ protected function getHostDsn(array $config): string */ protected function getDsn(array $config): string { - return $this->hasDsnString($config) - ? $this->getDsnString($config) - : $this->getHostDsn($config); + if (! empty($config['dsn'])) { + return $this->getDsnString($config); + } + + if (! empty($config['host'])) { + return $this->getHostDsn($config); + } + + throw new InvalidArgumentException('MongoDB connection configuration requires "dsn" or "host" key.'); } /** @inheritdoc */ diff --git a/tests/ConnectionTest.php b/tests/ConnectionTest.php index 60ee9ee3f..225de611e 100644 --- a/tests/ConnectionTest.php +++ b/tests/ConnectionTest.php @@ -204,6 +204,14 @@ public function testConnectionWithoutConfiguredDatabase(): void new Connection(['dsn' => 'mongodb://some-host']); } + public function testConnectionWithoutConfiguredDsnOrHost(): void + { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('MongoDB connection configuration requires "dsn" or "host" key.'); + + new Connection(['database' => 'hello']); + } + public function testCollection() { $collection = DB::connection('mongodb')->getCollection('unittest'); From 11c2672d6e7d711ee2e97fba593d00343f068122 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Tamarelle?= Date: Thu, 23 May 2024 16:16:23 +0200 Subject: [PATCH 2/2] Deprecate Connection::hasDsnString --- src/Connection.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Connection.php b/src/Connection.php index b29b1c0e0..734bd6d55 100644 --- a/src/Connection.php +++ b/src/Connection.php @@ -213,6 +213,8 @@ public function disconnect() /** * Determine if the given configuration array has a dsn string. + * + * @deprecated */ protected function hasDsnString(array $config): bool {