Completed
Pull Request — master (#17)
by Andreas
15:38
created

MongoCollection::update()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 26
rs 8.5806
cc 4
eloc 17
nc 8
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
19
/**
20
 * Represents a database collection.
21
 * @link http://www.php.net/manual/en/class.mongocollection.php
22
 */
23
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...
24
{
25
    use Helper\ReadPreference;
26
    use Helper\SlaveOkay;
27
    use Helper\WriteConcern;
28
29
    const ASCENDING = 1;
30
    const DESCENDING = -1;
31
32
    /**
33
     * @var MongoDB
34
     */
35
    public $db = NULL;
36
37
    /**
38
     * @var string
39
     */
40
    protected $name;
41
42
    /**
43
     * @var \MongoDB\Collection
44
     */
45
    protected $collection;
46
47
    /**
48
     * Creates a new collection
49
     *
50
     * @link http://www.php.net/manual/en/mongocollection.construct.php
51
     * @param MongoDB $db Parent database.
52
     * @param string $name Name for this collection.
53
     * @throws Exception
54
     * @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...
55
     */
56
    public function __construct(MongoDB $db, $name)
57
    {
58
        $this->db = $db;
59
        $this->name = $name;
60
61
        $this->setReadPreferenceFromArray($db->getReadPreference());
62
        $this->setWriteConcernFromArray($db->getWriteConcern());
63
64
        $this->createCollectionObject();
65
    }
66
67
    /**
68
     * Gets the underlying collection for this object
69
     *
70
     * @internal This part is not of the ext-mongo API and should not be used
71
     * @return \MongoDB\Collection
72
     */
73
    public function getCollection()
74
    {
75
        return $this->collection;
76
    }
77
78
    /**
79
     * String representation of this collection
80
     *
81
     * @link http://www.php.net/manual/en/mongocollection.--tostring.php
82
     * @return string Returns the full name of this collection.
83
     */
84
    public function __toString()
85
    {
86
        return (string) $this->db . '.' . $this->name;
87
    }
88
89
    /**
90
     * Gets a collection
91
     *
92
     * @link http://www.php.net/manual/en/mongocollection.get.php
93
     * @param string $name The next string in the collection name.
94
     * @return MongoCollection
95
     */
96
    public function __get($name)
97
    {
98
        // Handle w and wtimeout properties that replicate data stored in $readPreference
99
        if ($name === 'w' || $name === 'wtimeout') {
100
            return $this->getWriteConcern()[$name];
101
        }
102
103
        return $this->db->selectCollection($this->name . '.' . $name);
104
    }
105
106
    /**
107
     * @param string $name
108
     * @param mixed $value
109
     */
110 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...
111
    {
112
        if ($name === 'w' || $name === 'wtimeout') {
113
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
114
            $this->createCollectionObject();
115
        }
116
    }
117
118
    /**
119
     * Perform an aggregation using the aggregation framework
120
     *
121
     * @link http://www.php.net/manual/en/mongocollection.aggregate.php
122
     * @param array $pipeline
123
     * @param array $op
124
     * @return array
125
     */
126
    public function aggregate(array $pipeline, array $op = [])
127
    {
128
        if (! TypeConverter::isNumericArray($pipeline)) {
129
            $pipeline = [];
130
            $options = [];
131
132
            $i = 0;
133
            foreach (func_get_args() as $operator) {
134
                $i++;
135
                if (! is_array($operator)) {
136
                    trigger_error("Argument $i is not an array", E_WARNING);
137
                    return;
138
                }
139
140
                $pipeline[] = $operator;
141
            }
142
        } else {
143
            $options = $op;
144
        }
145
146
        $command = [
147
            'aggregate' => $this->name,
148
            'pipeline' => $pipeline
149
        ];
150
151
        $command += $options;
152
153
        return $this->db->command($command);
154
    }
155
156
    /**
157
     * Execute an aggregation pipeline command and retrieve results through a cursor
158
     *
159
     * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
160
     * @param array $pipeline
161
     * @param array $options
162
     * @return MongoCommandCursor
163
     */
164
    public function aggregateCursor(array $pipeline, array $options = [])
165
    {
166
        // Build command manually, can't use mongo-php-library here
167
        $command = [
168
            'aggregate' => $this->name,
169
            'pipeline' => $pipeline
170
        ];
171
172
        // Convert cursor option
173
        if (! isset($options['cursor']) || $options['cursor'] === true || $options['cursor'] === []) {
174
            // Cursor option needs to be an object convert bools and empty arrays since those won't be handled by TypeConverter
175
            $options['cursor'] = new \stdClass;
176
        }
177
178
        $command += $options;
179
180
        $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
181
        $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...
182
183
        return $cursor;
184
    }
185
186
    /**
187
     * Returns this collection's name
188
     *
189
     * @link http://www.php.net/manual/en/mongocollection.getname.php
190
     * @return string
191
     */
192
    public function getName()
193
    {
194
        return $this->name;
195
    }
196
197
    /**
198
     * {@inheritdoc}
199
     */
200
    public function setReadPreference($readPreference, $tags = null)
201
    {
202
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
203
        $this->createCollectionObject();
204
205
        return $result;
206
    }
207
208
    /**
209
     * {@inheritdoc}
210
     */
211
    public function setWriteConcern($wstring, $wtimeout = 0)
212
    {
213
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
214
        $this->createCollectionObject();
215
216
        return $result;
217
    }
218
219
    /**
220
     * Drops this collection
221
     *
222
     * @link http://www.php.net/manual/en/mongocollection.drop.php
223
     * @return array Returns the database response.
224
     */
225
    public function drop()
226
    {
227
        return TypeConverter::convertObjectToLegacyArray($this->collection->drop());
228
    }
229
230
    /**
231
     * Validates this collection
232
     *
233
     * @link http://www.php.net/manual/en/mongocollection.validate.php
234
     * @param bool $scan_data Only validate indices, not the base collection.
235
     * @return array Returns the database's evaluation of this object.
236
     */
237
    public function validate($scan_data = FALSE)
238
    {
239
        $command = [
240
            'validate' => $this->name,
241
            'full'     => $scan_data,
242
        ];
243
244
        return $this->db->command($command);
245
    }
246
247
    /**
248
     * Inserts an array into the collection
249
     *
250
     * @link http://www.php.net/manual/en/mongocollection.insert.php
251
     * @param array|object $a
252
     * @param array $options
253
     * @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.
254
     * @throws MongoCursorException if the "w" option is set and the write fails.
255
     * @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.
256
     * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
257
     */
258
    public function insert($a, array $options = [])
259
    {
260
        $result = $this->collection->insertOne(
261
            TypeConverter::convertLegacyArrayToObject($a),
262
            $this->convertWriteConcernOptions($options)
263
        );
264
265
        if (! $result->isAcknowledged()) {
266
            return true;
267
        }
268
269
        return [
270
            'ok' => 1.0,
271
            'n' => 0,
272
            'err' => null,
273
            'errmsg' => null,
274
        ];
275
    }
276
277
    /**
278
     * Inserts multiple documents into this collection
279
     *
280
     * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
281
     * @param array $a An array of arrays.
282
     * @param array $options Options for the inserts.
283
     * @throws MongoCursorException
284
     * @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.
285
     */
286
    public function batchInsert(array $a, array $options = [])
287
    {
288
        $result = $this->collection->insertMany(
289
            TypeConverter::convertLegacyArrayToObject($a),
0 ignored issues
show
Documentation introduced by
\Alcaeus\MongoDbAdapter\...LegacyArrayToObject($a) is of type array|object<stdClass>, but the function expects a array<integer,array|object>.

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...
290
            $this->convertWriteConcernOptions($options)
291
        );
292
293
        if (! $result->isAcknowledged()) {
294
            return true;
295
        }
296
297
        return [
298
            'connectionId' => 0,
299
            'n' => 0,
300
            'syncMillis' => 0,
301
            'writtenTo' => null,
302
            'err' => null,
303
            'errmsg' => null,
304
        ];
305
    }
306
307
    /**
308
     * Update records based on a given criteria
309
     *
310
     * @link http://www.php.net/manual/en/mongocollection.update.php
311
     * @param array $criteria Description of the objects to update.
312
     * @param array $newobj The object with which to update the matching records.
313
     * @param array $options
314
     * @throws MongoCursorException
315
     * @return boolean
316
     */
317
    public function update(array $criteria , array $newobj, array $options = [])
318
    {
319
        $multiple = isset($options['multiple']) ? $options['multiple'] : false;
320
        $method = $multiple ? 'updateMany' : 'updateOne';
321
        unset($options['multiple']);
322
323
        /** @var \MongoDB\UpdateResult $result */
324
        $result = $this->collection->$method(
325
            TypeConverter::convertLegacyArrayToObject($criteria),
326
            TypeConverter::convertLegacyArrayToObject($newobj),
327
            $this->convertWriteConcernOptions($options)
328
        );
329
330
        if (! $result->isAcknowledged()) {
331
            return true;
332
        }
333
334
        return [
335
            'ok' => 1.0,
336
            'nModified' => $result->getModifiedCount(),
337
            'n' => $result->getMatchedCount(),
338
            'err' => null,
339
            'errmsg' => null,
340
            'updatedExisting' => $result->getUpsertedCount() == 0,
341
        ];
342
    }
343
344
    /**
345
     * Remove records from this collection
346
     *
347
     * @link http://www.php.net/manual/en/mongocollection.remove.php
348
     * @param array $criteria Query criteria for the documents to delete.
349
     * @param array $options An array of options for the remove operation.
350
     * @throws MongoCursorException
351
     * @throws MongoCursorTimeoutException
352
     * @return bool|array Returns an array containing the status of the removal
353
     * if the "w" option is set. Otherwise, returns TRUE.
354
     */
355
    public function remove(array $criteria = [], array $options = [])
356
    {
357
        $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
358
        $method = $multiple ? 'deleteMany' : 'deleteOne';
359
360
        /** @var \MongoDB\DeleteResult $result */
361
        $result = $this->collection->$method(
362
            TypeConverter::convertLegacyArrayToObject($criteria),
363
            $this->convertWriteConcernOptions($options)
364
        );
365
366
        if (! $result->isAcknowledged()) {
367
            return true;
368
        }
369
370
        return [
371
            'ok' => 1.0,
372
            'n' => $result->getDeletedCount(),
373
            'err' => null,
374
            'errmsg' => null
375
        ];
376
    }
377
378
    /**
379
     * Querys this collection
380
     *
381
     * @link http://www.php.net/manual/en/mongocollection.find.php
382
     * @param array $query The fields for which to search.
383
     * @param array $fields Fields of the results to return.
384
     * @return MongoCursor
385
     */
386
    public function find(array $query = [], array $fields = [])
387
    {
388
        $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
389
        $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...
390
391
        return $cursor;
392
    }
393
394
    /**
395
     * Retrieve a list of distinct values for the given key across a collection
396
     *
397
     * @link http://www.php.net/manual/ru/mongocollection.distinct.php
398
     * @param string $key The key to use.
399
     * @param array $query An optional query parameters
400
     * @return array|bool Returns an array of distinct values, or FALSE on failure
401
     */
402
    public function distinct($key, array $query = [])
403
    {
404
        return array_map([TypeConverter::class, 'convertToLegacyType'], $this->collection->distinct($key, $query));
405
    }
406
407
    /**
408
     * Update a document and return it
409
     *
410
     * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
411
     * @param array $query The query criteria to search for.
412
     * @param array $update The update criteria.
413
     * @param array $fields Optionally only return these fields.
414
     * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
415
     * @return array Returns the original document, or the modified document when new is set.
416
     */
417
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
418
    {
419
        $query = TypeConverter::convertLegacyArrayToObject($query);
420
421
        if (isset($options['remove'])) {
422
            unset($options['remove']);
423
            $document = $this->collection->findOneAndDelete($query, $options);
424
        } else {
425
            $update = is_array($update) ? TypeConverter::convertLegacyArrayToObject($update) : [];
426
427
            if (isset($options['new'])) {
428
                $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
429
                unset($options['new']);
430
            }
431
432
            $options['projection'] = is_array($fields) ? TypeConverter::convertLegacyArrayToObject($fields) : [];
433
434
            $document = $this->collection->findOneAndUpdate($query, $update, $options);
435
        }
436
437
        if ($document) {
438
            $document = TypeConverter::convertObjectToLegacyArray($document);
439
        }
440
441
        return $document;
442
    }
443
444
    /**
445
     * Querys this collection, returning a single element
446
     *
447
     * @link http://www.php.net/manual/en/mongocollection.findone.php
448
     * @param array $query The fields for which to search.
449
     * @param array $fields Fields of the results to return.
450
     * @param array $options
451
     * @return array|null
452
     */
453
    public function findOne(array $query = [], array $fields = [], array $options = [])
454
    {
455
        $options = ['projection' => $fields] + $options;
456
457
        $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query), $options);
458
        if ($document !== null) {
459
            $document = TypeConverter::convertObjectToLegacyArray($document);
460
        }
461
462
        return $document;
463
    }
464
465
    /**
466
     * Creates an index on the given field(s), or does nothing if the index already exists
467
     *
468
     * @link http://www.php.net/manual/en/mongocollection.createindex.php
469
     * @param array $keys Field or fields to use as index.
470
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
471
     * @return array Returns the database response.
472
     *
473
     * @todo This method does not yet return the correct result
474
     */
475
    public function createIndex(array $keys, array $options = [])
476
    {
477
        // Note: this is what the result array should look like
478
//        $expected = [
479
//            'createdCollectionAutomatically' => true,
480
//            'numIndexesBefore' => 1,
481
//            'numIndexesAfter' => 2,
482
//            'ok' => 1.0
483
//        ];
484
485
        return $this->collection->createIndex($keys, $options);
486
    }
487
488
    /**
489
     * Creates an index on the given field(s), or does nothing if the index already exists
490
     *
491
     * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
492
     * @param array $keys Field or fields to use as index.
493
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
494
     * @return boolean always true
495
     * @deprecated Use MongoCollection::createIndex() instead.
496
     */
497
    public function ensureIndex(array $keys, array $options = [])
498
    {
499
        $this->createIndex($keys, $options);
500
501
        return true;
502
    }
503
504
    /**
505
     * Deletes an index from this collection
506
     *
507
     * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
508
     * @param string|array $keys Field or fields from which to delete the index.
509
     * @return array Returns the database response.
510
     */
511
    public function deleteIndex($keys)
512
    {
513
        if (is_string($keys)) {
514
            $indexName = $keys;
515
        } elseif (is_array($keys)) {
516
            $indexName = \MongoDB\generate_index_name($keys);
517
        } else {
518
            throw new \InvalidArgumentException();
519
        }
520
521
        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndex($indexName));
522
    }
523
524
    /**
525
     * Delete all indexes for this collection
526
     *
527
     * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
528
     * @return array Returns the database response.
529
     */
530
    public function deleteIndexes()
531
    {
532
        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndexes());
533
    }
534
535
    /**
536
     * Returns an array of index names for this collection
537
     *
538
     * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
539
     * @return array Returns a list of index names.
540
     */
541
    public function getIndexInfo()
542
    {
543
        $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
544
            return [
545
                'v' => $indexInfo->getVersion(),
546
                'key' => $indexInfo->getKey(),
547
                'name' => $indexInfo->getName(),
548
                'ns' => $indexInfo->getNamespace(),
549
            ];
550
        };
551
552
        return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
553
    }
554
555
    /**
556
     * Counts the number of documents in this collection
557
     *
558
     * @link http://www.php.net/manual/en/mongocollection.count.php
559
     * @param array|stdClass $query
560
     * @param array $options
561
     * @return int Returns the number of documents matching the query.
562
     */
563
    public function count($query = [], array $options = [])
564
    {
565
        return $this->collection->count(TypeConverter::convertLegacyArrayToObject($query), $options);
566
    }
567
568
    /**
569
     * Saves an object to this collection
570
     *
571
     * @link http://www.php.net/manual/en/mongocollection.save.php
572
     * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
573
     * @param array $options Options for the save.
574
     * @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.
575
     * @throws MongoCursorException if the "w" option is set and the write fails.
576
     * @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.
577
     * @return array|boolean If w was set, returns an array containing the status of the save.
578
     * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
579
     */
580
    public function save($a, array $options = [])
581
    {
582
        if (is_object($a)) {
583
            $a = (array) $a;
584
        }
585
586
        if ( ! array_key_exists('_id', $a)) {
587
            $id = new \MongoId();
588
        } else {
589
            $id = $a['_id'];
590
            unset($a['_id']);
591
        }
592
        $options['upsert'] = true;
593
594
        return $this->update(['_id' => $id], ['$set' => $a], $options);
595
    }
596
597
    /**
598
     * Creates a database reference
599
     *
600
     * @link http://www.php.net/manual/en/mongocollection.createdbref.php
601
     * @param array|object $document_or_id Object to which to create a reference.
602
     * @return array Returns a database reference array.
603
     */
604 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...
605
    {
606
        if ($document_or_id instanceof \MongoId) {
607
            $id = $document_or_id;
608
        } elseif (is_object($document_or_id)) {
609
            if (! isset($document_or_id->_id)) {
610
                return null;
611
            }
612
613
            $id = $document_or_id->_id;
614
        } elseif (is_array($document_or_id)) {
615
            if (! isset($document_or_id['_id'])) {
616
                return null;
617
            }
618
619
            $id = $document_or_id['_id'];
620
        } else {
621
            $id = $document_or_id;
622
        }
623
624
        return MongoDBRef::create($this->name, $id);
625
    }
626
627
    /**
628
     * Fetches the document pointed to by a database reference
629
     *
630
     * @link http://www.php.net/manual/en/mongocollection.getdbref.php
631
     * @param array $ref A database reference.
632
     * @return array Returns the database document pointed to by the reference.
633
     */
634
    public function getDBRef(array $ref)
635
    {
636
        return $this->db->getDBRef($ref);
637
    }
638
639
    /**
640
     * Performs an operation similar to SQL's GROUP BY command
641
     *
642
     * @link http://www.php.net/manual/en/mongocollection.group.php
643
     * @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.
644
     * @param array $initial Initial value of the aggregation counter object.
645
     * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
646
     * @param array $condition An condition that must be true for a row to be considered.
647
     * @return array
648
     */
649
    public function group($keys, array $initial, $reduce, array $condition = [])
650
    {
651
        if (is_string($reduce)) {
652
            $reduce = new MongoCode($reduce);
653
        }
654
655
        $command = [
656
            'group' => [
657
                'ns' => $this->name,
658
                '$reduce' => (string)$reduce,
659
                'initial' => $initial,
660
                'cond' => $condition,
661
            ],
662
        ];
663
664
        if ($keys instanceof MongoCode) {
665
            $command['group']['$keyf'] = (string)$keys;
666
        } else {
667
            $command['group']['key'] = $keys;
668
        }
669
        if (array_key_exists('condition', $condition)) {
670
            $command['group']['cond'] = $condition['condition'];
671
        }
672
        if (array_key_exists('finalize', $condition)) {
673
            if ($condition['finalize'] instanceof MongoCode) {
674
                $condition['finalize'] = (string)$condition['finalize'];
675
            }
676
            $command['group']['finalize'] = $condition['finalize'];
677
        }
678
679
        return $this->db->command($command);
680
    }
681
682
    /**
683
     * Returns an array of cursors to iterator over a full collection in parallel
684
     *
685
     * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
686
     * @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.
687
     * @return MongoCommandCursor[]
688
     */
689
    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...
690
    {
691
        $this->notImplemented();
692
    }
693
694
    protected function notImplemented()
695
    {
696
        throw new \Exception('Not implemented');
697
    }
698
699
    /**
700
     * @return \MongoDB\Collection
701
     */
702 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...
703
    {
704
        $options = [
705
            'readPreference' => $this->readPreference,
706
            'writeConcern' => $this->writeConcern,
707
        ];
708
709
        if ($this->collection === null) {
710
            $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
711
        } else {
712
            $this->collection = $this->collection->withOptions($options);
713
        }
714
    }
715
716
    /**
717
     * Converts legacy write concern options to a WriteConcern object
718
     *
719
     * @param array $options
720
     * @return array
721
     */
722
    private function convertWriteConcernOptions(array $options)
723
    {
724
        if (isset($options['safe'])) {
725
            $options['w'] = ($options['safe']) ? 1 : 0;
726
        }
727
728
        if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
729
            $options['wTimeoutMS'] = $options['wtimeout'];
730
        }
731
732
        if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
733
            $collectionWriteConcern = $this->getWriteConcern();
734
            $writeConcern = $this->createWriteConcernFromParameters(
735
                isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
736
                isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
737
            );
738
739
            $options['writeConcern'] = $writeConcern;
740
        }
741
742
        unset($options['safe']);
743
        unset($options['w']);
744
        unset($options['wTimeout']);
745
        unset($options['wTimeoutMS']);
746
747
        return $options;
748
    }
749
}
750
751