Completed
Pull Request — master (#63)
by Andreas
21:41
created

MongoClient::__sleep()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

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

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
342
    {
343
        return [
344
            'connected', 'status', 'server', 'persistent'
345
        ];
346
    }
347
}
348
349