Skip to content

Commit da9f4a1

Browse files
authored
Merge pull request #1397 from DMNSteve/1396
fix: fixes dsn connection strings by url encoding
2 parents f12f766 + b1ed166 commit da9f4a1

File tree

1 file changed

+45
-6
lines changed

1 file changed

+45
-6
lines changed

src/Jenssegers/Mongodb/Connection.php

Lines changed: 45 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Illuminate\Database\Connection as BaseConnection;
66
use Illuminate\Support\Arr;
7+
use Illuminate\Support\Str;
78
use MongoDB\Client;
89

910
class Connection extends BaseConnection
@@ -150,18 +151,43 @@ public function disconnect()
150151
}
151152

152153
/**
153-
* Create a DSN string from a configuration.
154+
* Determine if the given configuration array has a UNIX socket value.
154155
*
155-
* @param array $config
156+
* @param array $config
157+
* @return bool
158+
*/
159+
protected function hasDsnString(array $config)
160+
{
161+
return isset($config['dsn']) && ! empty($config['dsn']);
162+
}
163+
164+
/**
165+
* Get the DSN string for a socket configuration.
166+
*
167+
* @param array $config
156168
* @return string
157169
*/
158-
protected function getDsn(array $config)
170+
protected function getDsnString(array $config)
159171
{
160-
// Check if the user passed a complete dsn to the configuration.
161-
if (!empty($config['dsn'])) {
162-
return $config['dsn'];
172+
$dsn_string = $config['dsn'];
173+
174+
if ( Str::contains($dsn_string, 'mongodb://') ){
175+
$dsn_string = Str::replaceFirst('mongodb://', '', $dsn_string);
163176
}
164177

178+
$dsn_string = rawurlencode($dsn_string);
179+
180+
return "mongodb://{$dsn_string}";
181+
}
182+
183+
/**
184+
* Get the DSN string for a host / port configuration.
185+
*
186+
* @param array $config
187+
* @return string
188+
*/
189+
protected function getHostDsn(array $config)
190+
{
165191
// Treat host option as array of hosts
166192
$hosts = is_array($config['host']) ? $config['host'] : [$config['host']];
167193

@@ -178,6 +204,19 @@ protected function getDsn(array $config)
178204
return 'mongodb://' . implode(',', $hosts) . ($auth_database ? '/' . $auth_database : '');
179205
}
180206

207+
/**
208+
* Create a DSN string from a configuration.
209+
*
210+
* @param array $config
211+
* @return string
212+
*/
213+
protected function getDsn(array $config)
214+
{
215+
return $this->hasDsnString($config)
216+
? $this->getDsnString($config)
217+
: $this->getHostDsn($config);
218+
}
219+
181220
/**
182221
* @inheritdoc
183222
*/

0 commit comments

Comments
 (0)