33namespace Jenssegers \Mongodb ;
44
55use Illuminate \Database \Connection as BaseConnection ;
6+ use Illuminate \Support \Arr ;
7+ use Illuminate \Support \Str ;
68use MongoDB \Client ;
79
810class Connection extends BaseConnection
@@ -34,7 +36,7 @@ public function __construct(array $config)
3436 $ dsn = $ this ->getDsn ($ config );
3537
3638 // You can pass options directly to the MongoDB constructor
37- $ options = array_get ($ config , 'options ' , []);
39+ $ options = Arr:: get ($ config , 'options ' , []);
3840
3941 // Create the connection
4042 $ this ->connection = $ this ->createConnection ($ dsn , $ config , $ options );
@@ -149,18 +151,43 @@ public function disconnect()
149151 }
150152
151153 /**
152- * Create a DSN string from a configuration .
154+ * Determine if the given configuration array has a UNIX socket value .
153155 *
154- * @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
155168 * @return string
156169 */
157- protected function getDsn (array $ config )
170+ protected function getDsnString (array $ config )
158171 {
159- // Check if the user passed a complete dsn to the configuration.
160- if (!empty ($ config ['dsn ' ])) {
161- return $ config ['dsn ' ];
172+ $ dsn_string = $ config ['dsn ' ];
173+
174+ if (Str::contains ($ dsn_string , 'mongodb:// ' )) {
175+ $ dsn_string = Str::replaceFirst ('mongodb:// ' , '' , $ dsn_string );
162176 }
163177
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+ {
164191 // Treat host option as array of hosts
165192 $ hosts = is_array ($ config ['host ' ]) ? $ config ['host ' ] : [$ config ['host ' ]];
166193
@@ -177,6 +204,19 @@ protected function getDsn(array $config)
177204 return 'mongodb:// ' . implode (', ' , $ hosts ) . ($ auth_database ? '/ ' . $ auth_database : '' );
178205 }
179206
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+
180220 /**
181221 * @inheritdoc
182222 */
0 commit comments