Skip to content

Commit 1b7b5e4

Browse files
authored
Add method Connection::ping() to check server connection (mongodb#2677)
1 parent 3982f17 commit 1b7b5e4

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

src/Connection.php

+16
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,10 @@
99
use InvalidArgumentException;
1010
use MongoDB\Client;
1111
use MongoDB\Database;
12+
use MongoDB\Driver\Exception\AuthenticationException;
13+
use MongoDB\Driver\Exception\ConnectionException;
14+
use MongoDB\Driver\Exception\RuntimeException;
15+
use MongoDB\Driver\ReadPreference;
1216
use MongoDB\Laravel\Concerns\ManagesTransactions;
1317
use Throwable;
1418

@@ -189,6 +193,18 @@ protected function createConnection(string $dsn, array $config, array $options):
189193
return new Client($dsn, $options, $driverOptions);
190194
}
191195

196+
/**
197+
* Check the connection to the MongoDB server
198+
*
199+
* @throws ConnectionException if connection to the server fails (for reasons other than authentication).
200+
* @throws AuthenticationException if authentication is needed and fails.
201+
* @throws RuntimeException if a server matching the read preference could not be found.
202+
*/
203+
public function ping(): void
204+
{
205+
$this->getMongoClient()->getManager()->selectServer(new ReadPreference(ReadPreference::PRIMARY_PREFERRED));
206+
}
207+
192208
/** @inheritdoc */
193209
public function disconnect()
194210
{

tests/ConnectionTest.php

+27
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@
99
use InvalidArgumentException;
1010
use MongoDB\Client;
1111
use MongoDB\Database;
12+
use MongoDB\Driver\Exception\ConnectionTimeoutException;
1213
use MongoDB\Laravel\Collection;
1314
use MongoDB\Laravel\Connection;
1415
use MongoDB\Laravel\Query\Builder;
1516
use MongoDB\Laravel\Schema\Builder as SchemaBuilder;
1617

18+
use function env;
1719
use function spl_object_hash;
1820

1921
class ConnectionTest extends TestCase
@@ -231,4 +233,29 @@ public function testDriverName()
231233
$driver = DB::connection('mongodb')->getDriverName();
232234
$this->assertEquals('mongodb', $driver);
233235
}
236+
237+
public function testPingMethod()
238+
{
239+
$config = [
240+
'name' => 'mongodb',
241+
'driver' => 'mongodb',
242+
'dsn' => env('MONGODB_URI', 'mongodb://127.0.0.1/'),
243+
'database' => 'unittest',
244+
'options' => [
245+
'connectTimeoutMS' => 100,
246+
'serverSelectionTimeoutMS' => 250,
247+
],
248+
];
249+
250+
$instance = new Connection($config);
251+
$instance->ping();
252+
253+
$this->expectException(ConnectionTimeoutException::class);
254+
$this->expectExceptionMessage("No suitable servers found (`serverSelectionTryOnce` set): [Failed to resolve 'wrong-host']");
255+
256+
$config['dsn'] = 'mongodb://wrong-host/';
257+
258+
$instance = new Connection($config);
259+
$instance->ping();
260+
}
234261
}

0 commit comments

Comments
 (0)