Completed
Push — master ( 3e0a76...885f69 )
by Andreas
02:39
created

MongoClient::getHosts()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 32
Code Lines 23

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 32
rs 8.5806
cc 4
eloc 23
nc 4
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 Alcaeus\MongoDbAdapter\Helper;
17
use MongoDB\Client;
18
19
/**
20
 * A connection between PHP and MongoDB. This class is used to create and manage connections
21
 * See MongoClient::__construct() and the section on connecting for more information about creating connections.
22
 * @link http://www.php.net/manual/en/class.mongoclient.php
23
 */
24
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...
25
{
26
    use Helper\ReadPreference;
27
    use Helper\WriteConcern;
28
29
    const VERSION = '1.6.12';
30
    const DEFAULT_HOST = "localhost" ;
31
    const DEFAULT_PORT = 27017 ;
32
    const RP_PRIMARY = "primary" ;
33
    const RP_PRIMARY_PREFERRED = "primaryPreferred" ;
34
    const RP_SECONDARY = "secondary" ;
35
    const RP_SECONDARY_PREFERRED = "secondaryPreferred" ;
36
    const RP_NEAREST = "nearest" ;
37
38
    /**
39
     * @var bool
40
     * @deprecated This will not properly work as the underlying driver connects lazily
41
     */
42
    public $connected = false;
43
44
    /**
45
     * @var
46
     */
47
    public $status;
48
49
    /**
50
     * @var string
51
     */
52
    protected $server;
53
54
    /**
55
     * @var
56
     */
57
    protected $persistent;
58
59
    /**
60
     * @var Client
61
     */
62
    private $client;
63
64
    /**
65
     * @var \MongoDB\Driver\Manager
66
     */
67
    private $manager;
68
69
    /**
70
     * Creates a new database connection object
71
     *
72
     * @link http://php.net/manual/en/mongo.construct.php
73
     * @param string $server The server name.
74
     * @param array $options An array of options for the connection.
75
     * @param array $driverOptions An array of options for the MongoDB driver.
76
     * @throws MongoConnectionException
77
     */
78
    public function __construct($server = 'default', array $options = ['connect' => true], array $driverOptions = [])
79
    {
80
        if ($server === 'default') {
81
            $server = 'mongodb://' . self::DEFAULT_HOST . ':' . self::DEFAULT_PORT;
82
        }
83
84
        $this->server = $server;
85
        $this->client = new Client($server, $options, $driverOptions);
86
        $info = $this->client->__debugInfo();
87
        $this->manager = $info['manager'];
88
89
        if (isset($options['connect']) && $options['connect']) {
90
            $this->connect();
91
        }
92
    }
93
94
    /**
95
     * Closes this database connection
96
     *
97
     * @link http://www.php.net/manual/en/mongoclient.close.php
98
     * @param  boolean|string $connection
99
     * @return boolean If the connection was successfully closed.
100
     */
101
    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...
102
    {
103
        $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...
104
105
        return false;
106
    }
107
108
    /**
109
     * Connects to a database server
110
     *
111
     * @link http://www.php.net/manual/en/mongoclient.connect.php
112
     *
113
     * @throws MongoConnectionException
114
     * @return boolean If the connection was successful.
115
     */
116
    public function connect()
117
    {
118
        $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...
119
120
        return true;
121
    }
122
123
    /**
124
     * Drops a database
125
     *
126
     * @link http://www.php.net/manual/en/mongoclient.dropdb.php
127
     * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database.
128
     * @return array The database response.
129
     * @deprecated Use MongoDB::drop() instead.
130
     */
131
    public function dropDB($db)
132
    {
133
        return $this->selectDB($db)->drop();
134
    }
135
136
    /**
137
     * Gets a database
138
     *
139
     * @link http://php.net/manual/en/mongoclient.get.php
140
     * @param string $dbname The database name.
141
     * @return MongoDB The database name.
142
     */
143
    public function __get($dbname)
144
    {
145
        return $this->selectDB($dbname);
146
    }
147
148
    /**
149
     * Gets the client for this object
150
     *
151
     * @internal This part is not of the ext-mongo API and should not be used
152
     * @return Client
153
     */
154
    public function getClient()
155
    {
156
        return $this->client;
157
    }
158
159
    /**
160
     * Get connections
161
     *
162
     * Returns an array of all open connections, and information about each of the servers
163
     *
164
     * @return array
165
     */
166
    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...
167
    {
168
        return [];
169
    }
170
171
    /**
172
     * Get hosts
173
     *
174
     * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the
175
     * set. Without a replica set, it will just return an array with one element containing the host that you are
176
     * connected to.
177
     *
178
     * @return array
179
     */
180
    public function getHosts()
181
    {
182
        $this->forceConnect();
183
184
        $servers = [];
185
        foreach ($this->manager->getServers() as $server) {
186
            $key = sprintf('%s:%d', $server->getHost(), $server->getPort());
187
            $info = $server->getInfo();
188
189
            switch ($server->getType()) {
190
                case \MongoDB\Driver\Server::TYPE_RS_PRIMARY:
191
                    $state = 1;
192
                    break;
193
                case \MongoDB\Driver\Server::TYPE_RS_SECONDARY:
194
                    $state = 2;
195
                    break;
196
                default:
197
                    $state = 0;
198
            }
199
200
            $servers[$key] = [
201
                'host' => $server->getHost(),
202
                'port' => $server->getPort(),
203
                'health' => (int) $info['ok'],
204
                'state' => $state,
205
                'ping' => $server->getLatency(),
206
                'lastPing' => null,
207
            ];
208
        }
209
210
        return $servers;
211
    }
212
213
    /**
214
     * Kills a specific cursor on the server
215
     *
216
     * @link http://www.php.net/manual/en/mongoclient.killcursor.php
217
     * @param string $server_hash The server hash that has the cursor.
218
     * @param int|MongoInt64 $id The ID of the cursor to kill.
219
     * @return bool
220
     */
221
    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...
222
    {
223
        throw new \Exception('Not implemented');
224
    }
225
226
    /**
227
     * Lists all of the databases available
228
     *
229
     * @link http://php.net/manual/en/mongoclient.listdbs.php
230
     * @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.
231
     */
232
    public function listDBs()
233
    {
234
        return $this->client->listDatabases();
235
    }
236
237
    /**
238
     * Gets a database collection
239
     *
240
     * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
241
     * @param string $db The database name.
242
     * @param string $collection The collection name.
243
     * @return MongoCollection Returns a new collection object.
244
     * @throws Exception Throws Exception if the database or collection name is invalid.
245
     */
246
    public function selectCollection($db, $collection)
247
    {
248
        return new MongoCollection($this->selectDB($db), $collection);
249
    }
250
251
    /**
252
     * Gets a database
253
     *
254
     * @link http://www.php.net/manual/en/mongo.selectdb.php
255
     * @param string $name The database name.
256
     * @return MongoDB Returns a new db object.
257
     * @throws InvalidArgumentException
258
     */
259
    public function selectDB($name)
260
    {
261
        return new MongoDB($this, $name);
262
    }
263
264
    /**
265
     * {@inheritdoc}
266
     */
267
    public function setReadPreference($readPreference, $tags = null)
268
    {
269
        return $this->setReadPreferenceFromParameters($readPreference, $tags);
270
    }
271
272
    /**
273
     * {@inheritdoc}
274
     */
275
    public function setWriteConcern($wstring, $wtimeout = 0)
276
    {
277
        return $this->setWriteConcernFromParameters($wstring, $wtimeout);
278
    }
279
280
    /**
281
     * Choose a new secondary for slaveOkay reads
282
     *
283
     * @link www.php.net/manual/en/mongo.switchslave.php
284
     * @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.
285
     * @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).
286
     */
287
    public function switchSlave()
288
    {
289
        return $this->server;
290
    }
291
292
    /**
293
     * String representation of this connection
294
     *
295
     * @link http://www.php.net/manual/en/mongoclient.tostring.php
296
     * @return string Returns hostname and port for this connection.
297
     */
298
    public function __toString()
299
    {
300
        return $this->server;
301
    }
302
303
    /**
304
     * Forces a connection by executing the ping command
305
     */
306
    private function forceConnect()
307
    {
308
        $command = new \MongoDB\Driver\Command(['ping' => 1]);
309
        $this->manager->executeCommand('db', $command);
310
    }
311
}
312
313