Completed
Pull Request — master (#12)
by
unknown
03:04
created

MongoClient::getWriteConcern()   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
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
    /**
72
     * Creates a new database connection object
73
     *
74
     * @link http://php.net/manual/en/mongo.construct.php
75
     * @param string $server The server name.
76
     * @param array $options An array of options for the connection.
77
     * @param array $driverOptions An array of options for the MongoDB driver.
78
     * @throws MongoConnectionException
79
     */
80
    public function __construct($server = 'default', array $options = ["connect" => true], array $driverOptions = [])
81
    {
82
        if ($server === 'default') {
83
            $server = 'mongodb://' . self::DEFAULT_HOST . ':' . self::DEFAULT_PORT;
84
        }
85
86
        $this->server = $server;
87
        $this->client = new Client($server, $options, $driverOptions);
88
        $this->readPreference = new \MongoDB\Driver\ReadPreference(\MongoDB\Driver\ReadPreference::RP_PRIMARY);
89
        $info = $this->client->__debugInfo();
90
        $this->manager = $info['manager'];
91
92
        if (isset($options['connect']) && $options['connect']) {
93
            $this->connect();
94
        }
95
    }
96
97
    /**
98
     * Closes this database connection
99
     *
100
     * @link http://www.php.net/manual/en/mongoclient.close.php
101
     * @param  boolean|string $connection
102
     * @return boolean If the connection was successfully closed.
103
     */
104
    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...
105
    {
106
        $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...
107
108
        return false;
109
    }
110
111
    /**
112
     * Connects to a database server
113
     *
114
     * @link http://www.php.net/manual/en/mongoclient.connect.php
115
     *
116
     * @throws MongoConnectionException
117
     * @return boolean If the connection was successful.
118
     */
119
    public function connect()
120
    {
121
        $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...
122
123
        return true;
124
    }
125
126
    /**
127
     * Drops a database
128
     *
129
     * @link http://www.php.net/manual/en/mongoclient.dropdb.php
130
     * @param mixed $db The database to drop. Can be a MongoDB object or the name of the database.
131
     * @return array The database response.
132
     * @deprecated Use MongoDB::drop() instead.
133
     */
134
    public function dropDB($db)
135
    {
136
        return $this->selectDB($db)->drop();
137
    }
138
139
    /**
140
     * Gets a database
141
     *
142
     * @link http://php.net/manual/en/mongoclient.get.php
143
     * @param string $dbname The database name.
144
     * @return MongoDB The database name.
145
     */
146
    public function __get($dbname)
147
    {
148
        return $this->selectDB($dbname);
149
    }
150
151
    /**
152
     * Gets the client for this object
153
     *
154
     * @internal This part is not of the ext-mongo API and should not be used
155
     * @return Client
156
     */
157
    public function getClient()
158
    {
159
        return $this->client;
160
    }
161
162
    /**
163
     * Get connections
164
     *
165
     * Returns an array of all open connections, and information about each of the servers
166
     *
167
     * @return array
168
     */
169
    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...
170
    {
171
        return [];
172
    }
173
174
    /**
175
     * Get hosts
176
     *
177
     * This method is only useful with a connection to a replica set. It returns the status of all of the hosts in the
178
     * set. Without a replica set, it will just return an array with one element containing the host that you are
179
     * connected to.
180
     *
181
     * @return array
182
     */
183
    public function getHosts()
184
    {
185
        $this->forceConnect();
186
        $servers = $this->manager->getServers();
187
        $results = [];
188
        foreach ($servers as $server) {
189
            $key = sprintf('%s:%d', $server->getHost(), $server->getPort());
190
            $info = $server->getInfo();
191
            $results[$key] = [
192
                'host'     => $server->getHost(),
193
                'port'     => $server->getPort(),
194
                'health'   => (int)$info['ok'], // Not totally sure about this
195
                'state'    => $server->getType(),
196
                'ping'     => $server->getLatency(),
197
                'lastPing' => null,
198
            ];
199
        }
200
        return $results;
201
    }
202
203
    /**
204
     * Kills a specific cursor on the server
205
     *
206
     * @link http://www.php.net/manual/en/mongoclient.killcursor.php
207
     * @param string $server_hash The server hash that has the cursor. This can be obtained through
208
     * {@link http://www.php.net/manual/en/mongocursor.info.php MongoCursor::info()}.
209
     * @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}
210
     * containing the 64 bit cursor ID, or an object of the
211
     * {@link http://www.php.net/manual/en/class.mongoint64.php MongoInt64} class. The latter is necessary on 32
212
     * bit platforms (and Windows).
213
     */
214
    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...
215
    {
216
        throw new \Exception('Not implemented');
217
    }
218
219
    /**
220
     * Lists all of the databases available
221
     *
222
     * @link http://php.net/manual/en/mongoclient.listdbs.php
223
     * @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.
224
     */
225
    public function listDBs()
226
    {
227
        return $this->client->listDatabases();
228
    }
229
230
    /**
231
     * Gets a database collection
232
     *
233
     * @link http://www.php.net/manual/en/mongoclient.selectcollection.php
234
     * @param string $db The database name.
235
     * @param string $collection The collection name.
236
     * @return MongoCollection Returns a new collection object.
237
     * @throws Exception Throws Exception if the database or collection name is invalid.
238
     */
239
    public function selectCollection($db, $collection)
240
    {
241
        return new MongoCollection($this->selectDB($db), $collection);
242
    }
243
244
    /**
245
     * Gets a database
246
     *
247
     * @link http://www.php.net/manual/en/mongo.selectdb.php
248
     * @param string $name The database name.
249
     * @return MongoDB Returns a new db object.
250
     * @throws InvalidArgumentException
251
     */
252
    public function selectDB($name)
253
    {
254
        return new MongoDB($this, $name);
255
    }
256
257
    /**
258
     * {@inheritdoc}
259
     */
260
    public function setReadPreference($readPreference, array $tags = null)
261
    {
262
        return $this->setReadPreferenceFromParameters($readPreference, $tags);
263
    }
264
265
    /**
266
     * {@inheritdoc}
267
     */
268
    public function setWriteConcern($wstring, $wtimeout = 0)
269
    {
270
        return $this->setWriteConcernFromParameters($wstring, $wtimeout);
271
    }
272
273
    /**
274
     * Choose a new secondary for slaveOkay reads
275
     *
276
     * @link www.php.net/manual/en/mongo.switchslave.php
277
     * @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.
278
     * @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).
279
     */
280
    public function switchSlave()
281
    {
282
        return $this->server;
283
    }
284
285
    /**
286
     * String representation of this connection
287
     *
288
     * @link http://www.php.net/manual/en/mongoclient.tostring.php
289
     * @return string Returns hostname and port for this connection.
290
     */
291
    public function __toString()
292
    {
293
        return $this->server;
294
    }
295
296
    private function forceConnect()
297
    {
298
        $command = new \MongoDB\Driver\Command(['ping' => 1]);
299
        $this->manager->executeCommand('db', $command);
300
    }
301
302
}
303
304