Completed
Pull Request — master (#17)
by Andreas
46:51 queued 32:35
created

MongoCollection::getIndexInfo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 13
rs 9.4286
cc 1
eloc 8
nc 1
nop 0
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
use Alcaeus\MongoDbAdapter\Helper;
17
use 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'] : false;
358
        $method = $multiple ? 'deleteMany' : 'deleteOne';
359
360
        return $this->collection->$method($criteria, $options);
361
    }
362
363
    /**
364
     * Querys this collection
365
     *
366
     * @link http://www.php.net/manual/en/mongocollection.find.php
367
     * @param array $query The fields for which to search.
368
     * @param array $fields Fields of the results to return.
369
     * @return MongoCursor
370
     */
371
    public function find(array $query = [], array $fields = [])
372
    {
373
        $cursor = new MongoCursor($this->db->getConnection(), (string)$this, $query, $fields);
374
        $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...
375
376
        return $cursor;
377
    }
378
379
    /**
380
     * Retrieve a list of distinct values for the given key across a collection
381
     *
382
     * @link http://www.php.net/manual/ru/mongocollection.distinct.php
383
     * @param string $key The key to use.
384
     * @param array $query An optional query parameters
385
     * @return array|bool Returns an array of distinct values, or FALSE on failure
386
     */
387
    public function distinct($key, array $query = [])
388
    {
389
        return array_map([TypeConverter::class, 'convertToLegacyType'], $this->collection->distinct($key, $query));
390
    }
391
392
    /**
393
     * Update a document and return it
394
     * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
395
     * @param array $query The query criteria to search for.
396
     * @param array $update The update criteria.
397
     * @param array $fields Optionally only return these fields.
398
     * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
399
     * @return array Returns the original document, or the modified document when new is set.
400
     */
401
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
402
    {
403
        $query = TypeConverter::convertLegacyArrayToObject($query);
404
405
        if (isset($options['remove'])) {
406
            unset($options['remove']);
407
            $document = $this->collection->findOneAndDelete($query, $options);
408
        } else {
409
            $update = is_array($update) ? TypeConverter::convertLegacyArrayToObject($update) : [];
410
411
            if (isset($options['new'])) {
412
                $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
413
                unset($options['new']);
414
            }
415
416
            $options['projection'] = is_array($fields) ? TypeConverter::convertLegacyArrayToObject($fields) : [];
417
418
            $document = $this->collection->findOneAndUpdate($query, $update, $options);
419
        }
420
421
        if ($document) {
422
            $document = TypeConverter::convertObjectToLegacyArray($document);
423
        }
424
425
        return $document;
426
    }
427
428
    /**
429
     * Querys this collection, returning a single element
430
     * @link http://www.php.net/manual/en/mongocollection.findone.php
431
     * @param array $query The fields for which to search.
432
     * @param array $fields Fields of the results to return.
433
     * @return array|null
434
     */
435
    public function findOne(array $query = [], array $fields = [])
436
    {
437
        $document = $this->collection->findOne(TypeConverter::convertLegacyArrayToObject($query), ['projection' => $fields]);
438
        if ($document !== null) {
439
            $document = TypeConverter::convertObjectToLegacyArray($document);
440
        }
441
442
        return $document;
443
    }
444
445
    /**
446
     * Creates an index on the given field(s), or does nothing if the index already exists
447
     * @link http://www.php.net/manual/en/mongocollection.createindex.php
448
     * @param array $keys Field or fields to use as index.
449
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
450
     * @return array Returns the database response.
451
     *
452
     * @todo This method does not yet return the correct result
453
     */
454
    public function createIndex(array $keys, array $options = [])
455
    {
456
        // Note: this is what the result array should look like
457
//        $expected = [
458
//            'createdCollectionAutomatically' => true,
459
//            'numIndexesBefore' => 1,
460
//            'numIndexesAfter' => 2,
461
//            'ok' => 1.0
462
//        ];
463
464
        return $this->collection->createIndex($keys, $options);
465
    }
466
467
    /**
468
     * @deprecated Use MongoCollection::createIndex() instead.
469
     * Creates an index on the given field(s), or does nothing if the index already exists
470
     * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
471
     * @param array $keys Field or fields to use as index.
472
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
473
     * @return boolean always true
474
     */
475
    public function ensureIndex(array $keys, array $options = [])
476
    {
477
        $this->createIndex($keys, $options);
478
479
        return true;
480
    }
481
482
    /**
483
     * Deletes an index from this collection
484
     * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
485
     * @param string|array $keys Field or fields from which to delete the index.
486
     * @return array Returns the database response.
487
     */
488
    public function deleteIndex($keys)
489
    {
490
        if (is_string($keys)) {
491
            $indexName = $keys;
492
        } elseif (is_array($keys)) {
493
            $indexName = self::toIndexString($keys);
494
        } else {
495
            throw new \InvalidArgumentException();
496
        }
497
498
        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndex($indexName));
499
    }
500
501
    /**
502
     * Delete all indexes for this collection
503
     * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
504
     * @return array Returns the database response.
505
     */
506
    public function deleteIndexes()
507
    {
508
        return TypeConverter::convertObjectToLegacyArray($this->collection->dropIndexes());
509
    }
510
511
    /**
512
     * Returns an array of index names for this collection
513
     * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
514
     * @return array Returns a list of index names.
515
     */
516
    public function getIndexInfo()
517
    {
518
        $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
519
            return [
520
                'v' => $indexInfo->getVersion(),
521
                'key' => $indexInfo->getKey(),
522
                'name' => $indexInfo->getName(),
523
                'ns' => $indexInfo->getNamespace(),
524
            ];
525
        };
526
527
        return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
528
    }
529
530
    /**
531
     * Counts the number of documents in this collection
532
     * @link http://www.php.net/manual/en/mongocollection.count.php
533
     * @param array|stdClass $query
534
     * @return int Returns the number of documents matching the query.
535
     */
536
    public function count($query = [])
537
    {
538
        return $this->collection->count($query);
539
    }
540
541
    /**
542
     * Saves an object to this collection
543
     *
544
     * @link http://www.php.net/manual/en/mongocollection.save.php
545
     * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
546
     * @param array $options Options for the save.
547
     * @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.
548
     * @throws MongoCursorException if the "w" option is set and the write fails.
549
     * @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.
550
     * @return array|boolean If w was set, returns an array containing the status of the save.
551
     * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
552
     */
553
    public function save($a, array $options = [])
0 ignored issues
show
Unused Code introduced by
The parameter $options is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
554
    {
555
        if (is_object($a)) {
556
            $a = (array)$a;
557
        }
558
        if ( ! array_key_exists('_id', $a)) {
559
            $id = new \MongoId();
560
        } else {
561
            $id = $a['_id'];
562
            unset($a['_id']);
563
        }
564
        $filter = ['_id' => $id];
565
        $filter = TypeConverter::convertLegacyArrayToObject($filter);
566
        $a = TypeConverter::convertLegacyArrayToObject($a);
567
        return $this->collection->updateOne($filter, ['$set' => $a], ['upsert' => true]);
568
    }
569
570
    /**
571
     * Creates a database reference
572
     *
573
     * @link http://www.php.net/manual/en/mongocollection.createdbref.php
574
     * @param array $a Object to which to create a reference.
575
     * @return array Returns a database reference array.
576
     */
577
    public function createDBRef(array $a)
578
    {
579
        return \MongoDBRef::create($this->name, $a['_id']);
580
    }
581
582
    /**
583
     * Fetches the document pointed to by a database reference
584
     *
585
     * @link http://www.php.net/manual/en/mongocollection.getdbref.php
586
     * @param array $ref A database reference.
587
     * @return array Returns the database document pointed to by the reference.
588
     */
589
    public function getDBRef(array $ref)
590
    {
591
        return \MongoDBRef::get($this->db, $ref);
592
    }
593
594
    /**
595
     * @param mixed $keys
596
     * @static
597
     * @return string
598
     */
599
    protected static function toIndexString($keys)
600
    {
601
        $result = '';
602
        foreach ($keys as $name => $direction) {
603
            $result .= sprintf('%s_%d', $name, $direction);
604
        }
605
        return $result;
606
    }
607
608
    /**
609
     * Performs an operation similar to SQL's GROUP BY command
610
     *
611
     * @link http://www.php.net/manual/en/mongocollection.group.php
612
     * @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.
613
     * @param array $initial Initial value of the aggregation counter object.
614
     * @param MongoCode $reduce A function that aggregates (reduces) the objects iterated.
615
     * @param array $condition An condition that must be true for a row to be considered.
616
     * @return array
617
     */
618
    public function group($keys, array $initial, $reduce, array $condition = [])
619
    {
620
        if (is_string($reduce)) {
621
            $reduce = new MongoCode($reduce);
622
        }
623
        if ( ! $reduce instanceof MongoCode) {
624
            throw new \InvalidArgumentExcption('reduce parameter should be a string or MongoCode instance.');
625
        }
626
        $command = [
627
            'group' => [
628
                'ns' => $this->name,
629
                '$reduce' => (string)$reduce,
630
                'initial' => $initial,
631
                'cond' => $condition,
632
            ],
633
        ];
634
635
        if ($keys instanceof MongoCode) {
636
            $command['group']['$keyf'] = (string)$keys;
637
        } else {
638
            $command['group']['key'] = $keys;
639
        }
640
        if (array_key_exists('condition', $condition)) {
641
            $command['group']['cond'] = $condition['condition'];
642
        }
643
        if (array_key_exists('finalize', $condition)) {
644
            if ($condition['finalize'] instanceof MongoCode) {
645
                $condition['finalize'] = (string)$condition['finalize'];
646
            }
647
            $command['group']['finalize'] = $condition['finalize'];
648
        }
649
650
        return $this->db->command($command);
651
    }
652
653
    /**
654
     * Returns an array of cursors to iterator over a full collection in parallel
655
     *
656
     * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
657
     * @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.
658
     * @return MongoCommandCursor[]
659
     */
660
    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...
661
    {
662
        $this->notImplemented();
663
    }
664
665
    protected function notImplemented()
666
    {
667
        throw new \Exception('Not implemented');
668
    }
669
670
    /**
671
     * @return \MongoDB\Collection
672
     */
673 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...
674
    {
675
        $options = [
676
            'readPreference' => $this->readPreference,
677
            'writeConcern' => $this->writeConcern,
678
        ];
679
680
        if ($this->collection === null) {
681
            $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
682
        } else {
683
            $this->collection = $this->collection->withOptions($options);
684
        }
685
    }
686
687
    /**
688
     * @param array $options
689
     * @return array
690
     */
691
    private function convertWriteConcernOptions(array $options)
692
    {
693
        if (isset($options['safe'])) {
694
            $options['w'] = ($options['safe']) ? 1 : 0;
695
        }
696
697
        if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
698
            $options['wTimeoutMS'] = $options['wtimeout'];
699
        }
700
701
        if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
702
            $collectionWriteConcern = $this->getWriteConcern();
703
            $writeConcern = $this->createWriteConcernFromParameters(
704
                isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
705
                isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
706
            );
707
708
            $options['writeConcern'] = $writeConcern;
709
        }
710
711
        unset($options['safe']);
712
        unset($options['w']);
713
        unset($options['wTimeout']);
714
        unset($options['wTimeoutMS']);
715
716
        return $options;
717
    }
718
}
719
720