@@ -27,14 +27,16 @@ class Connection extends \Illuminate\Database\Connection {
27
27
*/
28
28
public function __construct (array $ config )
29
29
{
30
- // Store configuration
31
30
$ this ->config = $ config ;
32
31
33
- // Check for connection options
32
+ // Build the connection string
33
+ $ dsn = $ this ->getDsn ($ config );
34
+
35
+ // You can pass options directly to the MogoClient constructor
34
36
$ options = array_get ($ config , 'options ' , array ());
35
37
36
- // Create connection
37
- $ this ->connection = new MongoClient ( $ this ->getDsn ( $ config) , $ options );
38
+ // Create the connection
39
+ $ this ->connection = $ this ->createConnection ( $ dsn , $ config , $ options );
38
40
39
41
// Select database
40
42
$ this ->db = $ this ->connection ->{$ config ['database ' ]};
@@ -95,6 +97,31 @@ public function getMongoClient()
95
97
return $ this ->connection ;
96
98
}
97
99
100
+ /**
101
+ * Create a new MongoClient connection.
102
+ *
103
+ * @param string $dsn
104
+ * @param array $config
105
+ * @param array $options
106
+ * @return MongoClient
107
+ */
108
+ protected function createConnection ($ dsn , array $ config , array $ options )
109
+ {
110
+ // Add credentials as options, this make sure the connection will not fail if
111
+ // the username or password contains strange characters.
112
+ if (isset ($ config ['username ' ]) && $ config ['username ' ])
113
+ {
114
+ $ options ['username ' ] = $ config ['username ' ];
115
+ }
116
+
117
+ if (isset ($ config ['password ' ]) && $ config ['password ' ])
118
+ {
119
+ $ options ['password ' ] = $ config ['password ' ];
120
+ }
121
+
122
+ return new MongoClient ($ dsn , $ options );
123
+ }
124
+
98
125
/**
99
126
* Create a DSN string from a configuration.
100
127
*
@@ -120,17 +147,9 @@ protected function getDsn(array $config)
120
147
}
121
148
}
122
149
123
- // Credentials
124
- if (isset ($ config ['username ' ]) and isset ($ config ['password ' ]))
125
- {
126
- $ credentials = "{$ username }: {$ password }@ " ;
127
- }
128
- else
129
- {
130
- $ credentials = '' ;
131
- }
132
-
133
- return "mongodb:// {$ credentials }" . implode (', ' , $ hosts ) . "/ {$ database }" ;
150
+ // The database name needs to be in the connection string, otherwise it will
151
+ // authenticate to the admin database, which may result in permission errors.
152
+ return "mongodb:// " . implode (', ' , $ hosts ) . "/ {$ database }" ;
134
153
}
135
154
136
155
/**
@@ -145,4 +164,4 @@ public function __call($method, $parameters)
145
164
return call_user_func_array (array ($ this ->db , $ method ), $ parameters );
146
165
}
147
166
148
- }
167
+ }
0 commit comments