|
4 | 4 |
|
5 | 5 | use Illuminate\Database\Connection as BaseConnection;
|
6 | 6 | use Illuminate\Support\Arr;
|
| 7 | +use InvalidArgumentException; |
7 | 8 | use MongoDB\Client;
|
8 | 9 |
|
9 | 10 | class Connection extends BaseConnection
|
@@ -37,8 +38,11 @@ public function __construct(array $config)
|
37 | 38 | // Create the connection
|
38 | 39 | $this->connection = $this->createConnection($dsn, $config, $options);
|
39 | 40 |
|
| 41 | + // Get default database name |
| 42 | + $default_db = $this->getDefaultDatabaseName($dsn, $config); |
| 43 | + |
40 | 44 | // Select database
|
41 |
| - $this->db = $this->connection->selectDatabase($this->getDatabaseDsn($dsn, $config['database'])); |
| 45 | + $this->db = $this->connection->selectDatabase($default_db); |
42 | 46 |
|
43 | 47 | $this->useDefaultPostProcessor();
|
44 | 48 |
|
@@ -114,6 +118,26 @@ public function getDatabaseName()
|
114 | 118 | return $this->getMongoDB()->getDatabaseName();
|
115 | 119 | }
|
116 | 120 |
|
| 121 | + /** |
| 122 | + * Get the name of the default database based on db config or try to detect it from dsn |
| 123 | + * @param string $dsn |
| 124 | + * @param array $config |
| 125 | + * @return string |
| 126 | + * @throws InvalidArgumentException |
| 127 | + */ |
| 128 | + protected function getDefaultDatabaseName($dsn, $config) |
| 129 | + { |
| 130 | + if (empty($config['database'])) { |
| 131 | + if (preg_match('/^mongodb:\\/\\/.+\\/([^?&]+)/s', $dsn, $matches)) { |
| 132 | + $config['database'] = $matches[1]; |
| 133 | + } else { |
| 134 | + throw new InvalidArgumentException("Database is not properly configured."); |
| 135 | + } |
| 136 | + } |
| 137 | + |
| 138 | + return $config['database']; |
| 139 | + } |
| 140 | + |
117 | 141 | /**
|
118 | 142 | * Create a new MongoDB connection.
|
119 | 143 | * @param string $dsn
|
@@ -191,18 +215,6 @@ protected function getHostDsn(array $config)
|
191 | 215 | return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
|
192 | 216 | }
|
193 | 217 |
|
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 |
| - |
206 | 218 | /**
|
207 | 219 | * Create a DSN string from a configuration.
|
208 | 220 | * @param array $config
|
|
0 commit comments