Completed
Push — master ( b3f7d4...9578a4 )
by Andreas
02:50
created

MongoDB::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\Model\CollectionInfo;
18
19
/**
20
 * Instances of this class are used to interact with a database.
21
 * @link http://www.php.net/manual/en/class.mongodb.php
22
 */
23
class MongoDB
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...
24
{
25
    use Helper\ReadPreference;
26
    use Helper\WriteConcern;
27
28
    const PROFILING_OFF = 0;
29
    const PROFILING_SLOW = 1;
30
    const PROFILING_ON = 2;
31
32
    /**
33
     * @var MongoClient
34
     */
35
    protected $connection;
36
37
    /**
38
     * @var \MongoDB\Database
39
     */
40
    protected $db;
41
42
    /**
43
     * @var string
44
     */
45
    protected $name;
46
47
    /**
48
     * Creates a new database
49
     *
50
     * This method is not meant to be called directly. The preferred way to create an instance of MongoDB is through {@see Mongo::__get()} or {@see Mongo::selectDB()}.
51
     * @link http://www.php.net/manual/en/mongodb.construct.php
52
     * @param MongoClient $conn Database connection.
53
     * @param string $name Database name.
54
     * @throws Exception
55
     * @return MongoDB Returns the database.
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
56
     */
57
    public function __construct(MongoClient $conn, $name)
58
    {
59
        $this->connection = $conn;
60
        $this->name = $name;
61
62
        $this->setReadPreferenceFromArray($conn->getReadPreference());
63
        $this->setWriteConcernFromArray($conn->getWriteConcern());
64
65
        $this->createDatabaseObject();
66
    }
67
68
    /**
69
     * @return \MongoDB\Database
70
     * @internal
71
     */
72
    public function getDb()
73
    {
74
        return $this->db;
75
    }
76
77
    /**
78
     * The name of this database
79
     * @link http://www.php.net/manual/en/mongodb.--tostring.php
80
     * @return string Returns this database's name.
81
     */
82
    public function __toString()
83
    {
84
        return $this->name;
85
    }
86
87
    /**
88
     * Gets a collection
89
     *
90
     * @link http://www.php.net/manual/en/mongodb.get.php
91
     * @param string $name The name of the collection.
92
     * @return MongoCollection
93
     */
94
    public function __get($name)
95
    {
96
        // Handle w and wtimeout properties that replicate data stored in $readPreference
97
        if ($name === 'w' || $name === 'wtimeout') {
98
            return $this->getWriteConcern()[$name];
99
        }
100
101
        return $this->selectCollection($name);
102
    }
103
104
    /**
105
     * @param string $name
106
     * @param mixed $value
107
     */
108 View Code Duplication
    public function __set($name, $value)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
109
    {
110
        if ($name === 'w' || $name === 'wtimeout') {
111
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
112
            $this->createDatabaseObject();
113
        }
114
    }
115
116
    /**
117
     * (PECL mongo &gt;= 1.3.0)<br/>
118
     * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
119
     * Get all collections from this database
120
     * @return array Returns the names of the all the collections in the database as an
121
     * {@link http://www.php.net/manual/en/language.types.array.php array}.
122
     */
123
    public function getCollectionNames(array $options = [])
124
    {
125
        if (is_bool($options)) {
126
            $options = ['includeSystemCollections' => $options];
127
        }
128
129
        $collections = $this->db->listCollections($options);
130
131
        $getCollectionName = function (CollectionInfo $collectionInfo) {
132
            return $collectionInfo->getName();
133
        };
134
135
        return array_map($getCollectionName, (array) $collections);
136
    }
137
138
    /**
139
     * @return MongoClient
140
     * @internal This method is not part of the ext-mongo API
141
     */
142
    public function getConnection()
143
    {
144
        return $this->connection;
145
    }
146
147
    /**
148
     * (PECL mongo &gt;= 0.9.0)<br/>
149
     * Fetches toolkit for dealing with files stored in this database
150
     * @link http://www.php.net/manual/en/mongodb.getgridfs.php
151
     * @param string $prefix [optional] The prefix for the files and chunks collections.
152
     * @return MongoGridFS Returns a new gridfs object for this database.
153
     */
154
    public function getGridFS($prefix = "fs")
155
    {
156
        return new \MongoGridFS($this, $prefix, $prefix);
157
    }
158
159
    /**
160
     * (PECL mongo &gt;= 0.9.0)<br/>
161
     * Gets this database's profiling level
162
     * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
163
     * @return int Returns the profiling level.
164
     */
165
    public function getProfilingLevel()
166
    {
167
        return static::PROFILING_OFF;
168
    }
169
170
    /**
171
     * (PECL mongo &gt;= 1.1.0)<br/>
172
     * Get slaveOkay setting for this database
173
     * @link http://www.php.net/manual/en/mongodb.getslaveokay.php
174
     * @return bool Returns the value of slaveOkay for this instance.
175
     */
176
    public function getSlaveOkay()
177
    {
178
        return false;
179
    }
180
181
    /**
182
     * (PECL mongo &gt;= 0.9.0)<br/>
183
     * Sets this database's profiling level
184
     * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
185
     * @param int $level Profiling level.
186
     * @return int Returns the previous profiling level.
187
     */
188
    public function setProfilingLevel($level)
0 ignored issues
show
Unused Code introduced by
The parameter $level 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...
189
    {
190
        return static::PROFILING_OFF;
191
    }
192
193
    /**
194
     * (PECL mongo &gt;= 0.9.0)<br/>
195
     * Drops this database
196
     * @link http://www.php.net/manual/en/mongodb.drop.php
197
     * @return array Returns the database response.
198
     */
199
    public function drop()
200
    {
201
        return $this->db->drop();
202
    }
203
204
    /**
205
     * Repairs and compacts this database
206
     * @link http://www.php.net/manual/en/mongodb.repair.php
207
     * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
208
     * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
209
     * @return array <p>Returns db response.</p>
210
     */
211
    public function repair($preserve_cloned_files = FALSE, $backup_original_files = FALSE)
0 ignored issues
show
Unused Code introduced by
The parameter $preserve_cloned_files 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 $backup_original_files 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...
212
    {
213
        return [];
214
    }
215
216
    /**
217
     * (PECL mongo &gt;= 0.9.0)<br/>
218
     * Gets a collection
219
     * @link http://www.php.net/manual/en/mongodb.selectcollection.php
220
     * @param string $name <b>The collection name.</b>
221
     * @throws Exception if the collection name is invalid.
222
     * @return MongoCollection <p>
223
     * Returns a new collection object.
224
     * </p>
225
     */
226
    public function selectCollection($name)
227
    {
228
        return new MongoCollection($this, $name);
229
    }
230
231
    /**
232
     * (PECL mongo &gt;= 1.1.0)<br/>
233
     * Change slaveOkay setting for this database
234
     * @link http://php.net/manual/en/mongodb.setslaveokay.php
235
     * @param bool $ok [optional] <p>
236
     * If reads should be sent to secondary members of a replica set for all
237
     * possible queries using this {@link http://www.php.net/manual/en/class.mongodb.php MongoDB} instance.
238
     * </p>
239
     * @return bool Returns the former value of slaveOkay for this instance.
240
     */
241
    public function setSlaveOkay ($ok = true)
0 ignored issues
show
Unused Code introduced by
The parameter $ok 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...
242
    {
243
        return false;
244
    }
245
246
    /**
247
     * Creates a collection
248
     * @link http://www.php.net/manual/en/mongodb.createcollection.php
249
     * @param string $name The name of the collection.
250
     * @param array $options [optional] <p>
251
     * <p>
252
     * An array containing options for the collections. Each option is its own
253
     * element in the options array, with the option name listed below being
254
     * the key of the element. The supported options depend on the MongoDB
255
     * server version. At the moment, the following options are supported:
256
     * </p>
257
     * <p>
258
     * <b>capped</b>
259
     * <p>
260
     * If the collection should be a fixed size.
261
     * </p>
262
     * </p>
263
     * <p>
264
     * <b>size</b>
265
     * <p>
266
     * If the collection is fixed size, its size in bytes.</p></p>
267
     * <p><b>max</b>
268
     * <p>If the collection is fixed size, the maximum number of elements to store in the collection.</p></p>
269
     * <i>autoIndexId</i>
270
     *
271
     * <p>
272
     * If capped is <b>TRUE</b> you can specify <b>FALSE</b> to disable the
273
     * automatic index created on the <em>_id</em> field.
274
     * Before MongoDB 2.2, the default value for
275
     * <em>autoIndexId</em> was <b>FALSE</b>.
276
     * </p>
277
     * </p>
278
     * @return MongoCollection <p>Returns a collection object representing the new collection.</p>
279
     */
280
    public function createCollection($name, $options)
281
    {
282
        $this->db->createCollection($name, $options);
283
        return $this->selectCollection($name);
284
    }
285
286
    /**
287
     * (PECL mongo &gt;= 0.9.0)<br/>
288
     * @deprecated Use MongoCollection::drop() instead.
289
     * Drops a collection
290
     * @link http://www.php.net/manual/en/mongodb.dropcollection.php
291
     * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
292
     * @return array Returns the database response.
293
     */
294
    public function dropCollection($coll)
295
    {
296
        return $this->db->dropCollection((string) $coll);
297
    }
298
299
    /**
300
     * (PECL mongo &gt;= 0.9.0)<br/>
301
     * Get a list of collections in this database
302
     * @link http://www.php.net/manual/en/mongodb.listcollections.php
303
     * @param bool $includeSystemCollections [optional] <p>Include system collections.</p>
0 ignored issues
show
Bug introduced by
There is no parameter named $includeSystemCollections. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
304
     * @return array Returns a list of MongoCollections.
305
     */
306
    public function listCollections(array $options = [])
307
    {
308
        return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
309
    }
310
311
    /**
312
     * (PECL mongo &gt;= 0.9.0)<br/>
313
     * Creates a database reference
314
     * @link http://www.php.net/manual/en/mongodb.createdbref.php
315
     * @param string $collection The collection to which the database reference will point.
316
     * @param mixed $document_or_id <p>
317
     * If an array or object is given, its <em>_id</em> field will be
318
     * used as the reference ID. If a {@see MongoId} or scalar
319
     * is given, it will be used as the reference ID.
320
     * </p>
321
     * @return array <p>Returns a database reference array.</p>
322
     * <p>
323
     * If an array without an <em>_id</em> field was provided as the
324
     * <em>document_or_id</em> parameter, <b>NULL</b> will be returned.
325
     * </p>
326
     */
327
    public function createDBRef($collection, $document_or_id)
328
    {
329
        if (is_object($document_or_id)) {
330
            $id = isset($document_or_id->_id) ? $document_or_id->_id : null;
331
//            $id = $document_or_id->_id ?? null;
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
332
        } elseif (is_array($document_or_id)) {
333
            if (! isset($document_or_id['_id'])) {
334
                return null;
335
            }
336
337
            $id = $document_or_id['_id'];
338
        } else {
339
            $id = $document_or_id;
340
        }
341
342
        return [
343
            '$ref' => $collection,
344
            '$id' => $id,
345
            '$db' => $this->name,
346
        ];
347
    }
348
349
350
    /**
351
     * (PECL mongo &gt;= 0.9.0)<br/>
352
     * Fetches the document pointed to by a database reference
353
     * @link http://www.php.net/manual/en/mongodb.getdbref.php
354
     * @param array $ref A database reference.
355
     * @return array Returns the document pointed to by the reference.
356
     */
357
    public function getDBRef(array $ref)
0 ignored issues
show
Unused Code introduced by
The parameter $ref 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...
358
    {
359
        $this->notImplemented();
360
    }
361
362
    /**
363
     * (PECL mongo &gt;= 0.9.3)<br/>
364
     * Runs JavaScript code on the database server.
365
     * @link http://www.php.net/manual/en/mongodb.execute.php
366
     * @param MongoCode|string $code Code to execute.
367
     * @param array $args [optional] Arguments to be passed to code.
368
     * @return array Returns the result of the evaluation.
369
     */
370
    public function execute($code, array $args = array())
0 ignored issues
show
Unused Code introduced by
The parameter $code 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 $args 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...
371
    {
372
        $this->notImplemented();
373
    }
374
375
    /**
376
     * Execute a database command
377
     * @link http://www.php.net/manual/en/mongodb.command.php
378
     * @param array $data The query to send.
379
     * @param array() $options [optional] <p>
0 ignored issues
show
Documentation introduced by
The doc-type array() could not be parsed: Expected "|" or "end of type", but got "(" at position 5. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
380
     * This parameter is an associative array of the form
381
     * <em>array("optionname" =&gt; &lt;boolean&gt;, ...)</em>. Currently
382
     * supported options are:
383
     * </p><ul>
384
     * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
385
     * </ul>
386
     * @return array Returns database response.
387
     * Every database response is always maximum one document,
388
     * which means that the result of a database command can never exceed 16MB.
389
     * The resulting document's structure depends on the command,
390
     * but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
391
     */
392
    public function command(array $data, $options, &$hash)
0 ignored issues
show
Unused Code introduced by
The parameter $options 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 $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...
393
    {
394
        try {
395
            $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
396
            $cursor->setReadPreference($this->getReadPreference());
0 ignored issues
show
Documentation introduced by
$this->getReadPreference() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
397
398
            return iterator_to_array($cursor)[0];
399
        } catch (\MongoDB\Driver\Exception\RuntimeException $e) {
0 ignored issues
show
Bug introduced by
The class MongoDB\Driver\Exception\RuntimeException 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...
400
            return [
401
                'ok' => 0,
402
                'errmsg' => $e->getMessage(),
403
                'code' => $e->getCode(),
404
            ];
405
        }
406
    }
407
408
    /**
409
     * (PECL mongo &gt;= 0.9.5)<br/>
410
     * Check if there was an error on the most recent db operation performed
411
     * @link http://www.php.net/manual/en/mongodb.lasterror.php
412
     * @return array Returns the error, if there was one.
413
     */
414
    public function lastError()
415
    {
416
        $this->notImplemented();
417
    }
418
419
    /**
420
     * (PECL mongo &gt;= 0.9.5)<br/>
421
     * Checks for the last error thrown during a database operation
422
     * @link http://www.php.net/manual/en/mongodb.preverror.php
423
     * @return array Returns the error and the number of operations ago it occurred.
424
     */
425
    public function prevError()
426
    {
427
        $this->notImplemented();
428
    }
429
430
    /**
431
     * (PECL mongo &gt;= 0.9.5)<br/>
432
     * Clears any flagged errors on the database
433
     * @link http://www.php.net/manual/en/mongodb.reseterror.php
434
     * @return array Returns the database response.
435
     */
436
    public function resetError()
437
    {
438
        $this->notImplemented();
439
    }
440
441
    /**
442
     * (PECL mongo &gt;= 0.9.5)<br/>
443
     * Creates a database error
444
     * @link http://www.php.net/manual/en/mongodb.forceerror.php
445
     * @return boolean Returns the database response.
446
     */
447
    public function forceError()
448
    {
449
        $this->notImplemented();
450
    }
451
452
    /**
453
     * (PECL mongo &gt;= 1.0.1)<br/>
454
     * Log in to this database
455
     * @link http://www.php.net/manual/en/mongodb.authenticate.php
456
     * @param string $username The username.
457
     * @param string $password The password (in plaintext).
458
     * @return array <p>Returns database response. If the login was successful, it will return 1.</p>
459
     * <p>
460
     * <span style="color: #0000BB">&lt;?php<br></span><span style="color: #007700">array(</span><span style="color: #DD0000">"ok"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">1</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?&gt;</span>
461
     * </span>
462
     * </code></div>
463
     * </div>
464
     * </p>
465
     * <p> If something went wrong, it will return </p>
466
     * <p>
467
     * <div class="example-contents">
468
     * <div class="phpcode"><code><span style="color: #000000">
469
     * <span style="color: #0000BB">&lt;?php<br></span><span style="color: #007700">array(</span><span style="color: #DD0000">"ok"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #0000BB">0</span><span style="color: #007700">,&nbsp;</span><span style="color: #DD0000">"errmsg"&nbsp;</span><span style="color: #007700">=&gt;&nbsp;</span><span style="color: #DD0000">"auth&nbsp;fails"</span><span style="color: #007700">);<br></span><span style="color: #0000BB">?&gt;</span></p>
470
     *         <p>("auth fails" could be another message, depending on database version and
471
     *         what went wrong)</p>
472
     */
473
    public function authenticate($username, $password)
0 ignored issues
show
Unused Code introduced by
The parameter $username 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 $password 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...
474
    {
475
        $this->notImplemented();
476
    }
477
478
    /**
479
     * {@inheritdoc}
480
     */
481
    public function setReadPreference($readPreference, $tags = null)
482
    {
483
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
484
        $this->createDatabaseObject();
485
486
        return $result;
487
    }
488
489
    /**
490
     * {@inheritdoc}
491
     */
492
    public function setWriteConcern($wstring, $wtimeout = 0)
493
    {
494
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
495
        $this->createDatabaseObject();
496
497
        return $result;
498
    }
499
500
    protected function notImplemented()
501
    {
502
        throw new \Exception('Not implemented');
503
    }
504
505
    /**
506
     * @return \MongoDB\Database
507
     */
508 View Code Duplication
    private function createDatabaseObject()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
509
    {
510
        $options = [
511
            'readPreference' => $this->readPreference,
512
            'writeConcern' => $this->writeConcern,
513
        ];
514
515
        if ($this->db === null) {
516
            $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
517
        } else {
518
            $this->db = $this->db->withOptions($options);
519
        }
520
    }
521
}
522