Completed
Pull Request — master (#28)
by Andreas
03:41
created

MongoClient::listDBs()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 25
rs 8.8571
cc 3
eloc 16
nc 3
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
        $this->client = new Client($server, $options, $driverOptions);
87
        $info = $this->client->__debugInfo();
88
        $this->manager = $info['manager'];
89
90
        if (isset($options['connect']) && $options['connect']) {
91
            $this->connect();
92
        }
93
    }
94
95
96
    /**
97
     * Closes this database connection
98
     *
99
     * @link http://www.php.net/manual/en/mongoclient.close.php
100
     * @param  boolean|string $connection
101
     * @return boolean If the connection was successfully closed.
102
     */
103
    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...
104
    {
105
        $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...
106
107
        return false;
108
    }
109
110
    /**
111
     * Connects to a database server
112
     *
113
     * @link http://www.php.net/manual/en/mongoclient.connect.php
114
     *
115
     * @throws MongoConnectionException
116
     * @return boolean If the connection was successful.
117
     */
118
    public function connect()
119
    {
120
        $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...
121
122
        return true;
123
    }
124
125
    /**
126
     * Drops a database
127
     *
128
     * @link http://www.php.net/manual/en/mongoclient.dropdb.php
129
     * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database.
130
     * @return array The database response.
131
     * @deprecated Use MongoDB::drop() instead.
132
     */
133
    public function dropDB($db)
134
    {
135
        return $this->selectDB($db)->drop();
136
    }
137
138
    /**
139
     * Gets a database
140
     *
141
     * @link http://php.net/manual/en/mongoclient.get.php
142
     * @param string $dbname The database name.
143
     * @return MongoDB The database name.
144
     */
145
    public function __get($dbname)
146
    {
147
        return $this->selectDB($dbname);
148
    }
149
150
    /**
151
     * Gets the client for this object
152
     *
153
     * @internal This part is not of the ext-mongo API and should not be used
154
     * @return Client
155
     */
156
    public function getClient()
157
    {
158
        return $this->client;
159
    }
160
161
    /**
162
     * Get connections
163
     *
164
     * Returns an array of all open connections, and information about each of the servers
165
     *
166
     * @return array
167
     */
168
    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...
169
    {
170
        return [];
171
    }
172
173
    /**
174
     * Get hosts
175
     *
176
     * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the
177
     * set. Without a replica set, it will just return an array with one element containing the host that you are
178
     * connected to.
179
     *
180
     * @return array
181
     */
182
    public function getHosts()
183
    {
184
        $this->forceConnect();
185
186
        $results = [];
187
188
        try {
189
            $servers = $this->manager->getServers();
190
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
191
            throw ExceptionConverter::toLegacy($e);
192
        }
193
194
        foreach ($servers as $server) {
195
            $key = sprintf('%s:%d;-;.;%d', $server->getHost(), $server->getPort(), getmypid());
196
            $info = $server->getInfo();
197
198
            switch ($server->getType()) {
199
                case \MongoDB\Driver\Server::TYPE_RS_PRIMARY:
200
                    $state = 1;
201
                    break;
202
                case \MongoDB\Driver\Server::TYPE_RS_SECONDARY:
203
                    $state = 2;
204
                    break;
205
                default:
206
                    $state = 0;
207
            }
208
209
            $results[$key] = [
210
                'host' => $server->getHost(),
211
                'port' => $server->getPort(),
212
                'health' => (int) $info['ok'],
213
                'state' => $state,
214
                'ping' => $server->getLatency(),
215
                'lastPing' => null,
216
            ];
217
        }
218
219
        return $results;
220
    }
221
222
    /**
223
     * Kills a specific cursor on the server
224
     *
225
     * @link http://www.php.net/manual/en/mongoclient.killcursor.php
226
     * @param string $server_hash The server hash that has the cursor.
227
     * @param int|MongoInt64 $id The ID of the cursor to kill.
228
     * @return bool
229
     */
230
    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...
231
    {
232
        $this->notImplemented();
233
    }
234
235
    /**
236
     * Lists all of the databases available
237
     *
238
     * @link http://php.net/manual/en/mongoclient.listdbs.php
239
     * @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.
240
     */
241
    public function listDBs()
242
    {
243
        try {
244
            $databaseInfoIterator = $this->client->listDatabases();
245
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
246
            throw ExceptionConverter::toLegacy($e);
247
        }
248
249
        $databases = [
250
            'databases' => [],
251
            'totalSize' => 0,
252
            'ok' => 1.0,
253
        ];
254
255
        foreach ($databaseInfoIterator as $databaseInfo) {
256
            $databases['databases'][] = [
257
                'name' => $databaseInfo->getName(),
258
                'empty' => $databaseInfo->isEmpty(),
259
                'sizeOnDisk' => $databaseInfo->getSizeOnDisk(),
260
            ];
261
            $databases['totalSize'] += $databaseInfo->getSizeOnDisk();
262
        }
263
264
        return $databases;
265
    }
266
267
    /**
268
     * Gets a database collection
269
     *
270
     * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
271
     * @param string $db The database name.
272
     * @param string $collection The collection name.
273
     * @return MongoCollection Returns a new collection object.
274
     * @throws Exception Throws Exception if the database or collection name is invalid.
275
     */
276
    public function selectCollection($db, $collection)
277
    {
278
        return new MongoCollection($this->selectDB($db), $collection);
279
    }
280
281
    /**
282
     * Gets a database
283
     *
284
     * @link http://www.php.net/manual/en/mongo.selectdb.php
285
     * @param string $name The database name.
286
     * @return MongoDB Returns a new db object.
287
     * @throws InvalidArgumentException
288
     */
289
    public function selectDB($name)
290
    {
291
        return new MongoDB($this, $name);
292
    }
293
294
    /**
295
     * {@inheritdoc}
296
     */
297
    public function setReadPreference($readPreference, $tags = null)
298
    {
299
        return $this->setReadPreferenceFromParameters($readPreference, $tags);
300
    }
301
302
    /**
303
     * {@inheritdoc}
304
     */
305
    public function setWriteConcern($wstring, $wtimeout = 0)
306
    {
307
        return $this->setWriteConcernFromParameters($wstring, $wtimeout);
308
    }
309
310
    /**
311
     * String representation of this connection
312
     *
313
     * @link http://www.php.net/manual/en/mongoclient.tostring.php
314
     * @return string Returns hostname and port for this connection.
315
     */
316
    public function __toString()
317
    {
318
        return $this->server;
319
    }
320
321
    /**
322
     * Forces a connection by executing the ping command
323
     */
324
    private function forceConnect()
325
    {
326
        $command = new \MongoDB\Driver\Command(['ping' => 1]);
327
        $this->manager->executeCommand('db', $command);
328
    }
329
330
    private function notImplemented()
331
    {
332
        throw new \Exception('Not implemented');
333
    }
334
}
335
336