GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( d42e2b...ab132c )
by De
03:07
created

Client::isEmulationMode()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/**
4
 * This file is part of the PHPMongo package.
5
 *
6
 * (c) Dmytro Sokil <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Sokil\Mongo;
13
14
use \Psr\Log\LoggerInterface;
15
16
/**
17
 * Connection manager and factory to get database and collection instances.
18
 * 
19
 * @link https://github.com/sokil/php-mongo#connecting Connecting
20
 * @link https://github.com/sokil/php-mongo#selecting-database-and-collection Get database and collection instance
21
 */
22
class Client
23
{
24
    const DEFAULT_DSN = 'mongodb://127.0.0.1';
25
    
26
    private $dsn = self::DEFAULT_DSN;
27
    
28
    private $connectOptions = array();
29
    
30
    /**
31
     *
32
     * @var \MongoClient
33
     */
34
    private $mongoClient;
35
    
36
    private $databasePool = array();
37
    
38
    /**
39
     * @var array Database to class mapping
40
     */
41
    private $mapping = array();
42
    
43
        
44
    private $logger;
45
    
46
    private $currentDatabaseName;
47
48
    /**
49
     *
50
     * @var string version of MongoDb
51
     */
52
    private $dbVersion;
53
    
54
    private $debug = false;
55
56
    /**
57
     * 
58
     * @param string $dsn Data Source Name
59
     * @param array $options
60
     */
61
    public function __construct($dsn = null, array $options = null) {
62
        if ($dsn) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $dsn of type string|null is loosely compared to true; this is ambiguous if the string can be empty. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
63
            $this->setDsn($dsn);
64
        }
65
        
66
        if($options) {
67
            $this->setConnectOptions($options);
68
        }
69
    }
70
71
    /**
72
     * Check if client emulates ext-mongo driver by new ext-mongodb extension
73
     *
74
     * @return bool
75
     */
76
    public static function isEmulationMode()
77
    {
78
        return class_exists('\MongoDB\Driver\Manager');
79
    }
80
    
81
    /**
82
     * Set credentials to auth on db, specified in connect options or dsn.
83
     * If not specified - auth on admin db
84
     * 
85
     * @param type $username
86
     * @param type $password
87
     * @return \Sokil\Mongo\Client
88
     */
89
    public function setCredentials($username, $password)
90
    {
91
        $this->connectOptions['username'] = $username;
92
        $this->connectOptions['password'] = $password;
93
        
94
        return $this;
95
    }
96
    
97
    public function __get($name)
98
    {
99
        return $this->getDatabase($name);
100
    }
101
    
102
    /**
103
     * 
104
     * @return string Version of PHP driver
105
     */
106
    public function getVersion()
107
    {
108
        return \MongoClient::VERSION;
109
    }
110
111
    /**
112
     *
113
     * @return string version of mongo database
114
     */
115
    public function getDbVersion()
116
    {
117
        if ($this->dbVersion) {
118
            return $this->dbVersion;
119
        }
120
121
        $buildInfo = $this
122
            ->getDatabase('admin')
123
            ->executeCommand(array('buildinfo' => 1));
124
        
125
        $this->dbVersion = $buildInfo['version'];
126
        return $this->dbVersion;
127
    }
128
    
129
    public function setDsn($dsn)
130
    {
131
        $this->dsn = $dsn;
132
        return $this;
133
    }
134
    
135
    public function getDsn()
136
    {
137
        return $this->dsn;
138
    }
139
    
140
    /**
141
     * Set connect options
142
     * 
143
     * @link http://php.net/manual/en/mongoclient.construct.php connect options
144
     * @param array $options
145
     * @return \Sokil\Mongo\Client
146
     */
147
    public function setConnectOptions(array $options)
148
    {
149
        $this->connectOptions = $options;
150
        return $this;
151
    }
152
153
    public function getConnectOptions()
154
    {
155
        return $this->connectOptions;
156
    }
157
    
158
    /**
159
     * Set mongo's client
160
     * 
161
     * @param \MongoClient $client
162
     * @return \Sokil\Mongo\Client
163
     */
164
    public function setMongoClient(\MongoClient $client)
165
    {
166
        $this->mongoClient = $client;
167
        return $this;
168
    }
169
    
170
    /**
171
     * Get mongo connection instance
172
     *
173
     * @return \MongoClient
174
     * @throws Exception
175
     */
176
    public function getMongoClient()
177
    {
178
        if ($this->mongoClient) {
179
            return $this->mongoClient;
180
        }
181
182
        $this->mongoClient = new \MongoClient(
183
            $this->dsn,
184
            $this->connectOptions
185
        );
186
        
187
        return $this->mongoClient;
188
    }
189
    
190
    /**
191
     * Get list of all active connections through this client
192
     * 
193
     * @return array
194
     */
195
    public function getConnections()
196
    {
197
        return $this->mongoClient->getConnections();
198
    }
199
    
200
    /**
201
     * Map database and collection name to class.
202
     * 
203
     * Collection name -> array definition:
204
     *  ['acmeDatabaseName' => ['acmeCollectionName' => ['class' => '\Acme\Collection\SomeCollectionClass']]]
205
     * Collection name -> collection class name (deprecated: use definition array):
206
     *  ['acmeDatabaseName' => ['acmeCollectionName' => '\Acme\Collection\SomeCollectionClass']]
207
     * Collection's class namespace (deprecated: use definition array):
208
     *  ['acmeDatabaseName' => '\Acme\Collection']
209
     *
210
     * @param array $mapping classpath or class prefix
211
     * @return Client
212
     */
213
    public function map(array $mapping) {
214
        $this->mapping = $mapping;
215
        
216
        return $this;
217
    }
218
    
219
    /**
220
     * Get database instance
221
     *
222
     * @param string    $name   database name
223
     * @return Database
224
     */
225
    public function getDatabase($name = null) {
226
        
227
        if (!$name) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $name of type string|null is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
228
            $name = $this->getCurrentDatabaseName();
229
        }
230
231
        if (!isset($this->databasePool[$name])) {
232
            // init db
233
            $database = new Database($this, $name);
234
            if (isset($this->mapping[$name])) {
235
                $database->map($this->mapping[$name]);
236
            }
237
238
            // configure db
239
            $this->databasePool[$name] = $database;
240
        }
241
        
242
        return $this->databasePool[$name];
243
    }
244
    
245
    /**
246
     * Select database
247
     * 
248
     * @param string $name
249
     * @return \Sokil\Mongo\Client
250
     */
251
    public function useDatabase($name)
252
    {
253
        $this->currentDatabaseName = $name;
254
        return $this;
255
    }
256
257
    /**
258
     * Get name of current database
259
     *
260
     * @return string
261
     * @throws Exception
262
     */
263
    public function getCurrentDatabaseName()
264
    {
265
        if (!$this->currentDatabaseName) {
266
            throw new Exception('Database not selected');
267
        }
268
269
        return $this->currentDatabaseName;
270
    }
271
    
272
    /**
273
     * Get collection from previously selected database by self::useDatabase()
274
     * 
275
     * @param string $name
276
     * @return \Sokil\Mongo\Collection
277
     * @throws Exception
278
     */
279
    public function getCollection($name)
280
    {        
281
        return $this
282
            ->getDatabase($this->getCurrentDatabaseName())
283
            ->getCollection($name);
284
    }
285
    
286
    public function readPrimaryOnly()
287
    {
288
        $this->getMongoClient()->setReadPreference(\MongoClient::RP_PRIMARY);
289
        return $this;
290
    }
291
    
292
    public function readPrimaryPreferred(array $tags = null)
293
    {
294
        $this->getMongoClient()->setReadPreference(\MongoClient::RP_PRIMARY_PREFERRED, $tags);
295
        return $this;
296
    }
297
    
298
    public function readSecondaryOnly(array $tags = null)
299
    {
300
        $this->getMongoClient()->setReadPreference(\MongoClient::RP_SECONDARY, $tags);
301
        return $this;
302
    }
303
    
304
    public function readSecondaryPreferred(array $tags = null)
305
    {
306
        $this->getMongoClient()->setReadPreference(\MongoClient::RP_SECONDARY_PREFERRED, $tags);
307
        return $this;
308
    }
309
    
310
    public function readNearest(array $tags = null)
311
    {
312
        $this->getMongoClient()->setReadPreference(\MongoClient::RP_NEAREST, $tags);
313
        return $this;
314
    }
315
316
    public function getReadPreference()
317
    {
318
        return $this->getMongoClient()->getReadPreference();
319
    }
320
    
321
    public function setLogger(LoggerInterface $logger)
322
    {
323
        $this->logger = $logger;
324
        return $this;
325
    }
326
    
327
    /**
328
     * 
329
     * @return \Psr\Log\LoggerInterface
330
     */
331
    public function getLogger()
332
    {
333
        return $this->logger;
334
    }
335
336
    /**
337
     * Check if logger defined
338
     *
339
     * @return bool
340
     */
341
    public function hasLogger()
342
    {
343
        return (bool) $this->logger;
344
    }
345
346
    /**
347
     * Remove logger
348
     *
349
     * @return \Sokil\Mongo\Client
350
     */
351
    public function removeLogger()
352
    {
353
        $this->logger = null;
354
        return $this;
355
    }
356
357
    /**
358
     * Enable or disable debug mode
359
     */
360
    public function debug($enabled = true)
361
    {
362
        $this->debug = (bool) $enabled;
363
        return $this;
364
    }
365
366
    /**
367
     * Check state of debug mode
368
     */
369
    public function isDebugEnabled()
370
    {
371
        return $this->debug;
372
    }
373
374
    /**
375
     * Define write concern on whole requests
376
     *
377
     * @param string|integer $w write concern
378
     * @param int $timeout timeout in milliseconds
379
     * @return \Sokil\Mongo\Client
380
     *
381
     * @throws \Sokil\Mongo\Exception
382
     */
383
    public function setWriteConcern($w, $timeout = 10000)
384
    {
385
        if (!$this->getMongoClient()->setWriteConcern($w, (int) $timeout)) {
386
            throw new Exception('Error setting write concern');
387
        }
388
        
389
        return $this;
390
    }
391
    
392
    /**
393
     * Define unacknowledged write concern on whole requests
394
     *
395
     * @param int $timeout timeout in milliseconds
396
     * @return \Sokil\Mongo\Client
397
     */
398
    public function setUnacknowledgedWriteConcern($timeout = 10000)
399
    {
400
        $this->setWriteConcern(0, (int) $timeout);
401
        return $this;
402
    }
403
    
404
    /**
405
     * Define majority write concern on whole requests
406
     *
407
     * @param int $timeout timeout in milliseconds
408
     * @return \Sokil\Mongo\Client
409
     */
410
    public function setMajorityWriteConcern($timeout = 10000)
411
    {
412
        $this->setWriteConcern('majority', (int) $timeout);
413
        return $this;
414
    }
415
416
    /**
417
     * Get currently active write concern on connection level
418
     *
419
     * @return string|int
420
     */
421
    public function getWriteConcern()
422
    {
423
        return $this->getMongoClient()->getWriteConcern();
424
    }
425
426
    /**
427
     * Create new persistence manager
428
     * @return \Sokil\Mongo\Persistence
429
     */
430
    public function createPersistence()
431
    {
432
        // operations of same type and in same collection executed at once 
433
        if (version_compare($this->getVersion(), '1.5', '>=') && version_compare($this->getDbVersion(), '2.6', '>=')) {
434
            return new Persistence();
435
        }
436
437
        // all operations executed separately
438
        return new PersistenceLegacy();
439
    }
440
}
441