Skip to content

[Updated PR#1491] Gets database name from DSN string #1954

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Feb 10, 2020
15 changes: 13 additions & 2 deletions src/Jenssegers/Mongodb/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ public function __construct(array $config)
$this->connection = $this->createConnection($dsn, $config, $options);

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

$this->useDefaultPostProcessor();

Expand Down Expand Up @@ -188,10 +188,21 @@ protected function getHostDsn(array $config)

// Check if we want to authenticate against a specific database.
$auth_database = isset($config['options']) && !empty($config['options']['database']) ? $config['options']['database'] : null;

return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
}

/**
* Get database name from DSN string, if there is no database in DSN path - returns back $database argument.
* @param string $dsn
* @param $database
* @return string
*/
protected function getDatabaseDsn($dsn, $database)
{
$dsnDatabase = trim(parse_url($dsn, PHP_URL_PATH), '/');
return trim($dsnDatabase) ? $dsnDatabase : $database;
}

/**
* Create a DSN string from a configuration.
* @param array $config
Expand Down