Completed
Pull Request — master (#17)
by Andreas
15:20 queued 06:48
created

MongoClient::switchSlave()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 4
rs 10
cc 1
eloc 2
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 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
        $this->notImplemented();
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
        $databaseInfoIterator = $this->client->listDatabases();
235
236
        $databases = [
237
            'databases' => [],
238
            'totalSize' => 0,
239
            'ok' => 1.0,
240
        ];
241
242
        foreach ($databaseInfoIterator as $databaseInfo) {
243
            $databases['databases'][] = $databaseInfo->getName();
244
            $databases['totalSize'] += $databaseInfo->getSizeOnDisk();
245
        }
246
247
        return $databases;
248
    }
249
250
    /**
251
     * Gets a database collection
252
     *
253
     * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
254
     * @param string $db The database name.
255
     * @param string $collection The collection name.
256
     * @return MongoCollection Returns a new collection object.
257
     * @throws Exception Throws Exception if the database or collection name is invalid.
258
     */
259
    public function selectCollection($db, $collection)
260
    {
261
        return new MongoCollection($this->selectDB($db), $collection);
262
    }
263
264
    /**
265
     * Gets a database
266
     *
267
     * @link http://www.php.net/manual/en/mongo.selectdb.php
268
     * @param string $name The database name.
269
     * @return MongoDB Returns a new db object.
270
     * @throws InvalidArgumentException
271
     */
272
    public function selectDB($name)
273
    {
274
        return new MongoDB($this, $name);
275
    }
276
277
    /**
278
     * {@inheritdoc}
279
     */
280
    public function setReadPreference($readPreference, $tags = null)
281
    {
282
        return $this->setReadPreferenceFromParameters($readPreference, $tags);
283
    }
284
285
    /**
286
     * {@inheritdoc}
287
     */
288
    public function setWriteConcern($wstring, $wtimeout = 0)
289
    {
290
        return $this->setWriteConcernFromParameters($wstring, $wtimeout);
291
    }
292
293
    /**
294
     * String representation of this connection
295
     *
296
     * @link http://www.php.net/manual/en/mongoclient.tostring.php
297
     * @return string Returns hostname and port for this connection.
298
     */
299
    public function __toString()
300
    {
301
        return $this->server;
302
    }
303
304
    /**
305
     * Forces a connection by executing the ping command
306
     */
307
    private function forceConnect()
308
    {
309
        $command = new \MongoDB\Driver\Command(['ping' => 1]);
310
        $this->manager->executeCommand('db', $command);
311
    }
312
313
    private function notImplemented()
314
    {
315
        throw new \Exception('Not implemented');
316
    }
317
}
318
319