Completed
Pull Request — master (#28)
by Andreas
04:32 queued 02:14
created

MongoCollection::aggregate()   C

Complexity

Conditions 7
Paths 13

Size

Total Lines 38
Code Lines 24

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 38
rs 6.7272
cc 7
eloc 24
nc 13
nop 2
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
use Alcaeus\MongoDbAdapter\Helper;
17
use Alcaeus\MongoDbAdapter\TypeConverter;
18
use Alcaeus\MongoDbAdapter\ExceptionConverter;
19
20
/**
21
 * Represents a database collection.
22
 * @link http://www.php.net/manual/en/class.mongocollection.php
23
 */
24
class MongoCollection
25
{
26
    use Helper\ReadPreference;
27
    use Helper\SlaveOkay;
28
    use Helper\WriteConcern;
29
30
    const ASCENDING = 1;
31
    const DESCENDING = -1;
32
33
    /**
34
     * @var MongoDB
35
     */
36
    public $db = NULL;
37
38
    /**
39
     * @var string
40
     */
41
    protected $name;
42
43
    /**
44
     * @var \MongoDB\Collection
45
     */
46
    protected $collection;
47
48
    /**
49
     * Creates a new collection
50
     *
51
     * @link http://www.php.net/manual/en/mongocollection.construct.php
52
     * @param MongoDB $db Parent database.
53
     * @param string $name Name for this collection.
54
     * @throws Exception
55
     */
56
    public function __construct(MongoDB $db, $name)
57
    {
58
        $this->checkCollectionName($name);
59
        $this->db = $db;
60
        $this->name = $name;
61
62
        $this->setReadPreferenceFromArray($db->getReadPreference());
63
        $this->setWriteConcernFromArray($db->getWriteConcern());
64
65
        $this->createCollectionObject();
66
    }
67
68
    /**
69
     * Gets the underlying collection for this object
70
     *
71
     * @internal This part is not of the ext-mongo API and should not be used
72
     * @return \MongoDB\Collection
73
     */
74
    public function getCollection()
75
    {
76
        return $this->collection;
77
    }
78
79
    /**
80
     * String representation of this collection
81
     *
82
     * @link http://www.php.net/manual/en/mongocollection.--tostring.php
83
     * @return string Returns the full name of this collection.
84
     */
85
    public function __toString()
86
    {
87
        return (string) $this->db . '.' . $this->name;
88
    }
89
90
    /**
91
     * Gets a collection
92
     *
93
     * @link http://www.php.net/manual/en/mongocollection.get.php
94
     * @param string $name The next string in the collection name.
95
     * @return MongoCollection
96
     */
97
    public function __get($name)
98
    {
99
        // Handle w and wtimeout properties that replicate data stored in $readPreference
100
        if ($name === 'w' || $name === 'wtimeout') {
101
            return $this->getWriteConcern()[$name];
102
        }
103
104
        return $this->db->selectCollection($this->name . '.' . $name);
105
    }
106
107
    /**
108
     * @param string $name
109
     * @param mixed $value
110
     */
111
    public function __set($name, $value)
112
    {
113
        if ($name === 'w' || $name === 'wtimeout') {
114
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
115
            $this->createCollectionObject();
116
        }
117
    }
118
119
    /**
120
     * Perform an aggregation using the aggregation framework
121
     *
122
     * @link http://www.php.net/manual/en/mongocollection.aggregate.php
123
     * @param array $pipeline
124
     * @param array $op
125
     * @return array
126
     */
127
    public function aggregate(array $pipeline, array $op = [])
128
    {
129
        if (! TypeConverter::isNumericArray($pipeline)) {
130
            $pipeline = [];
131
            $options = [];
132
133
            $i = 0;
134
            foreach (func_get_args() as $operator) {
135
                $i++;
136
                if (! is_array($operator)) {
137
                    trigger_error("Argument $i is not an array", E_WARNING);
138
                    return;
139
                }
140
141
                $pipeline[] = $operator;
142
            }
143
        } else {
144
            $options = $op;
145
        }
146
147
        if (isset($options['cursor'])) {
148
            $options['useCursor'] = true;
149
150
            if (isset($options['cursor']['batchSize'])) {
151
                $options['batchSize'] = $options['cursor']['batchSize'];
152
            }
153
154
            unset($options['cursor']);
155
        } else {
156
            $options['useCursor'] = false;
157
        }
158
159
        try {
160
            return $this->collection->aggregate(TypeConverter::fromLegacy($pipeline), $options);
161
        } catch (\MongoDB\Driver\Exception\Exception $e) {
162
            throw ExceptionConverter::toLegacy($e);
163
        }
164
    }
165
166
    /**
167
     * Execute an aggregation pipeline command and retrieve results through a cursor
168
     *
169
     * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
170
     * @param array $pipeline
171
     * @param array $options
172
     * @return MongoCommandCursor
173
     */
174
    public function aggregateCursor(array $pipeline, array $options = [])
175
    {
176
        // Build command manually, can't use mongo-php-library here
177
        $command = [
178
            'aggregate' => $this->name,
179
            'pipeline' => $pipeline
180
        ];
181
182
        // Convert cursor option
183
        if (! isset($options['cursor'])) {
184
            $options['cursor'] = new \stdClass();
185
        }
186
187
        $command += $options;
188
189
        $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
190
        $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...
191
192
        return $cursor;
193
    }
194
195
    /**
196
     * Returns this collection's name
197
     *
198
     * @link http://www.php.net/manual/en/mongocollection.getname.php
199
     * @return string
200
     */
201
    public function getName()
202
    {
203
        return $this->name;
204
    }
205
206
    /**
207
     * {@inheritdoc}
208
     */
209
    public function setReadPreference($readPreference, $tags = null)
210
    {
211
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
212
        $this->createCollectionObject();
213
214
        return $result;
215
    }
216
217
    /**
218
     * {@inheritdoc}
219
     */
220
    public function setWriteConcern($wstring, $wtimeout = 0)
221
    {
222
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
223
        $this->createCollectionObject();
224
225
        return $result;
226
    }
227
228
    /**
229
     * Drops this collection
230
     *
231
     * @link http://www.php.net/manual/en/mongocollection.drop.php
232
     * @return array Returns the database response.
233
     */
234
    public function drop()
235
    {
236
        return TypeConverter::toLegacy($this->collection->drop());
237
    }
238
239
    /**
240
     * Validates this collection
241
     *
242
     * @link http://www.php.net/manual/en/mongocollection.validate.php
243
     * @param bool $scan_data Only validate indices, not the base collection.
244
     * @return array Returns the database's evaluation of this object.
245
     */
246
    public function validate($scan_data = FALSE)
247
    {
248
        $command = [
249
            'validate' => $this->name,
250
            'full'     => $scan_data,
251
        ];
252
253
        return $this->db->command($command);
254
    }
255
256
    /**
257
     * Inserts an array into the collection
258
     *
259
     * @link http://www.php.net/manual/en/mongocollection.insert.php
260
     * @param array|object $a
261
     * @param array $options
262
     * @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.
263
     * @throws MongoCursorException if the "w" option is set and the write fails.
264
     * @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.
265
     * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
266
     */
267
    public function insert(&$a, array $options = [])
268
    {
269
        if (! $this->ensureDocumentHasMongoId($a)) {
270
            trigger_error(sprintf('%s(): expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
271
            return;
272
        }
273
274
        if (! count((array)$a)) {
275
            throw new \MongoException('document must be an array or object');
276
        }
277
278
        try {
279
            $result = $this->collection->insertOne(
280
                TypeConverter::fromLegacy($a),
281
                $this->convertWriteConcernOptions($options)
282
            );
283
        } catch (\MongoDB\Driver\Exception\Exception $e) {
284
            throw ExceptionConverter::toLegacy($e);
285
        }
286
287
        if (! $result->isAcknowledged()) {
288
            return true;
289
        }
290
291
        return [
292
            'ok' => 1.0,
293
            'n' => 0,
294
            'err' => null,
295
            'errmsg' => null,
296
        ];
297
    }
298
299
    /**
300
     * Inserts multiple documents into this collection
301
     *
302
     * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
303
     * @param array $a An array of arrays.
304
     * @param array $options Options for the inserts.
305
     * @throws MongoCursorException
306
     * @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.
307
     */
308
    public function batchInsert(array &$a, array $options = [])
309
    {
310
        if (empty($a)) {
311
            throw new \MongoException('No write ops were included in the batch');
312
        }
313
314
        $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
315
316
        foreach ($a as $key => $item) {
317
            try {
318
                if (! $this->ensureDocumentHasMongoId($a[$key])) {
319
                    if ($continueOnError) {
320
                        unset($a[$key]);
321
                    } else {
322
                        trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
323
                        return;
324
                    }
325
                }
326
            } catch (MongoException $e) {
327
                if ( ! $continueOnError) {
328
                    throw $e;
329
                }
330
            }
331
        }
332
333
        try {
334
            $result = $this->collection->insertMany(
335
                TypeConverter::fromLegacy(array_values($a)),
336
                $this->convertWriteConcernOptions($options)
337
            );
338
        } catch (\MongoDB\Driver\Exception\Exception $e) {
339
            throw ExceptionConverter::toLegacy($e);
340
        }
341
342
        if (! $result->isAcknowledged()) {
343
            return true;
344
        }
345
346
        return [
347
            'ok' => 1.0,
348
            'connectionId' => 0,
349
            'n' => 0,
350
            'syncMillis' => 0,
351
            'writtenTo' => null,
352
            'err' => null,
353
        ];
354
    }
355
356
    /**
357
     * Update records based on a given criteria
358
     *
359
     * @link http://www.php.net/manual/en/mongocollection.update.php
360
     * @param array $criteria Description of the objects to update.
361
     * @param array $newobj The object with which to update the matching records.
362
     * @param array $options
363
     * @throws MongoCursorException
364
     * @return boolean
365
     */
366
    public function update(array $criteria , array $newobj, array $options = [])
367
    {
368
        $multiple = isset($options['multiple']) ? $options['multiple'] : false;
369
        $method = $multiple ? 'updateMany' : 'updateOne';
370
        unset($options['multiple']);
371
372
        try {
373
            /** @var \MongoDB\UpdateResult $result */
374
            $result = $this->collection->$method(
375
                TypeConverter::fromLegacy($criteria),
376
                TypeConverter::fromLegacy($newobj),
377
                $this->convertWriteConcernOptions($options)
378
            );
379
        } catch (\MongoDB\Driver\Exception\Exception $e) {
380
            throw ExceptionConverter::toLegacy($e);
381
        }
382
383
        if (! $result->isAcknowledged()) {
384
            return true;
385
        }
386
387
        return [
388
            'ok' => 1.0,
389
            'nModified' => $result->getModifiedCount(),
390
            'n' => $result->getMatchedCount(),
391
            'err' => null,
392
            'errmsg' => null,
393
            'updatedExisting' => $result->getUpsertedCount() == 0,
394
        ];
395
    }
396
397
    /**
398
     * Remove records from this collection
399
     *
400
     * @link http://www.php.net/manual/en/mongocollection.remove.php
401
     * @param array $criteria Query criteria for the documents to delete.
402
     * @param array $options An array of options for the remove operation.
403
     * @throws MongoCursorException
404
     * @throws MongoCursorTimeoutException
405
     * @return bool|array Returns an array containing the status of the removal
406
     * if the "w" option is set. Otherwise, returns TRUE.
407
     */
408
    public function remove(array $criteria = [], array $options = [])
409
    {
410
        $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
411
        $method = $multiple ? 'deleteMany' : 'deleteOne';
412
413
        try {
414
            /** @var \MongoDB\DeleteResult $result */
415
            $result = $this->collection->$method(
416
                TypeConverter::fromLegacy($criteria),
417
                $this->convertWriteConcernOptions($options)
418
            );
419
        } catch (\MongoDB\Driver\Exception\Exception $e) {
420
            throw ExceptionConverter::toLegacy($e);
421
        }
422
423
        if (! $result->isAcknowledged()) {
424
            return true;
425
        }
426
427
        return [
428
            'ok' => 1.0,
429
            'n' => $result->getDeletedCount(),
430
            'err' => null,
431
            'errmsg' => null
432
        ];
433
    }
434
435
    /**
436
     * Querys this collection
437
     *
438
     * @link http://www.php.net/manual/en/mongocollection.find.php
439
     * @param array $query The fields for which to search.
440
     * @param array $fields Fields of the results to return.
441
     * @return MongoCursor
442
     */
443 View Code Duplication
    public function find(array $query = [], array $fields = [])
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
444
    {
445
        $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
446
        $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...
447
448
        return $cursor;
449
    }
450
451
    /**
452
     * Retrieve a list of distinct values for the given key across a collection
453
     *
454
     * @link http://www.php.net/manual/ru/mongocollection.distinct.php
455
     * @param string $key The key to use.
456
     * @param array $query An optional query parameters
457
     * @return array|bool Returns an array of distinct values, or FALSE on failure
458
     */
459
    public function distinct($key, array $query = [])
460
    {
461
        try {
462
            return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, $query));
463
        } catch (\MongoDB\Driver\Exception\Exception $e) {
464
            return false;
465
        }
466
    }
467
468
    /**
469
     * Update a document and return it
470
     *
471
     * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
472
     * @param array $query The query criteria to search for.
473
     * @param array $update The update criteria.
474
     * @param array $fields Optionally only return these fields.
475
     * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
476
     * @return array Returns the original document, or the modified document when new is set.
477
     */
478
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
479
    {
480
        $query = TypeConverter::fromLegacy($query);
481
        try {
482
            if (isset($options['remove'])) {
483
                unset($options['remove']);
484
                $document = $this->collection->findOneAndDelete($query, $options);
485
            } else {
486
                $update = is_array($update) ? TypeConverter::fromLegacy($update) : [];
487
488
                if (isset($options['new'])) {
489
                    $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
490
                    unset($options['new']);
491
                }
492
493
                $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
494
495
                $document = $this->collection->findOneAndUpdate($query, $update, $options);
496
            }
497
        } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
498
            throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
499
        } catch (\MongoDB\Driver\Exception\Exception $e) {
500
            throw ExceptionConverter::toLegacy($e, 'MongoResultException');
501
        }
502
503
        if ($document) {
504
            $document = TypeConverter::toLegacy($document);
505
        }
506
507
        return $document;
508
    }
509
510
    /**
511
     * Querys this collection, returning a single element
512
     *
513
     * @link http://www.php.net/manual/en/mongocollection.findone.php
514
     * @param array $query The fields for which to search.
515
     * @param array $fields Fields of the results to return.
516
     * @param array $options
517
     * @return array|null
518
     */
519
    public function findOne(array $query = [], array $fields = [], array $options = [])
520
    {
521
        $options = ['projection' => $fields] + $options;
522
        try {
523
            $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
524
        } catch (\MongoDB\Driver\Exception\Exception $e) {
525
            throw ExceptionConverter::toLegacy($e);
526
        }
527
528
        if ($document !== null) {
529
            $document = TypeConverter::toLegacy($document);
530
        }
531
532
        return $document;
533
    }
534
535
    /**
536
     * Creates an index on the given field(s), or does nothing if the index already exists
537
     *
538
     * @link http://www.php.net/manual/en/mongocollection.createindex.php
539
     * @param array $keys Field or fields to use as index.
540
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
541
     * @return array Returns the database response.
542
     *
543
     * @todo This method does not yet return the correct result
544
     */
545
    public function createIndex($keys, array $options = [])
546
    {
547
        if (is_string($keys)) {
548
            if (empty($keys)) {
549
                throw new MongoException('empty string passed as key field');
550
            }
551
            $keys = [$keys => 1];
552
        }
553
554
        if (is_object($keys)) {
555
            $keys = (array) $keys;
556
        }
557
558
        if (! is_array($keys) || ! count($keys)) {
559
            throw new MongoException('keys cannot be empty');
560
        }
561
562
        // duplicate
563
        $neededOptions = ['unique' => 1, 'sparse' => 1, 'expireAfterSeconds' => 1, 'background' => 1, 'dropDups' => 1];
564
        $indexOptions = array_intersect_key($options, $neededOptions);
565
        $indexes = $this->collection->listIndexes();
566
        foreach ($indexes as $index) {
567
            if (! empty($options['name']) && $index->getName() === $options['name']) {
568
                throw new \MongoResultException(sprintf('index with name: %s already exists', $index->getName()));
569
            }
570
571
            if ($index->getKey() == $keys) {
572
                $currentIndexOptions = array_intersect_key($index->__debugInfo(), $neededOptions);
573
574
                unset($currentIndexOptions['name']);
575
                if ($currentIndexOptions != $indexOptions) {
576
                    throw new \MongoResultException('Index with same keys but different options already exists');
577
                }
578
579
                return [
580
                    'createdCollectionAutomatically' => false,
581
                    'numIndexesBefore' => count($indexes),
582
                    'numIndexesAfter' => count($indexes),
583
                    'note' => 'all indexes already exist',
584
                    'ok' => 1.0
585
                ];
586
            }
587
        }
588
589
        try {
590
            $this->collection->createIndex($keys, $this->convertWriteConcernOptions($options));
591
        } catch (\MongoDB\Driver\Exception\Exception $e) {
592
            throw ExceptionConverter::toLegacy($e);
593
        }
594
595
        return [
596
            'createdCollectionAutomatically' => true,
597
            'numIndexesBefore' => count($indexes),
598
            'numIndexesAfter' => count($indexes) + 1,
599
            'ok' => 1.0
600
        ];
601
    }
602
603
    /**
604
     * Creates an index on the given field(s), or does nothing if the index already exists
605
     *
606
     * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
607
     * @param array $keys Field or fields to use as index.
608
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
609
     * @return boolean always true
610
     * @deprecated Use MongoCollection::createIndex() instead.
611
     */
612
    public function ensureIndex(array $keys, array $options = [])
613
    {
614
        $this->createIndex($keys, $options);
615
616
        return true;
617
    }
618
619
    /**
620
     * Deletes an index from this collection
621
     *
622
     * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
623
     * @param string|array $keys Field or fields from which to delete the index.
624
     * @return array Returns the database response.
625
     */
626
    public function deleteIndex($keys)
627
    {
628
        if (is_string($keys)) {
629
            $indexName = $keys;
630
        } elseif (is_array($keys)) {
631
            $indexName = \MongoDB\generate_index_name($keys);
632
        } else {
633
            throw new \InvalidArgumentException();
634
        }
635
636
        return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
637
    }
638
639
    /**
640
     * Delete all indexes for this collection
641
     *
642
     * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
643
     * @return array Returns the database response.
644
     */
645
    public function deleteIndexes()
646
    {
647
        return TypeConverter::toLegacy($this->collection->dropIndexes());
648
    }
649
650
    /**
651
     * Returns an array of index names for this collection
652
     *
653
     * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
654
     * @return array Returns a list of index names.
655
     */
656
    public function getIndexInfo()
657
    {
658
        $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
659
            return [
660
                'v' => $indexInfo->getVersion(),
661
                'key' => $indexInfo->getKey(),
662
                'name' => $indexInfo->getName(),
663
                'ns' => $indexInfo->getNamespace(),
664
            ];
665
        };
666
667
        return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
668
    }
669
670
    /**
671
     * Counts the number of documents in this collection
672
     *
673
     * @link http://www.php.net/manual/en/mongocollection.count.php
674
     * @param array|stdClass $query
675
     * @param array $options
676
     * @return int Returns the number of documents matching the query.
677
     */
678
    public function count($query = [], array $options = [])
679
    {
680
        try {
681
            return $this->collection->count(TypeConverter::fromLegacy($query), $options);
682
        } catch (\MongoDB\Driver\Exception\Exception $e) {
683
            throw ExceptionConverter::toLegacy($e);
684
        }
685
    }
686
687
    /**
688
     * Saves an object to this collection
689
     *
690
     * @link http://www.php.net/manual/en/mongocollection.save.php
691
     * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
692
     * @param array $options Options for the save.
693
     * @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.
694
     * @throws MongoCursorException if the "w" option is set and the write fails.
695
     * @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.
696
     * @return array|boolean If w was set, returns an array containing the status of the save.
697
     * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
698
     */
699
    public function save(&$a, array $options = [])
700
    {
701
        $id = $this->ensureDocumentHasMongoId($a);
702
703
        $document = (array) $a;
704
705
        $options['upsert'] = true;
706
707
        try {
708
            /** @var \MongoDB\UpdateResult $result */
709
            $result = $this->collection->replaceOne(
710
                TypeConverter::fromLegacy(['_id' => $id]),
711
                TypeConverter::fromLegacy($document),
712
                $this->convertWriteConcernOptions($options)
713
            );
714
715
            if (! $result->isAcknowledged()) {
716
                return true;
717
            }
718
719
            $resultArray = [
720
                'ok' => 1.0,
721
                'nModified' => $result->getModifiedCount(),
722
                'n' => $result->getUpsertedCount() + $result->getModifiedCount(),
723
                'err' => null,
724
                'errmsg' => null,
725
                'updatedExisting' => $result->getUpsertedCount() == 0,
726
            ];
727
            if ($result->getUpsertedId() !== null) {
728
                $resultArray['upserted'] = TypeConverter::toLegacy($result->getUpsertedId());
729
            }
730
731
            return $resultArray;
732
        } catch (\MongoDB\Driver\Exception\Exception $e) {
733
            throw ExceptionConverter::toLegacy($e);
734
        }
735
    }
736
737
    /**
738
     * Creates a database reference
739
     *
740
     * @link http://www.php.net/manual/en/mongocollection.createdbref.php
741
     * @param array|object $document_or_id Object to which to create a reference.
742
     * @return array Returns a database reference array.
743
     */
744
    public function createDBRef($document_or_id)
745
    {
746 View Code Duplication
        if ($document_or_id instanceof \MongoId) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
747
            $id = $document_or_id;
748
        } elseif (is_object($document_or_id)) {
749
            if (! isset($document_or_id->_id)) {
750
                return null;
751
            }
752
753
            $id = $document_or_id->_id;
754
        } elseif (is_array($document_or_id)) {
755
            if (! isset($document_or_id['_id'])) {
756
                return null;
757
            }
758
759
            $id = $document_or_id['_id'];
760
        } else {
761
            $id = $document_or_id;
762
        }
763
764
        return MongoDBRef::create($this->name, $id);
765
    }
766
767
    /**
768
     * Fetches the document pointed to by a database reference
769
     *
770
     * @link http://www.php.net/manual/en/mongocollection.getdbref.php
771
     * @param array $ref A database reference.
772
     * @return array Returns the database document pointed to by the reference.
773
     */
774
    public function getDBRef(array $ref)
775
    {
776
        return $this->db->getDBRef($ref);
777
    }
778
779
    /**
780
     * Performs an operation similar to SQL's GROUP BY command
781
     *
782
     * @link http://www.php.net/manual/en/mongocollection.group.php
783
     * @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.
784
     * @param array $initial Initial value of the aggregation counter object.
785
     * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
786
     * @param array $condition An condition that must be true for a row to be considered.
787
     * @return array
788
     */
789
    public function group($keys, array $initial, $reduce, array $condition = [])
790
    {
791
        if (is_string($reduce)) {
792
            $reduce = new MongoCode($reduce);
793
        }
794
795
        $command = [
796
            'group' => [
797
                'ns' => $this->name,
798
                '$reduce' => (string)$reduce,
799
                'initial' => $initial,
800
                'cond' => $condition,
801
            ],
802
        ];
803
804
        if ($keys instanceof MongoCode) {
805
            $command['group']['$keyf'] = (string)$keys;
806
        } else {
807
            $command['group']['key'] = $keys;
808
        }
809
        if (array_key_exists('condition', $condition)) {
810
            $command['group']['cond'] = $condition['condition'];
811
        }
812
        if (array_key_exists('finalize', $condition)) {
813
            if ($condition['finalize'] instanceof MongoCode) {
814
                $condition['finalize'] = (string)$condition['finalize'];
815
            }
816
            $command['group']['finalize'] = $condition['finalize'];
817
        }
818
819
        return $this->db->command($command);
820
    }
821
822
    /**
823
     * Returns an array of cursors to iterator over a full collection in parallel
824
     *
825
     * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
826
     * @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.
827
     * @return MongoCommandCursor[]
828
     */
829
    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...
830
    {
831
        $this->notImplemented();
832
    }
833
834
    protected function notImplemented()
835
    {
836
        throw new \Exception('Not implemented');
837
    }
838
839
    /**
840
     * @return \MongoDB\Collection
841
     */
842 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...
843
    {
844
        $options = [
845
            'readPreference' => $this->readPreference,
846
            'writeConcern' => $this->writeConcern,
847
        ];
848
849
        if ($this->collection === null) {
850
            $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
851
        } else {
852
            $this->collection = $this->collection->withOptions($options);
853
        }
854
    }
855
856
    /**
857
     * Converts legacy write concern options to a WriteConcern object
858
     *
859
     * @param array $options
860
     * @return array
861
     */
862
    private function convertWriteConcernOptions(array $options)
863
    {
864
        if (isset($options['safe'])) {
865
            $options['w'] = ($options['safe']) ? 1 : 0;
866
        }
867
868
        if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
869
            $options['wTimeoutMS'] = $options['wtimeout'];
870
        }
871
872
        if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
873
            $collectionWriteConcern = $this->getWriteConcern();
874
            $writeConcern = $this->createWriteConcernFromParameters(
875
                isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
876
                isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
877
            );
878
879
            $options['writeConcern'] = $writeConcern;
880
        }
881
882
        unset($options['safe']);
883
        unset($options['w']);
884
        unset($options['wTimeout']);
885
        unset($options['wTimeoutMS']);
886
887
        return $options;
888
    }
889
890
    /**
891
     * @param array|object $document
892
     * @return MongoId
893
     */
894
    private function ensureDocumentHasMongoId(&$document)
895
    {
896
        $checkKeys = function($array) {
897
            foreach (array_keys($array) as $key) {
898
                if (empty($key) || strpos($key, '*') === 1) {
899
                    throw new \MongoException('document contain invalid key');
900
                }
901
            }
902
        };
903
904
        if (is_array($document)) {
905
            if (! isset($document['_id'])) {
906
                $document['_id'] = new \MongoId();
907
            }
908
909
            $checkKeys($document);
910
911
            return $document['_id'];
912
        } elseif (is_object($document)) {
913
            if (! isset($document->_id)) {
914
                $document->_id = new \MongoId();
915
            }
916
917
            $checkKeys((array) $document);
918
919
            return $document->_id;
920
        }
921
922
        return null;
923
    }
924
925
    private function checkCollectionName($name)
926
    {
927
        if (empty($name)) {
928
            throw new Exception('Collection name cannot be empty');
929
        } elseif (strpos($name, chr(0)) !== false) {
930
            throw new Exception('Collection name cannot contain null bytes');
931
        }
932
    }
933
}
934
935