Completed
Pull Request — master (#12)
by
unknown
02:29
created

MongoClient::forceConnect()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 5
rs 9.4286
cc 1
eloc 3
nc 1
nop 0
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
use MongoDB\Client;
17
18
/**
19
 * A connection between PHP and MongoDB. This class is used to create and manage connections
20
 * See MongoClient::__construct() and the section on connecting for more information about creating connections.
21
 * @link http://www.php.net/manual/en/class.mongoclient.php
22
 */
23
class MongoClient
1 ignored issue
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
24
{
25
    const VERSION = '1.6.12';
26
    const DEFAULT_HOST = "localhost" ;
27
    const DEFAULT_PORT = 27017 ;
28
    const RP_PRIMARY = "primary" ;
29
    const RP_PRIMARY_PREFERRED = "primaryPreferred" ;
30
    const RP_SECONDARY = "secondary" ;
31
    const RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
32
    const RP_NEAREST = "nearest" ;
33
34
    /**
35
     * @var bool
36
     * @deprecated This will not properly work as the underlying driver connects lazily
37
     */
38
    public $connected = false;
39
40
    /**
41
     * @var
42
     */
43
    public $status;
44
45
    /**
46
     * @var string
47
     */
48
    protected $server;
49
50
    /**
51
     * @var
52
     */
53
    protected $persistent;
54
55
    /**
56
     * @var Client
57
     */
58
    private $client;
59
60
    /**
61
     * @var \MongoDB\Driver\Manager
62
     */
63
    private $manager;
64
65
    private $readPreference = [
66
        'type' => self::RP_PRIMARY,
67
        'tagsets' => [],
68
    ];
69
70
    private $writeConcern = [
71
        'w' => 1,
72
        'wtimeout' => null,
73
    ];
74
75
76
    /**
77
     * Creates a new database connection object
78
     *
79
     * @link http://php.net/manual/en/mongo.construct.php
80
     * @param string $server The server name.
81
     * @param array $options An array of options for the connection.
82
     * @param array $driverOptions An array of options for the MongoDB driver.
83
     * @throws MongoConnectionException
84
     */
85
    public function __construct($server = 'default', array $options = ["connect" => true], array $driverOptions = [])
86
    {
87
        if ($server === 'default') {
88
            $server = 'mongodb://' . self::DEFAULT_HOST . ':' . self::DEFAULT_PORT;
89
        }
90
91
        $this->server = $server;
92
        $this->client = new Client($server, $options, $driverOptions);
93
        $info = $this->client->__debugInfo();
94
        $this->manager = $info['manager'];
95
96
        if (isset($options['connect']) && $options['connect']) {
97
            $this->connect();
98
        }
99
    }
100
101
    /**
102
     * Closes this database connection
103
     *
104
     * @link http://www.php.net/manual/en/mongoclient.close.php
105
     * @param  boolean|string $connection
106
     * @return boolean If the connection was successfully closed.
107
     */
108
    public function close($connection = null)
0 ignored issues
show
Unused Code introduced by
The parameter $connection is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
109
    {
110
        $this->connected = false;
1 ignored issue
show
Deprecated Code introduced by
The property MongoClient::$connected has been deprecated with message: This will not properly work as the underlying driver connects lazily

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
111
112
        return false;
113
    }
114
115
    /**
116
     * Connects to a database server
117
     *
118
     * @link http://www.php.net/manual/en/mongoclient.connect.php
119
     *
120
     * @throws MongoConnectionException
121
     * @return boolean If the connection was successful.
122
     */
123
    public function connect()
124
    {
125
        $this->connected = true;
1 ignored issue
show
Deprecated Code introduced by
The property MongoClient::$connected has been deprecated with message: This will not properly work as the underlying driver connects lazily

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
126
127
        return true;
128
    }
129
130
    /**
131
     * Drops a database
132
     *
133
     * @link http://www.php.net/manual/en/mongoclient.dropdb.php
134
     * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database.
135
     * @return array The database response.
136
     * @deprecated Use MongoDB::drop() instead.
137
     */
138
    public function dropDB($db)
139
    {
140
        return $this->selectDB($db)->drop();
141
    }
142
143
    /**
144
     * Gets a database
145
     *
146
     * @link http://php.net/manual/en/mongoclient.get.php
147
     * @param string $dbname The database name.
148
     * @return MongoDB The database name.
149
     */
150
    public function __get($dbname)
151
    {
152
        return $this->selectDB($dbname);
153
    }
154
155
    /**
156
     * Gets the client for this object
157
     *
158
     * @internal This part is not of the ext-mongo API and should not be used
159
     * @return Client
160
     */
161
    public function getClient()
162
    {
163
        return $this->client;
164
    }
165
166
    /**
167
     * Get connections
168
     *
169
     * Returns an array of all open connections, and information about each of the servers
170
     *
171
     * @return array
172
     */
173
    static public function getConnections()
0 ignored issues
show
Coding Style introduced by
As per PSR2, the static declaration should come after the visibility declaration.
Loading history...
174
    {
175
        return [];
176
    }
177
178
    /**
179
     * Get hosts
180
     *
181
     * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the
182
     * set. Without a replica set, it will just return an array with one element containing the host that you are
183
     * connected to.
184
     *
185
     * @return array
186
     */
187
    public function getHosts()
188
    {
189
        $this->forceConnect();
190
        $servers = $this->manager->getServers();
191
        $results = [];
192
        foreach ($servers as $server) {
193
            $key = sprintf('%s:%d', $server->getHost(), $server->getPort());
194
            $info = $server->getInfo();
195
            $results[$key] = [
196
                'host'     => $server->getHost(),
197
                'port'     => $server->getPort(),
198
                'health'   => (int)$info['ok'], // Not totally sure about this
199
                'state'    => $server->getType(),
200
                'ping'     => $server->getLatency(),
201
                'lastPing' => null,
202
            ];
203
        }
204
        return $results;
205
    }
206
207
    /**
208
     * Get the read preference for this connection
209
     *
210
     * @return array
211
     */
212
    public function getReadPreference()
213
    {
214
        return $this->readPreference;
215
    }
216
217
    /**
218
     * Get the write concern for this connection
219
     *
220
     * @return array Returns an array describing the write concern.
221
     */
222
    public function getWriteConcern()
223
    {
224
        return $this->writeConcern;
225
    }
226
227
    /**
228
     * Kills a specific cursor on the server
229
     *
230
     * @link http://www.php.net/manual/en/mongoclient.killcursor.php
231
     * @param string $server_hash The server hash that has the cursor. This can be obtained through
232
     * {@link http://www.php.net/manual/en/mongocursor.info.php MongoCursor::info()}.
233
     * @param int|MongoInt64 $id The ID of the cursor to kill. You can either supply an {@link http://www.php.net/manual/en/language.types.integer.php int}
234
     * containing the 64 bit cursor ID, or an object of the
235
     * {@link http://www.php.net/manual/en/class.mongoint64.php MongoInt64} class. The latter is necessary on 32
236
     * bit platforms (and Windows).
237
     */
238
    public function killCursor($server_hash , $id)
0 ignored issues
show
Unused Code introduced by
The parameter $server_hash is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $id is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
239
    {
240
        throw new \Exception('Not implemented');
241
    }
242
243
    /**
244
     * Lists all of the databases available
245
     *
246
     * @link http://php.net/manual/en/mongoclient.listdbs.php
247
     * @return array Returns an associative array containing three fields. The first field is databases, which in turn contains an array. Each element of the array is an associative array corresponding to a database, giving the database's name, size, and if it's empty. The other two fields are totalSize (in bytes) and ok, which is 1 if this method ran successfully.
248
     */
249
    public function listDBs()
250
    {
251
        return $this->client->listDatabases();
252
    }
253
254
    /**
255
     * Gets a database collection
256
     *
257
     * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
258
     * @param string $db The database name.
259
     * @param string $collection The collection name.
260
     * @return MongoCollection Returns a new collection object.
261
     * @throws Exception Throws Exception if the database or collection name is invalid.
262
     */
263
    public function selectCollection($db, $collection)
264
    {
265
        $collection = new MongoCollection($this->selectDB($db), $collection);
266
        $collection->setReadPreference($this->readPreference['type'], $this->readPreference['tagsets']);
267
        $collection->setWriteConcern($this->writeConcern['w'], $this->writeConcern['wtimeout']);
268
        return $collection;
269
    }
270
271
    /**
272
     * Gets a database
273
     *
274
     * @link http://www.php.net/manual/en/mongo.selectdb.php
275
     * @param string $name The database name.
276
     * @return MongoDB Returns a new db object.
277
     * @throws InvalidArgumentException
278
     */
279
    public function selectDB($name)
280
    {
281
        return new MongoDB($this, $name);
282
    }
283
284
    /**
285
     * Set read preference
286
     *
287
     * @param string $readPreference
288
     * @param array $tags
289
     * @return bool
290
     */
291
    public function setReadPreference($readPreference, array $tags = null)
292
    {
293
        $this->readPreference['type'] = $readPreference;
294
        if (is_null($tags)) {
295
            $tags = [];
296
        }
297
        $this->readPreference['tagsets'] = $tags;
298
        return true;
299
    }
300
301
    /**
302
     * (PECL mongo &gt;= 1.5.0)<br/>
303
     * @link http://php.net/manual/en/mongoclient.setwriteconcern.php
304
     * Set the write concern for this database
305
     * @param mixed $w <p>The write concern. This may be an integer denoting the number of servers required to acknowledge the write, or a string mode (e.g. "majority").</p>
306
     * @param int $wtimeout[optional] <p>The maximum number of milliseconds to wait for the server to satisfy the write concern.</p>
0 ignored issues
show
Documentation introduced by
There is no parameter named $wtimeout[optional]. Did you maybe mean $wtimeout?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
307
     * @return boolean Returns <b>TRUE</b> on success, or <b>FALSE</b> otherwise.
308
     */
309
    public function setWriteConcern($w, $wtimeout = null)
310
    {
311
        $this->writeConcern['w'] = $w;
312
        if ($wtimeout) {
313
            $this->writeConcern['wtimeout'] = $wtimeout;
314
        }
315
        return true;
316
    }
317
318
    /**
319
     * Choose a new secondary for slaveOkay reads
320
     *
321
     * @link www.php.net/manual/en/mongo.switchslave.php
322
     * @return string The address of the secondary this connection is using for reads. This may be the same as the previous address as addresses are randomly chosen. It may return only one address if only one secondary (or only the primary) is available.
323
     * @throws MongoException (error code 15) if it is called on a non-replica-set connection. It will also throw MongoExceptions if it cannot find anyone (primary or secondary) to read from (error code 16).
324
     */
325
    public function switchSlave()
326
    {
327
        return $this->server;
328
    }
329
330
    /**
331
     * String representation of this connection
332
     *
333
     * @link http://www.php.net/manual/en/mongoclient.tostring.php
334
     * @return string Returns hostname and port for this connection.
335
     */
336
    public function __toString()
337
    {
338
        return $this->server;
339
    }
340
341
    private function forceConnect()
342
    {
343
        $command = new \MongoDB\Driver\Command(['ping' => 1]);
344
        $this->manager->executeCommand('db', $command);
345
    }
346
347
}
348
349