Completed
Pull Request — master (#17)
by Andreas
15:20 queued 06:48
created

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