Completed
Push — master ( 53b41d...ee831b )
by Andreas
06:29
created

MongoCollection::update()   B

Complexity

Conditions 6
Paths 20

Size

Total Lines 41
Code Lines 30

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 41
rs 8.439
cc 6
eloc 30
nc 20
nop 3
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\TypeConverter;
18
use Alcaeus\MongoDbAdapter\ExceptionConverter;
19
20
/**
21
 * Represents a database collection.
22
 * @link http://www.php.net/manual/en/class.mongocollection.php
23
 */
24
class MongoCollection
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\SlaveOkay;
28
    use Helper\WriteConcern;
29
30
    const ASCENDING = 1;
31
    const DESCENDING = -1;
32
33
    /**
34
     * @var MongoDB
35
     */
36
    public $db = NULL;
37
38
    /**
39
     * @var string
40
     */
41
    protected $name;
42
43
    /**
44
     * @var \MongoDB\Collection
45
     */
46
    protected $collection;
47
48
    /**
49
     * Creates a new collection
50
     *
51
     * @link http://www.php.net/manual/en/mongocollection.construct.php
52
     * @param MongoDB $db Parent database.
53
     * @param string $name Name for this collection.
54
     * @throws Exception
55
     * @return MongoCollection
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(MongoDB $db, $name)
58
    {
59
        $this->checkCollectionName($name);
60
        $this->db = $db;
61
        $this->name = $name;
62
63
        $this->setReadPreferenceFromArray($db->getReadPreference());
64
        $this->setWriteConcernFromArray($db->getWriteConcern());
65
66
        $this->createCollectionObject();
67
    }
68
69
    /**
70
     * Gets the underlying collection for this object
71
     *
72
     * @internal This part is not of the ext-mongo API and should not be used
73
     * @return \MongoDB\Collection
74
     */
75
    public function getCollection()
76
    {
77
        return $this->collection;
78
    }
79
80
    /**
81
     * String representation of this collection
82
     *
83
     * @link http://www.php.net/manual/en/mongocollection.--tostring.php
84
     * @return string Returns the full name of this collection.
85
     */
86
    public function __toString()
87
    {
88
        return (string) $this->db . '.' . $this->name;
89
    }
90
91
    /**
92
     * Gets a collection
93
     *
94
     * @link http://www.php.net/manual/en/mongocollection.get.php
95
     * @param string $name The next string in the collection name.
96
     * @return MongoCollection
97
     */
98
    public function __get($name)
99
    {
100
        // Handle w and wtimeout properties that replicate data stored in $readPreference
101
        if ($name === 'w' || $name === 'wtimeout') {
102
            return $this->getWriteConcern()[$name];
103
        }
104
105
        return $this->db->selectCollection($this->name . '.' . $name);
106
    }
107
108
    /**
109
     * @param string $name
110
     * @param mixed $value
111
     */
112 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...
113
    {
114
        if ($name === 'w' || $name === 'wtimeout') {
115
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
116
            $this->createCollectionObject();
117
        }
118
    }
119
120
    /**
121
     * Perform an aggregation using the aggregation framework
122
     *
123
     * @link http://www.php.net/manual/en/mongocollection.aggregate.php
124
     * @param array $pipeline
125
     * @param array $op
126
     * @return array
127
     */
128
    public function aggregate(array $pipeline, array $op = [])
129
    {
130
        if (! TypeConverter::isNumericArray($pipeline)) {
131
            $pipeline = [];
132
            $options = [];
133
134
            $i = 0;
135
            foreach (func_get_args() as $operator) {
136
                $i++;
137
                if (! is_array($operator)) {
138
                    trigger_error("Argument $i is not an array", E_WARNING);
139
                    return;
140
                }
141
142
                $pipeline[] = $operator;
143
            }
144
        } else {
145
            $options = $op;
146
        }
147
148
        $command = [
149
            'aggregate' => $this->name,
150
            'pipeline' => $pipeline
151
        ];
152
153
        $command += $options;
154
155
        try {
156
            return $this->db->command($command);
157
        } catch (MongoCursorTimeoutException $e) {
158
            throw new MongoExecutionTimeoutException($e->getMessage(), $e->getCode(), $e);
159
        }
160
161
    }
162
163
    /**
164
     * Execute an aggregation pipeline command and retrieve results through a cursor
165
     *
166
     * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
167
     * @param array $pipeline
168
     * @param array $options
169
     * @return MongoCommandCursor
170
     */
171
    public function aggregateCursor(array $pipeline, array $options = [])
172
    {
173
        // Build command manually, can't use mongo-php-library here
174
        $command = [
175
            'aggregate' => $this->name,
176
            'pipeline' => $pipeline
177
        ];
178
179
        // Convert cursor option
180
        if (! isset($options['cursor'])) {
181
            $options['cursor'] = true;
182
        }
183
184
        $command += $options;
185
186
        $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
187
        $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...
188
189
        return $cursor;
190
    }
191
192
    /**
193
     * Returns this collection's name
194
     *
195
     * @link http://www.php.net/manual/en/mongocollection.getname.php
196
     * @return string
197
     */
198
    public function getName()
199
    {
200
        return $this->name;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function setReadPreference($readPreference, $tags = null)
207
    {
208
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
209
        $this->createCollectionObject();
210
211
        return $result;
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function setWriteConcern($wstring, $wtimeout = 0)
218
    {
219
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
220
        $this->createCollectionObject();
221
222
        return $result;
223
    }
224
225
    /**
226
     * Drops this collection
227
     *
228
     * @link http://www.php.net/manual/en/mongocollection.drop.php
229
     * @return array Returns the database response.
230
     */
231
    public function drop()
232
    {
233
        return TypeConverter::toLegacy($this->collection->drop());
234
    }
235
236
    /**
237
     * Validates this collection
238
     *
239
     * @link http://www.php.net/manual/en/mongocollection.validate.php
240
     * @param bool $scan_data Only validate indices, not the base collection.
241
     * @return array Returns the database's evaluation of this object.
242
     */
243
    public function validate($scan_data = FALSE)
244
    {
245
        $command = [
246
            'validate' => $this->name,
247
            'full'     => $scan_data,
248
        ];
249
250
        return $this->db->command($command);
251
    }
252
253
    /**
254
     * Inserts an array into the collection
255
     *
256
     * @link http://www.php.net/manual/en/mongocollection.insert.php
257
     * @param array|object $a
258
     * @param array $options
259
     * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
260
     * @throws MongoCursorException if the "w" option is set and the write fails.
261
     * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
262
     * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
263
     */
264
    public function insert(&$a, array $options = [])
265
    {
266
        if (! $this->ensureDocumentHasMongoId($a)) {
267
            trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
268
            return;
269
        }
270
271
        if (! count((array)$a)) {
272
            throw new \MongoException('document must be an array or object');
273
        }
274
275
        try {
276
            $result = $this->collection->insertOne(
277
                TypeConverter::fromLegacy($a),
278
                $this->convertWriteConcernOptions($options)
279
            );
280
        } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\BulkWriteException 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...
281
            $writeResult = $e->getWriteResult();
282
            $writeError = $writeResult->getWriteErrors()[0];
283
            return [
284
                'ok' => 0.0,
285
                'n' => 0,
286
                'err' => $writeError->getCode(),
287
                'errmsg' => $writeError->getMessage(),
288
            ];
289
        } 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...
290
            ExceptionConverter::toLegacy($e);
291
        }
292
293
        if (! $result->isAcknowledged()) {
294
            return true;
295
        }
296
297
        return [
298
            'ok' => 1.0,
299
            'n' => 0,
300
            'err' => null,
301
            'errmsg' => null,
302
        ];
303
    }
304
305
    /**
306
     * Inserts multiple documents into this collection
307
     *
308
     * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
309
     * @param array $a An array of arrays.
310
     * @param array $options Options for the inserts.
311
     * @throws MongoCursorException
312
     * @return mixed If "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.
313
     */
314
    public function batchInsert(array &$a, array $options = [])
315
    {
316
        if (empty($a)) {
317
            throw new \MongoException('No write ops were included in the batch');
318
        }
319
320
        $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
321
322
        foreach ($a as $key => $item) {
323
            try {
324
                if (! $this->ensureDocumentHasMongoId($a[$key])) {
325
                    if ($continueOnError) {
326
                        unset($a[$key]);
327
                    } else {
328
                        trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
329
                        return;
330
                    }
331
                }
332
            } catch (MongoException $e) {
333
                if ( ! $continueOnError) {
334
                    throw $e;
335
                }
336
            }
337
        }
338
339
        try {
340
            $result = $this->collection->insertMany(
341
                TypeConverter::fromLegacy(array_values($a)),
342
                $this->convertWriteConcernOptions($options)
343
            );
344
        } 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...
345
            ExceptionConverter::toLegacy($e);
346
        }
347
348
        if (! $result->isAcknowledged()) {
349
            return true;
350
        }
351
352
        return [
353
            'connectionId' => 0,
354
            'n' => 0,
355
            'syncMillis' => 0,
356
            'writtenTo' => null,
357
            'err' => null,
358
            'errmsg' => null,
359
        ];
360
    }
361
362
    /**
363
     * Update records based on a given criteria
364
     *
365
     * @link http://www.php.net/manual/en/mongocollection.update.php
366
     * @param array $criteria Description of the objects to update.
367
     * @param array $newobj The object with which to update the matching records.
368
     * @param array $options
369
     * @throws MongoCursorException
370
     * @return boolean
371
     */
372
    public function update(array $criteria , array $newobj, array $options = [])
373
    {
374
        $multiple = isset($options['multiple']) ? $options['multiple'] : false;
375
        $method = $multiple ? 'updateMany' : 'updateOne';
376
        unset($options['multiple']);
377
378
        try {
379
            /** @var \MongoDB\UpdateResult $result */
380
            $result = $this->collection->$method(
381
                TypeConverter::fromLegacy($criteria),
382
                TypeConverter::fromLegacy($newobj),
383
                $this->convertWriteConcernOptions($options)
384
            );
385
        } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\BulkWriteException 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...
386
            $writeResult = $e->getWriteResult();
387
            $writeError = $writeResult->getWriteErrors()[0];
388
            return [
389
                'ok' => 0.0,
390
                'nModified' => $writeResult->getModifiedCount(),
391
                'n' => $writeResult->getMatchedCount(),
392
                'err' => $writeError->getCode(),
393
                'errmsg' => $writeError->getMessage(),
394
                'updatedExisting' => $writeResult->getUpsertedCount() == 0,
395
            ];
396
        } 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...
397
            ExceptionConverter::toLegacy($e);
398
        }
399
400
        if (! $result->isAcknowledged()) {
401
            return true;
402
        }
403
404
        return [
405
            'ok' => 1.0,
406
            'nModified' => $result->getModifiedCount(),
407
            'n' => $result->getMatchedCount(),
408
            'err' => null,
409
            'errmsg' => null,
410
            'updatedExisting' => $result->getUpsertedCount() == 0,
411
        ];
412
    }
413
414
    /**
415
     * Remove records from this collection
416
     *
417
     * @link http://www.php.net/manual/en/mongocollection.remove.php
418
     * @param array $criteria Query criteria for the documents to delete.
419
     * @param array $options An array of options for the remove operation.
420
     * @throws MongoCursorException
421
     * @throws MongoCursorTimeoutException
422
     * @return bool|array Returns an array containing the status of the removal
423
     * if the "w" option is set. Otherwise, returns TRUE.
424
     */
425
    public function remove(array $criteria = [], array $options = [])
426
    {
427
        $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
428
        $method = $multiple ? 'deleteMany' : 'deleteOne';
429
430
        try {
431
            /** @var \MongoDB\DeleteResult $result */
432
            $result = $this->collection->$method(
433
                TypeConverter::fromLegacy($criteria),
434
                $this->convertWriteConcernOptions($options)
435
            );
436
        } 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...
437
            ExceptionConverter::toLegacy($e);
438
        }
439
440
        if (! $result->isAcknowledged()) {
441
            return true;
442
        }
443
444
        return [
445
            'ok' => 1.0,
446
            'n' => $result->getDeletedCount(),
447
            'err' => null,
448
            'errmsg' => null
449
        ];
450
    }
451
452
    /**
453
     * Querys this collection
454
     *
455
     * @link http://www.php.net/manual/en/mongocollection.find.php
456
     * @param array $query The fields for which to search.
457
     * @param array $fields Fields of the results to return.
458
     * @return MongoCursor
459
     */
460 View Code Duplication
    public function find(array $query = [], array $fields = [])
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...
461
    {
462
        $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
463
        $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...
464
465
        return $cursor;
466
    }
467
468
    /**
469
     * Retrieve a list of distinct values for the given key across a collection
470
     *
471
     * @link http://www.php.net/manual/ru/mongocollection.distinct.php
472
     * @param string $key The key to use.
473
     * @param array $query An optional query parameters
474
     * @return array|bool Returns an array of distinct values, or FALSE on failure
475
     */
476
    public function distinct($key, array $query = [])
477
    {
478
        try {
479
            return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, $query));
480
        } 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...
481
            return false;
482
        }
483
    }
484
485
    /**
486
     * Update a document and return it
487
     *
488
     * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
489
     * @param array $query The query criteria to search for.
490
     * @param array $update The update criteria.
491
     * @param array $fields Optionally only return these fields.
492
     * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
493
     * @return array Returns the original document, or the modified document when new is set.
494
     */
495
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
496
    {
497
        $query = TypeConverter::fromLegacy($query);
498
        try {
499
            if (isset($options['remove'])) {
500
                unset($options['remove']);
501
                $document = $this->collection->findOneAndDelete($query, $options);
502
            } else {
503
                $update = is_array($update) ? TypeConverter::fromLegacy($update) : [];
504
505
                if (isset($options['new'])) {
506
                    $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
507
                    unset($options['new']);
508
                }
509
510
                $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
511
512
                $document = $this->collection->findOneAndUpdate($query, $update, $options);
513
            }
514
        } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\ConnectionException 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...
515
            throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
516
        } 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...
517
            throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
518
        } 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...
519
            ExceptionConverter::toLegacy($e);
520
        }
521
522
        if ($document) {
523
            $document = TypeConverter::toLegacy($document);
0 ignored issues
show
Bug introduced by
The variable $document does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
524
        }
525
526
        return $document;
527
    }
528
529
    /**
530
     * Querys this collection, returning a single element
531
     *
532
     * @link http://www.php.net/manual/en/mongocollection.findone.php
533
     * @param array $query The fields for which to search.
534
     * @param array $fields Fields of the results to return.
535
     * @param array $options
536
     * @return array|null
537
     */
538
    public function findOne(array $query = [], array $fields = [], array $options = [])
539
    {
540
        $options = ['projection' => $fields] + $options;
541
        try {
542
            $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
543
        } 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...
544
            ExceptionConverter::toLegacy($e);
545
        }
546
547
        if ($document !== null) {
548
            $document = TypeConverter::toLegacy($document);
549
        }
550
551
        return $document;
552
    }
553
554
    /**
555
     * Creates an index on the given field(s), or does nothing if the index already exists
556
     *
557
     * @link http://www.php.net/manual/en/mongocollection.createindex.php
558
     * @param array $keys Field or fields to use as index.
559
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
560
     * @return array Returns the database response.
561
     *
562
     * @todo This method does not yet return the correct result
563
     */
564
    public function createIndex($keys, array $options = [])
565
    {
566
        if (is_string($keys)) {
567
            if (empty($keys)) {
568
                throw new MongoException('empty string passed as key field');
569
            }
570
            $keys = [$keys => 1];
571
        }
572
573
        if (is_object($keys)) {
574
            $keys = (array) $keys;
575
        }
576
577
        if (! is_array($keys) || ! count($keys)) {
578
            throw new MongoException('keys cannot be empty');
579
        }
580
581
        // duplicate
582
        $neededOptions = ['unique' => 1, 'sparse' => 1, 'expireAfterSeconds' => 1, 'background' => 1, 'dropDups' => 1];
583
        $indexOptions = array_intersect_key($options, $neededOptions);
584
        $indexes = $this->collection->listIndexes();
585
        foreach ($indexes as $index) {
586
587
            if (! empty($options['name']) && $index->getName() === $options['name']) {
588
                throw new \MongoResultException(sprintf('index with name: %s already exists', $index->getName()));
589
            }
590
591
            if ($index->getKey() == $keys) {
592
                $currentIndexOptions = array_intersect_key($index->__debugInfo(), $neededOptions);
593
594
                unset($currentIndexOptions['name']);
595
                if ($currentIndexOptions != $indexOptions) {
596
                    throw new \MongoResultException('Index with same keys but different options already exists');
597
                }
598
599
                return [
600
                    'createdCollectionAutomatically' => false,
601
                    'numIndexesBefore' => count($indexes),
602
                    'numIndexesAfter' => count($indexes),
603
                    'note' => 'all indexes already exist',
604
                    'ok' => 1.0
605
                ];
606
            }
607
        }
608
609
        try {
610
            $this->collection->createIndex($keys, $this->convertWriteConcernOptions($options));
611
        } 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...
612
            ExceptionConverter::toLegacy($e);
613
        }
614
615
        return [
616
            'createdCollectionAutomatically' => true,
617
            'numIndexesBefore' => count($indexes),
618
            'numIndexesAfter' => count($indexes) + 1,
619
            'ok' => 1.0
620
        ];
621
    }
622
623
    /**
624
     * Creates an index on the given field(s), or does nothing if the index already exists
625
     *
626
     * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
627
     * @param array $keys Field or fields to use as index.
628
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
629
     * @return boolean always true
630
     * @deprecated Use MongoCollection::createIndex() instead.
631
     */
632
    public function ensureIndex(array $keys, array $options = [])
633
    {
634
        $this->createIndex($keys, $options);
635
636
        return true;
637
    }
638
639
    /**
640
     * Deletes an index from this collection
641
     *
642
     * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
643
     * @param string|array $keys Field or fields from which to delete the index.
644
     * @return array Returns the database response.
645
     */
646
    public function deleteIndex($keys)
647
    {
648
        if (is_string($keys)) {
649
            $indexName = $keys;
650
        } elseif (is_array($keys)) {
651
            $indexName = \MongoDB\generate_index_name($keys);
652
        } else {
653
            throw new \InvalidArgumentException();
654
        }
655
656
        return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
657
    }
658
659
    /**
660
     * Delete all indexes for this collection
661
     *
662
     * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
663
     * @return array Returns the database response.
664
     */
665
    public function deleteIndexes()
666
    {
667
        return TypeConverter::toLegacy($this->collection->dropIndexes());
668
    }
669
670
    /**
671
     * Returns an array of index names for this collection
672
     *
673
     * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
674
     * @return array Returns a list of index names.
675
     */
676
    public function getIndexInfo()
677
    {
678
        $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
679
            return [
680
                'v' => $indexInfo->getVersion(),
681
                'key' => $indexInfo->getKey(),
682
                'name' => $indexInfo->getName(),
683
                'ns' => $indexInfo->getNamespace(),
684
            ];
685
        };
686
687
        return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
688
    }
689
690
    /**
691
     * Counts the number of documents in this collection
692
     *
693
     * @link http://www.php.net/manual/en/mongocollection.count.php
694
     * @param array|stdClass $query
695
     * @param array $options
696
     * @return int Returns the number of documents matching the query.
697
     */
698
    public function count($query = [], array $options = [])
699
    {
700
        try {
701
            return $this->collection->count(TypeConverter::fromLegacy($query), $options);
702
        } 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...
703
            ExceptionConverter::toLegacy($e);
704
        }
705
    }
706
707
    /**
708
     * Saves an object to this collection
709
     *
710
     * @link http://www.php.net/manual/en/mongocollection.save.php
711
     * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
712
     * @param array $options Options for the save.
713
     * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
714
     * @throws MongoCursorException if the "w" option is set and the write fails.
715
     * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
716
     * @return array|boolean If w was set, returns an array containing the status of the save.
717
     * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
718
     */
719
    public function save(&$a, array $options = [])
720
    {
721
        $id = $this->ensureDocumentHasMongoId($a);
722
723
        $document = (array) $a;
724
        unset($document['_id']);
725
726
        $options['upsert'] = true;
727
728
        $result = $this->update(['_id' => $id], ['$set' => $a], $options);
729
        if ($result['ok'] == 0.0) {
730
            throw new \MongoCursorException();
731
        }
732
733
        return $result;
734
    }
735
736
    /**
737
     * Creates a database reference
738
     *
739
     * @link http://www.php.net/manual/en/mongocollection.createdbref.php
740
     * @param array|object $document_or_id Object to which to create a reference.
741
     * @return array Returns a database reference array.
742
     */
743 View Code Duplication
    public function createDBRef($document_or_id)
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...
744
    {
745
        if ($document_or_id instanceof \MongoId) {
746
            $id = $document_or_id;
747
        } elseif (is_object($document_or_id)) {
748
            if (! isset($document_or_id->_id)) {
749
                return null;
750
            }
751
752
            $id = $document_or_id->_id;
753
        } elseif (is_array($document_or_id)) {
754
            if (! isset($document_or_id['_id'])) {
755
                return null;
756
            }
757
758
            $id = $document_or_id['_id'];
759
        } else {
760
            $id = $document_or_id;
761
        }
762
763
        return MongoDBRef::create($this->name, $id);
764
    }
765
766
    /**
767
     * Fetches the document pointed to by a database reference
768
     *
769
     * @link http://www.php.net/manual/en/mongocollection.getdbref.php
770
     * @param array $ref A database reference.
771
     * @return array Returns the database document pointed to by the reference.
772
     */
773
    public function getDBRef(array $ref)
774
    {
775
        return $this->db->getDBRef($ref);
776
    }
777
778
    /**
779
     * Performs an operation similar to SQL's GROUP BY command
780
     *
781
     * @link http://www.php.net/manual/en/mongocollection.group.php
782
     * @param mixed $keys Fields to group by. If an array or non-code object is passed, it will be the key used to group results.
783
     * @param array $initial Initial value of the aggregation counter object.
784
     * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
785
     * @param array $condition An condition that must be true for a row to be considered.
786
     * @return array
787
     */
788
    public function group($keys, array $initial, $reduce, array $condition = [])
789
    {
790
        if (is_string($reduce)) {
791
            $reduce = new MongoCode($reduce);
792
        }
793
794
        $command = [
795
            'group' => [
796
                'ns' => $this->name,
797
                '$reduce' => (string)$reduce,
798
                'initial' => $initial,
799
                'cond' => $condition,
800
            ],
801
        ];
802
803
        if ($keys instanceof MongoCode) {
804
            $command['group']['$keyf'] = (string)$keys;
805
        } else {
806
            $command['group']['key'] = $keys;
807
        }
808
        if (array_key_exists('condition', $condition)) {
809
            $command['group']['cond'] = $condition['condition'];
810
        }
811
        if (array_key_exists('finalize', $condition)) {
812
            if ($condition['finalize'] instanceof MongoCode) {
813
                $condition['finalize'] = (string)$condition['finalize'];
814
            }
815
            $command['group']['finalize'] = $condition['finalize'];
816
        }
817
818
        return $this->db->command($command);
819
    }
820
821
    /**
822
     * Returns an array of cursors to iterator over a full collection in parallel
823
     *
824
     * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
825
     * @param int $num_cursors The number of cursors to request from the server. Please note, that the server can return less cursors than you requested.
826
     * @return MongoCommandCursor[]
827
     */
828
    public function parallelCollectionScan($num_cursors)
0 ignored issues
show
Unused Code introduced by
The parameter $num_cursors 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...
829
    {
830
        $this->notImplemented();
831
    }
832
833
    protected function notImplemented()
834
    {
835
        throw new \Exception('Not implemented');
836
    }
837
838
    /**
839
     * @return \MongoDB\Collection
840
     */
841 View Code Duplication
    private function createCollectionObject()
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...
842
    {
843
        $options = [
844
            'readPreference' => $this->readPreference,
845
            'writeConcern' => $this->writeConcern,
846
        ];
847
848
        if ($this->collection === null) {
849
            $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
850
        } else {
851
            $this->collection = $this->collection->withOptions($options);
852
        }
853
    }
854
855
    /**
856
     * Converts legacy write concern options to a WriteConcern object
857
     *
858
     * @param array $options
859
     * @return array
860
     */
861
    private function convertWriteConcernOptions(array $options)
862
    {
863
        if (isset($options['safe'])) {
864
            $options['w'] = ($options['safe']) ? 1 : 0;
865
        }
866
867
        if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
868
            $options['wTimeoutMS'] = $options['wtimeout'];
869
        }
870
871
        if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
872
            $collectionWriteConcern = $this->getWriteConcern();
873
            $writeConcern = $this->createWriteConcernFromParameters(
874
                isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
875
                isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
876
            );
877
878
            $options['writeConcern'] = $writeConcern;
879
        }
880
881
        unset($options['safe']);
882
        unset($options['w']);
883
        unset($options['wTimeout']);
884
        unset($options['wTimeoutMS']);
885
886
        return $options;
887
    }
888
889
    /**
890
     * @param array|object $document
891
     * @return MongoId
892
     */
893
    private function ensureDocumentHasMongoId(&$document)
894
    {
895
        $checkKeys = function($array) {
896
            foreach (array_keys($array) as $key) {
897
                if (is_int($key) || empty($key) || strpos($key, '*') === 1) {
898
                    throw new \MongoException('document contain invalid key');
899
                }
900
            }
901
        };
902
903
        if (is_array($document)) {
904
            if (empty($document)) {
905
                throw new \MongoException('document cannot be empty');
906
            }
907
            if (! isset($document['_id'])) {
908
                $document['_id'] = new \MongoId();
909
            }
910
911
            $checkKeys($document);
912
913
            return $document['_id'];
914
        } elseif (is_object($document)) {
915
            if (empty((array) $document)) {
916
                throw new \MongoException('document cannot be empty');
917
            }
918
            if (! isset($document->_id)) {
919
                $document->_id = new \MongoId();
920
            }
921
922
            $checkKeys((array) $document);
923
924
            return $document->_id;
925
        }
926
927
        return null;
928
    }
929
930
    private function checkCollectionName($name)
931
    {
932
        if (empty($name)) {
933
            throw new Exception('Collection name cannot be empty');
934
        } elseif (strpos($name, chr(0)) !== false) {
935
            throw new Exception('Collection name cannot contain null bytes');
936
        }
937
    }
938
}
939
940