Completed
Pull Request — master (#12)
by
unknown
02:42
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
    use Helper\Slave;
28
29
    const PROFILING_OFF = 0;
30
    const PROFILING_SLOW = 1;
31
    const PROFILING_ON = 2;
32
33
    /**
34
     * @var MongoClient
35
     */
36
    protected $connection;
37
38
    /**
39
     * @var \MongoDB\Database
40
     */
41
    protected $db;
42
43
    /**
44
     * @var string
45
     */
46
    protected $name;
47
48
    /**
49
     * Creates a new database
50
     *
51
     * 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()}.
52
     * @link http://www.php.net/manual/en/mongodb.construct.php
53
     * @param MongoClient $conn Database connection.
54
     * @param string $name Database name.
55
     * @throws Exception
56
     * @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...
57
     */
58
    public function __construct(MongoClient $conn, $name)
59
    {
60
        $this->connection = $conn;
61
        $this->name = $name;
62
63
        $this->setReadPreferenceFromArray($conn->getReadPreference());
64
        $this->setWriteConcernFromArray($conn->getWriteConcern());
65
66
        $this->createDatabaseObject();
67
    }
68
69
    /**
70
     * @return \MongoDB\Database
71
     * @internal
72
     */
73
    public function getDb()
74
    {
75
        return $this->db;
76
    }
77
78
    /**
79
     * The name of this database
80
     * @link http://www.php.net/manual/en/mongodb.--tostring.php
81
     * @return string Returns this database's name.
82
     */
83
    public function __toString()
84
    {
85
        return $this->name;
86
    }
87
88
    /**
89
     * Gets a collection
90
     *
91
     * @link http://www.php.net/manual/en/mongodb.get.php
92
     * @param string $name The name of the collection.
93
     * @return MongoCollection
94
     */
95
    public function __get($name)
96
    {
97
        // Handle w and wtimeout properties that replicate data stored in $readPreference
98
        if ($name === 'w' || $name === 'wtimeout') {
99
            return $this->getWriteConcern()[$name];
100
        }
101
102
        return $this->selectCollection($name);
103
    }
104
105
    /**
106
     * @param string $name
107
     * @param mixed $value
108
     */
109 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...
110
    {
111
        if ($name === 'w' || $name === 'wtimeout') {
112
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
113
            $this->createDatabaseObject();
114
        }
115
    }
116
117
    /**
118
     * (PECL mongo &gt;= 1.3.0)<br/>
119
     * @link http://www.php.net/manual/en/mongodb.getcollectionnames.php
120
     * Get all collections from this database
121
     * @return array Returns the names of the all the collections in the database as an
122
     * {@link http://www.php.net/manual/en/language.types.array.php array}.
123
     */
124
    public function getCollectionNames(array $options = [])
125
    {
126
        if (is_bool($options)) {
127
            $options = ['includeSystemCollections' => $options];
128
        }
129
130
        $collections = $this->db->listCollections($options);
131
132
        $getCollectionName = function (CollectionInfo $collectionInfo) {
133
            return $collectionInfo->getName();
134
        };
135
136
        return array_map($getCollectionName, (array) $collections);
137
    }
138
139
    /**
140
     * @return MongoClient
141
     * @internal This method is not part of the ext-mongo API
142
     */
143
    public function getConnection()
144
    {
145
        return $this->connection;
146
    }
147
148
    /**
149
     * (PECL mongo &gt;= 0.9.0)<br/>
150
     * Fetches toolkit for dealing with files stored in this database
151
     * @link http://www.php.net/manual/en/mongodb.getgridfs.php
152
     * @param string $prefix [optional] The prefix for the files and chunks collections.
153
     * @return MongoGridFS Returns a new gridfs object for this database.
154
     */
155
    public function getGridFS($prefix = "fs")
156
    {
157
        return new \MongoGridFS($this, $prefix, $prefix);
158
    }
159
160
    /**
161
     * (PECL mongo &gt;= 0.9.0)<br/>
162
     * Gets this database's profiling level
163
     * @link http://www.php.net/manual/en/mongodb.getprofilinglevel.php
164
     * @return int Returns the profiling level.
165
     */
166
    public function getProfilingLevel()
167
    {
168
        return static::PROFILING_OFF;
169
    }
170
171
    /**
172
     * (PECL mongo &gt;= 0.9.0)<br/>
173
     * Sets this database's profiling level
174
     * @link http://www.php.net/manual/en/mongodb.setprofilinglevel.php
175
     * @param int $level Profiling level.
176
     * @return int Returns the previous profiling level.
177
     */
178
    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...
179
    {
180
        return static::PROFILING_OFF;
181
    }
182
183
    /**
184
     * (PECL mongo &gt;= 0.9.0)<br/>
185
     * Drops this database
186
     * @link http://www.php.net/manual/en/mongodb.drop.php
187
     * @return array Returns the database response.
188
     */
189
    public function drop()
190
    {
191
        return $this->db->drop();
192
    }
193
194
    /**
195
     * Repairs and compacts this database
196
     * @link http://www.php.net/manual/en/mongodb.repair.php
197
     * @param bool $preserve_cloned_files [optional] <p>If cloned files should be kept if the repair fails.</p>
198
     * @param bool $backup_original_files [optional] <p>If original files should be backed up.</p>
199
     * @return array <p>Returns db response.</p>
200
     */
201
    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...
202
    {
203
        return [];
204
    }
205
206
    /**
207
     * (PECL mongo &gt;= 0.9.0)<br/>
208
     * Gets a collection
209
     * @link http://www.php.net/manual/en/mongodb.selectcollection.php
210
     * @param string $name <b>The collection name.</b>
211
     * @throws Exception if the collection name is invalid.
212
     * @return MongoCollection <p>
213
     * Returns a new collection object.
214
     * </p>
215
     */
216
    public function selectCollection($name)
217
    {
218
        return new MongoCollection($this, $name);
219
    }
220
221
    /**
222
     * {@inheritdoc}
223
     */
224
    public function setSlaveOkay($ok = true)
225
    {
226
        $result = $this->setSlaveOkayFromParameter($ok);
227
        $this->createDatabaseObject();
228
        return $result;
229
    }
230
231
    /**
232
     * Creates a collection
233
     * @link http://www.php.net/manual/en/mongodb.createcollection.php
234
     * @param string $name The name of the collection.
235
     * @param array $options [optional] <p>
236
     * <p>
237
     * An array containing options for the collections. Each option is its own
238
     * element in the options array, with the option name listed below being
239
     * the key of the element. The supported options depend on the MongoDB
240
     * server version. At the moment, the following options are supported:
241
     * </p>
242
     * <p>
243
     * <b>capped</b>
244
     * <p>
245
     * If the collection should be a fixed size.
246
     * </p>
247
     * </p>
248
     * <p>
249
     * <b>size</b>
250
     * <p>
251
     * If the collection is fixed size, its size in bytes.</p></p>
252
     * <p><b>max</b>
253
     * <p>If the collection is fixed size, the maximum number of elements to store in the collection.</p></p>
254
     * <i>autoIndexId</i>
255
     *
256
     * <p>
257
     * If capped is <b>TRUE</b> you can specify <b>FALSE</b> to disable the
258
     * automatic index created on the <em>_id</em> field.
259
     * Before MongoDB 2.2, the default value for
260
     * <em>autoIndexId</em> was <b>FALSE</b>.
261
     * </p>
262
     * </p>
263
     * @return MongoCollection <p>Returns a collection object representing the new collection.</p>
264
     */
265
    public function createCollection($name, $options)
266
    {
267
        $this->db->createCollection($name, $options);
268
        return $this->selectCollection($name);
269
    }
270
271
    /**
272
     * (PECL mongo &gt;= 0.9.0)<br/>
273
     * @deprecated Use MongoCollection::drop() instead.
274
     * Drops a collection
275
     * @link http://www.php.net/manual/en/mongodb.dropcollection.php
276
     * @param MongoCollection|string $coll MongoCollection or name of collection to drop.
277
     * @return array Returns the database response.
278
     */
279
    public function dropCollection($coll)
280
    {
281
        return $this->db->dropCollection((string) $coll);
282
    }
283
284
    /**
285
     * (PECL mongo &gt;= 0.9.0)<br/>
286
     * Get a list of collections in this database
287
     * @link http://www.php.net/manual/en/mongodb.listcollections.php
288
     * @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...
289
     * @return array Returns a list of MongoCollections.
290
     */
291
    public function listCollections(array $options = [])
292
    {
293
        return array_map([$this, 'selectCollection'], $this->getCollectionNames($options));
294
    }
295
296
    /**
297
     * (PECL mongo &gt;= 0.9.0)<br/>
298
     * Creates a database reference
299
     * @link http://www.php.net/manual/en/mongodb.createdbref.php
300
     * @param string $collection The collection to which the database reference will point.
301
     * @param mixed $document_or_id <p>
302
     * If an array or object is given, its <em>_id</em> field will be
303
     * used as the reference ID. If a {@see MongoId} or scalar
304
     * is given, it will be used as the reference ID.
305
     * </p>
306
     * @return array <p>Returns a database reference array.</p>
307
     * <p>
308
     * If an array without an <em>_id</em> field was provided as the
309
     * <em>document_or_id</em> parameter, <b>NULL</b> will be returned.
310
     * </p>
311
     */
312
    public function createDBRef($collection, $document_or_id)
313
    {
314
        if (is_object($document_or_id)) {
315
            $id = isset($document_or_id->_id) ? $document_or_id->_id : null;
316
//            $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...
317
        } elseif (is_array($document_or_id)) {
318
            if (! isset($document_or_id['_id'])) {
319
                return null;
320
            }
321
322
            $id = $document_or_id['_id'];
323
        } else {
324
            $id = $document_or_id;
325
        }
326
327
        return [
328
            '$ref' => $collection,
329
            '$id' => $id,
330
            '$db' => $this->name,
331
        ];
332
    }
333
334
335
    /**
336
     * (PECL mongo &gt;= 0.9.0)<br/>
337
     * Fetches the document pointed to by a database reference
338
     * @link http://www.php.net/manual/en/mongodb.getdbref.php
339
     * @param array $ref A database reference.
340
     * @return array Returns the document pointed to by the reference.
341
     */
342
    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...
343
    {
344
        $this->notImplemented();
345
    }
346
347
    /**
348
     * (PECL mongo &gt;= 0.9.3)<br/>
349
     * Runs JavaScript code on the database server.
350
     * @link http://www.php.net/manual/en/mongodb.execute.php
351
     * @param MongoCode|string $code Code to execute.
352
     * @param array $args [optional] Arguments to be passed to code.
353
     * @return array Returns the result of the evaluation.
354
     */
355
    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...
356
    {
357
        $this->notImplemented();
358
    }
359
360
    /**
361
     * Execute a database command
362
     * @link http://www.php.net/manual/en/mongodb.command.php
363
     * @param array $data The query to send.
364
     * @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...
365
     * This parameter is an associative array of the form
366
     * <em>array("optionname" =&gt; &lt;boolean&gt;, ...)</em>. Currently
367
     * supported options are:
368
     * </p><ul>
369
     * <li><p><em>"timeout"</em></p><p>Deprecated alias for <em>"socketTimeoutMS"</em>.</p></li>
370
     * </ul>
371
     * @return array Returns database response.
372
     * Every database response is always maximum one document,
373
     * which means that the result of a database command can never exceed 16MB.
374
     * The resulting document's structure depends on the command,
375
     * but most results will have the ok field to indicate success or failure and results containing an array of each of the resulting documents.
376
     */
377
    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...
378
    {
379
        try {
380
            $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
381
            $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...
382
383
            return iterator_to_array($cursor)[0];
384
        } 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...
385
            return [
386
                'ok' => 0,
387
                'errmsg' => $e->getMessage(),
388
                'code' => $e->getCode(),
389
            ];
390
        }
391
    }
392
393
    /**
394
     * (PECL mongo &gt;= 0.9.5)<br/>
395
     * Check if there was an error on the most recent db operation performed
396
     * @link http://www.php.net/manual/en/mongodb.lasterror.php
397
     * @return array Returns the error, if there was one.
398
     */
399
    public function lastError()
400
    {
401
        $this->notImplemented();
402
    }
403
404
    /**
405
     * (PECL mongo &gt;= 0.9.5)<br/>
406
     * Checks for the last error thrown during a database operation
407
     * @link http://www.php.net/manual/en/mongodb.preverror.php
408
     * @return array Returns the error and the number of operations ago it occurred.
409
     */
410
    public function prevError()
411
    {
412
        $this->notImplemented();
413
    }
414
415
    /**
416
     * (PECL mongo &gt;= 0.9.5)<br/>
417
     * Clears any flagged errors on the database
418
     * @link http://www.php.net/manual/en/mongodb.reseterror.php
419
     * @return array Returns the database response.
420
     */
421
    public function resetError()
422
    {
423
        $this->notImplemented();
424
    }
425
426
    /**
427
     * (PECL mongo &gt;= 0.9.5)<br/>
428
     * Creates a database error
429
     * @link http://www.php.net/manual/en/mongodb.forceerror.php
430
     * @return boolean Returns the database response.
431
     */
432
    public function forceError()
433
    {
434
        $this->notImplemented();
435
    }
436
437
    /**
438
     * (PECL mongo &gt;= 1.0.1)<br/>
439
     * Log in to this database
440
     * @link http://www.php.net/manual/en/mongodb.authenticate.php
441
     * @param string $username The username.
442
     * @param string $password The password (in plaintext).
443
     * @return array <p>Returns database response. If the login was successful, it will return 1.</p>
444
     * <p>
445
     * <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>
446
     * </span>
447
     * </code></div>
448
     * </div>
449
     * </p>
450
     * <p> If something went wrong, it will return </p>
451
     * <p>
452
     * <div class="example-contents">
453
     * <div class="phpcode"><code><span style="color: #000000">
454
     * <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>
455
     *         <p>("auth fails" could be another message, depending on database version and
456
     *         what went wrong)</p>
457
     */
458
    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...
459
    {
460
        $this->notImplemented();
461
    }
462
463
    /**
464
     * {@inheritdoc}
465
     */
466
    public function setReadPreference($readPreference, $tags = null)
467
    {
468
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
469
        $this->createDatabaseObject();
470
471
        return $result;
472
    }
473
474
    /**
475
     * {@inheritdoc}
476
     */
477
    public function setWriteConcern($wstring, $wtimeout = 0)
478
    {
479
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
480
        $this->createDatabaseObject();
481
482
        return $result;
483
    }
484
485
    protected function notImplemented()
486
    {
487
        throw new \Exception('Not implemented');
488
    }
489
490
    /**
491
     * @return \MongoDB\Database
492
     */
493 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...
494
    {
495
        $options = [
496
            'readPreference' => $this->readPreference,
497
            'writeConcern' => $this->writeConcern,
498
        ];
499
500
        if ($this->db === null) {
501
            $this->db = $this->connection->getClient()->selectDatabase($this->name, $options);
502
        } else {
503
            $this->db = $this->db->withOptions($options);
504
        }
505
    }
506
}
507