Skip to content

Commit d0c7b4d

Browse files
authored
Merge pull request #18 from divine/pr/17
Get database from dsn
2 parents 4d81b40 + 5cb9a01 commit d0c7b4d

File tree

1 file changed

+13
-2
lines changed

1 file changed

+13
-2
lines changed

src/Jenssegers/Mongodb/Connection.php

+13-2
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public function __construct(array $config)
3838
$this->connection = $this->createConnection($dsn, $config, $options);
3939

4040
// Select database
41-
$this->db = $this->connection->selectDatabase($config['database']);
41+
$this->db = $this->connection->selectDatabase($this->getDatabaseDsn($dsn, $config['database']));
4242

4343
$this->useDefaultPostProcessor();
4444

@@ -188,10 +188,21 @@ protected function getHostDsn(array $config)
188188

189189
// Check if we want to authenticate against a specific database.
190190
$auth_database = isset($config['options']) && !empty($config['options']['database']) ? $config['options']['database'] : null;
191-
192191
return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
193192
}
194193

194+
/**
195+
* Get database name from DSN string, if there is no database in DSN path - returns back $database argument.
196+
* @param string $dsn
197+
* @param $database
198+
* @return string
199+
*/
200+
protected function getDatabaseDsn($dsn, $database)
201+
{
202+
$dsnDatabase = trim(parse_url($dsn, PHP_URL_PATH), '/');
203+
return trim($dsnDatabase) ? $dsnDatabase : $database;
204+
}
205+
195206
/**
196207
* Create a DSN string from a configuration.
197208
* @param array $config

0 commit comments

Comments
 (0)