Completed
Pull Request — master (#28)
by Andreas
12:38
created

MongoCollection::update()   B

Complexity

Conditions 6
Paths 16

Size

Total Lines 41
Code Lines 30

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 41
rs 8.439
cc 6
eloc 30
nc 16
nop 3
1
<?php
2
/*
3
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
4
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
5
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
6
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
7
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
8
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
9
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
10
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
11
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
12
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
13
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
14
 */
15
16
use Alcaeus\MongoDbAdapter\Helper;
17
use Alcaeus\MongoDbAdapter\TypeConverter;
18
use Alcaeus\MongoDbAdapter\ExceptionConverter;
19
20
/**
21
 * Represents a database collection.
22
 * @link http://www.php.net/manual/en/class.mongocollection.php
23
 */
24
class MongoCollection
1 ignored issue
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
25
{
26
    use Helper\ReadPreference;
27
    use Helper\SlaveOkay;
28
    use Helper\WriteConcern;
29
30
    const ASCENDING = 1;
31
    const DESCENDING = -1;
32
33
    /**
34
     * @var MongoDB
35
     */
36
    public $db = NULL;
37
38
    /**
39
     * @var string
40
     */
41
    protected $name;
42
43
    /**
44
     * @var \MongoDB\Collection
45
     */
46
    protected $collection;
47
48
    /**
49
     * Creates a new collection
50
     *
51
     * @link http://www.php.net/manual/en/mongocollection.construct.php
52
     * @param MongoDB $db Parent database.
53
     * @param string $name Name for this collection.
54
     * @throws Exception
55
     * @return MongoCollection
0 ignored issues
show
Comprehensibility Best Practice introduced by
Adding a @return annotation to constructors is generally not recommended as a constructor does not have a meaningful return value.

Adding a @return annotation to a constructor is not recommended, since a constructor does not have a meaningful return value.

Please refer to the PHP core documentation on constructors.

Loading history...
56
     */
57
    public function __construct(MongoDB $db, $name)
58
    {
59
        $this->checkCollectionName($name);
60
        $this->db = $db;
61
        $this->name = $name;
62
63
        $this->setReadPreferenceFromArray($db->getReadPreference());
64
        $this->setWriteConcernFromArray($db->getWriteConcern());
65
66
        $this->createCollectionObject();
67
    }
68
69
    /**
70
     * Gets the underlying collection for this object
71
     *
72
     * @internal This part is not of the ext-mongo API and should not be used
73
     * @return \MongoDB\Collection
74
     */
75
    public function getCollection()
76
    {
77
        return $this->collection;
78
    }
79
80
    /**
81
     * String representation of this collection
82
     *
83
     * @link http://www.php.net/manual/en/mongocollection.--tostring.php
84
     * @return string Returns the full name of this collection.
85
     */
86
    public function __toString()
87
    {
88
        return (string) $this->db . '.' . $this->name;
89
    }
90
91
    /**
92
     * Gets a collection
93
     *
94
     * @link http://www.php.net/manual/en/mongocollection.get.php
95
     * @param string $name The next string in the collection name.
96
     * @return MongoCollection
97
     */
98
    public function __get($name)
99
    {
100
        // Handle w and wtimeout properties that replicate data stored in $readPreference
101
        if ($name === 'w' || $name === 'wtimeout') {
102
            return $this->getWriteConcern()[$name];
103
        }
104
105
        return $this->db->selectCollection($this->name . '.' . $name);
106
    }
107
108
    /**
109
     * @param string $name
110
     * @param mixed $value
111
     */
112
    public function __set($name, $value)
113
    {
114
        if ($name === 'w' || $name === 'wtimeout') {
115
            $this->setWriteConcernFromArray([$name => $value] + $this->getWriteConcern());
116
            $this->createCollectionObject();
117
        }
118
    }
119
120
    /**
121
     * Perform an aggregation using the aggregation framework
122
     *
123
     * @link http://www.php.net/manual/en/mongocollection.aggregate.php
124
     * @param array $pipeline
125
     * @param array $op
126
     * @return array
127
     */
128
    public function aggregate(array $pipeline, array $op = [])
129
    {
130
        if (! TypeConverter::isNumericArray($pipeline)) {
131
            $pipeline = [];
132
            $options = [];
133
134
            $i = 0;
135
            foreach (func_get_args() as $operator) {
136
                $i++;
137
                if (! is_array($operator)) {
138
                    trigger_error("Argument $i is not an array", E_WARNING);
139
                    return;
140
                }
141
142
                $pipeline[] = $operator;
143
            }
144
        } else {
145
            $options = $op;
146
        }
147
148
        $command = [
149
            'aggregate' => $this->name,
150
            'pipeline' => $pipeline
151
        ];
152
153
        $command += $options;
154
155
        try {
156
            return $this->db->command($command);
157
        } catch (MongoCursorTimeoutException $e) {
158
            throw new MongoExecutionTimeoutException($e->getMessage(), $e->getCode(), $e);
159
        }
160
161
    }
162
163
    /**
164
     * Execute an aggregation pipeline command and retrieve results through a cursor
165
     *
166
     * @link http://php.net/manual/en/mongocollection.aggregatecursor.php
167
     * @param array $pipeline
168
     * @param array $options
169
     * @return MongoCommandCursor
170
     */
171
    public function aggregateCursor(array $pipeline, array $options = [])
172
    {
173
        // Build command manually, can't use mongo-php-library here
174
        $command = [
175
            'aggregate' => $this->name,
176
            'pipeline' => $pipeline
177
        ];
178
179
        // Convert cursor option
180
        if (! isset($options['cursor'])) {
181
            $options['cursor'] = true;
182
        }
183
184
        $command += $options;
185
186
        $cursor = new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
187
        $cursor->setReadPreference($this->getReadPreference());
0 ignored issues
show
Documentation introduced by
$this->getReadPreference() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
188
189
        return $cursor;
190
    }
191
192
    /**
193
     * Returns this collection's name
194
     *
195
     * @link http://www.php.net/manual/en/mongocollection.getname.php
196
     * @return string
197
     */
198
    public function getName()
199
    {
200
        return $this->name;
201
    }
202
203
    /**
204
     * {@inheritdoc}
205
     */
206
    public function setReadPreference($readPreference, $tags = null)
207
    {
208
        $result = $this->setReadPreferenceFromParameters($readPreference, $tags);
209
        $this->createCollectionObject();
210
211
        return $result;
212
    }
213
214
    /**
215
     * {@inheritdoc}
216
     */
217
    public function setWriteConcern($wstring, $wtimeout = 0)
218
    {
219
        $result = $this->setWriteConcernFromParameters($wstring, $wtimeout);
220
        $this->createCollectionObject();
221
222
        return $result;
223
    }
224
225
    /**
226
     * Drops this collection
227
     *
228
     * @link http://www.php.net/manual/en/mongocollection.drop.php
229
     * @return array Returns the database response.
230
     */
231
    public function drop()
232
    {
233
        return TypeConverter::toLegacy($this->collection->drop());
234
    }
235
236
    /**
237
     * Validates this collection
238
     *
239
     * @link http://www.php.net/manual/en/mongocollection.validate.php
240
     * @param bool $scan_data Only validate indices, not the base collection.
241
     * @return array Returns the database's evaluation of this object.
242
     */
243
    public function validate($scan_data = FALSE)
244
    {
245
        $command = [
246
            'validate' => $this->name,
247
            'full'     => $scan_data,
248
        ];
249
250
        return $this->db->command($command);
251
    }
252
253
    /**
254
     * Inserts an array into the collection
255
     *
256
     * @link http://www.php.net/manual/en/mongocollection.insert.php
257
     * @param array|object $a
258
     * @param array $options
259
     * @throws MongoException if the inserted document is empty or if it contains zero-length keys. Attempting to insert an object with protected and private properties will cause a zero-length key error.
260
     * @throws MongoCursorException if the "w" option is set and the write fails.
261
     * @throws MongoCursorTimeoutException if the "w" option is set to a value greater than one and the operation takes longer than MongoCursor::$timeout milliseconds to complete. This does not kill the operation on the server, it is a client-side timeout. The operation in MongoCollection::$wtimeout is milliseconds.
262
     * @return bool|array Returns an array containing the status of the insertion if the "w" option is set.
263
     */
264
    public function insert(&$a, array $options = [])
265
    {
266
        if (! $this->ensureDocumentHasMongoId($a)) {
267
            trigger_error(sprintf('%s(): expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
268
            return;
269
        }
270
271
        if (! count((array)$a)) {
272
            throw new \MongoException('document must be an array or object');
273
        }
274
275
        try {
276
            $result = $this->collection->insertOne(
277
                TypeConverter::fromLegacy($a),
278
                $this->convertWriteConcernOptions($options)
279
            );
280
        } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\BulkWriteException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
281
            $writeResult = $e->getWriteResult();
282
            $writeError = $writeResult->getWriteErrors()[0];
283
            return [
284
                'ok' => 0.0,
285
                'n' => 0,
286
                'err' => $writeError->getCode(),
287
                'errmsg' => $writeError->getMessage(),
288
            ];
289
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
290
            throw ExceptionConverter::toLegacy($e);
291
        }
292
293
        if (! $result->isAcknowledged()) {
294
            return true;
295
        }
296
297
        return [
298
            'ok' => 1.0,
299
            'n' => 0,
300
            'err' => null,
301
            'errmsg' => null,
302
        ];
303
    }
304
305
    /**
306
     * Inserts multiple documents into this collection
307
     *
308
     * @link http://www.php.net/manual/en/mongocollection.batchinsert.php
309
     * @param array $a An array of arrays.
310
     * @param array $options Options for the inserts.
311
     * @throws MongoCursorException
312
     * @return mixed If "safe" is set, returns an associative array with the status of the inserts ("ok") and any error that may have occured ("err"). Otherwise, returns TRUE if the batch insert was successfully sent, FALSE otherwise.
313
     */
314
    public function batchInsert(array &$a, array $options = [])
315
    {
316
        if (empty($a)) {
317
            throw new \MongoException('No write ops were included in the batch');
318
        }
319
320
        $continueOnError = isset($options['continueOnError']) && $options['continueOnError'];
321
322
        foreach ($a as $key => $item) {
323
            try {
324
                if (! $this->ensureDocumentHasMongoId($a[$key])) {
325
                    if ($continueOnError) {
326
                        unset($a[$key]);
327
                    } else {
328
                        trigger_error(sprintf('%s expects parameter %d to be an array or object, %s given', __METHOD__, 1, gettype($a)), E_USER_WARNING);
329
                        return;
330
                    }
331
                }
332
            } catch (MongoException $e) {
333
                if ( ! $continueOnError) {
334
                    throw $e;
335
                }
336
            }
337
        }
338
339
        try {
340
            $result = $this->collection->insertMany(
341
                TypeConverter::fromLegacy(array_values($a)),
342
                $this->convertWriteConcernOptions($options)
343
            );
344
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
345
            throw ExceptionConverter::toLegacy($e);
346
        }
347
348
        if (! $result->isAcknowledged()) {
349
            return true;
350
        }
351
352
        return [
353
            'connectionId' => 0,
354
            'n' => 0,
355
            'syncMillis' => 0,
356
            'writtenTo' => null,
357
            'err' => null,
358
        ];
359
    }
360
361
    /**
362
     * Update records based on a given criteria
363
     *
364
     * @link http://www.php.net/manual/en/mongocollection.update.php
365
     * @param array $criteria Description of the objects to update.
366
     * @param array $newobj The object with which to update the matching records.
367
     * @param array $options
368
     * @throws MongoCursorException
369
     * @return boolean
370
     */
371
    public function update(array $criteria , array $newobj, array $options = [])
372
    {
373
        $multiple = isset($options['multiple']) ? $options['multiple'] : false;
374
        $method = $multiple ? 'updateMany' : 'updateOne';
375
        unset($options['multiple']);
376
377
        try {
378
            /** @var \MongoDB\UpdateResult $result */
379
            $result = $this->collection->$method(
380
                TypeConverter::fromLegacy($criteria),
381
                TypeConverter::fromLegacy($newobj),
382
                $this->convertWriteConcernOptions($options)
383
            );
384
        } catch (\MongoDB\Driver\Exception\BulkWriteException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\BulkWriteException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
385
            $writeResult = $e->getWriteResult();
386
            $writeError = $writeResult->getWriteErrors()[0];
387
            return [
388
                'ok' => 0.0,
389
                'nModified' => $writeResult->getModifiedCount(),
390
                'n' => $writeResult->getMatchedCount(),
391
                'err' => $writeError->getCode(),
392
                'errmsg' => $writeError->getMessage(),
393
                'updatedExisting' => $writeResult->getUpsertedCount() == 0,
394
            ];
395
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
396
            throw ExceptionConverter::toLegacy($e);
397
        }
398
399
        if (! $result->isAcknowledged()) {
400
            return true;
401
        }
402
403
        return [
404
            'ok' => 1.0,
405
            'nModified' => $result->getModifiedCount(),
406
            'n' => $result->getMatchedCount(),
407
            'err' => null,
408
            'errmsg' => null,
409
            'updatedExisting' => $result->getUpsertedCount() == 0,
410
        ];
411
    }
412
413
    /**
414
     * Remove records from this collection
415
     *
416
     * @link http://www.php.net/manual/en/mongocollection.remove.php
417
     * @param array $criteria Query criteria for the documents to delete.
418
     * @param array $options An array of options for the remove operation.
419
     * @throws MongoCursorException
420
     * @throws MongoCursorTimeoutException
421
     * @return bool|array Returns an array containing the status of the removal
422
     * if the "w" option is set. Otherwise, returns TRUE.
423
     */
424
    public function remove(array $criteria = [], array $options = [])
425
    {
426
        $multiple = isset($options['justOne']) ? !$options['justOne'] : true;
427
        $method = $multiple ? 'deleteMany' : 'deleteOne';
428
429
        try {
430
            /** @var \MongoDB\DeleteResult $result */
431
            $result = $this->collection->$method(
432
                TypeConverter::fromLegacy($criteria),
433
                $this->convertWriteConcernOptions($options)
434
            );
435
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
436
            throw ExceptionConverter::toLegacy($e);
437
        }
438
439
        if (! $result->isAcknowledged()) {
440
            return true;
441
        }
442
443
        return [
444
            'ok' => 1.0,
445
            'n' => $result->getDeletedCount(),
446
            'err' => null,
447
            'errmsg' => null
448
        ];
449
    }
450
451
    /**
452
     * Querys this collection
453
     *
454
     * @link http://www.php.net/manual/en/mongocollection.find.php
455
     * @param array $query The fields for which to search.
456
     * @param array $fields Fields of the results to return.
457
     * @return MongoCursor
458
     */
459 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...
460
    {
461
        $cursor = new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
462
        $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...
463
464
        return $cursor;
465
    }
466
467
    /**
468
     * Retrieve a list of distinct values for the given key across a collection
469
     *
470
     * @link http://www.php.net/manual/ru/mongocollection.distinct.php
471
     * @param string $key The key to use.
472
     * @param array $query An optional query parameters
473
     * @return array|bool Returns an array of distinct values, or FALSE on failure
474
     */
475
    public function distinct($key, array $query = [])
476
    {
477
        try {
478
            return array_map([TypeConverter::class, 'toLegacy'], $this->collection->distinct($key, $query));
479
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
480
            return false;
481
        }
482
    }
483
484
    /**
485
     * Update a document and return it
486
     *
487
     * @link http://www.php.net/manual/ru/mongocollection.findandmodify.php
488
     * @param array $query The query criteria to search for.
489
     * @param array $update The update criteria.
490
     * @param array $fields Optionally only return these fields.
491
     * @param array $options An array of options to apply, such as remove the match document from the DB and return it.
492
     * @return array Returns the original document, or the modified document when new is set.
493
     */
494
    public function findAndModify(array $query, array $update = null, array $fields = null, array $options = [])
495
    {
496
        $query = TypeConverter::fromLegacy($query);
497
        try {
498
            if (isset($options['remove'])) {
499
                unset($options['remove']);
500
                $document = $this->collection->findOneAndDelete($query, $options);
501
            } else {
502
                $update = is_array($update) ? TypeConverter::fromLegacy($update) : [];
503
504
                if (isset($options['new'])) {
505
                    $options['returnDocument'] = \MongoDB\Operation\FindOneAndUpdate::RETURN_DOCUMENT_AFTER;
506
                    unset($options['new']);
507
                }
508
509
                $options['projection'] = is_array($fields) ? TypeConverter::fromLegacy($fields) : [];
510
511
                $document = $this->collection->findOneAndUpdate($query, $update, $options);
512
            }
513
        } catch (\MongoDB\Driver\Exception\ConnectionException $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\ConnectionException does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
514
            throw new MongoResultException($e->getMessage(), $e->getCode(), $e);
515
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
516
            throw ExceptionConverter::toLegacy($e, 'MongoResultException');
517
        }
518
519
        if ($document) {
520
            $document = TypeConverter::toLegacy($document);
521
        }
522
523
        return $document;
524
    }
525
526
    /**
527
     * Querys this collection, returning a single element
528
     *
529
     * @link http://www.php.net/manual/en/mongocollection.findone.php
530
     * @param array $query The fields for which to search.
531
     * @param array $fields Fields of the results to return.
532
     * @param array $options
533
     * @return array|null
534
     */
535
    public function findOne(array $query = [], array $fields = [], array $options = [])
536
    {
537
        $options = ['projection' => $fields] + $options;
538
        try {
539
            $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);
540
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
541
            throw ExceptionConverter::toLegacy($e);
542
        }
543
544
        if ($document !== null) {
545
            $document = TypeConverter::toLegacy($document);
546
        }
547
548
        return $document;
549
    }
550
551
    /**
552
     * Creates an index on the given field(s), or does nothing if the index already exists
553
     *
554
     * @link http://www.php.net/manual/en/mongocollection.createindex.php
555
     * @param array $keys Field or fields to use as index.
556
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
557
     * @return array Returns the database response.
558
     *
559
     * @todo This method does not yet return the correct result
560
     */
561
    public function createIndex($keys, array $options = [])
562
    {
563
        if (is_string($keys)) {
564
            if (empty($keys)) {
565
                throw new MongoException('empty string passed as key field');
566
            }
567
            $keys = [$keys => 1];
568
        }
569
570
        if (is_object($keys)) {
571
            $keys = (array) $keys;
572
        }
573
574
        if (! is_array($keys) || ! count($keys)) {
575
            throw new MongoException('keys cannot be empty');
576
        }
577
578
        // duplicate
579
        $neededOptions = ['unique' => 1, 'sparse' => 1, 'expireAfterSeconds' => 1, 'background' => 1, 'dropDups' => 1];
580
        $indexOptions = array_intersect_key($options, $neededOptions);
581
        $indexes = $this->collection->listIndexes();
582
        foreach ($indexes as $index) {
583
584
            if (! empty($options['name']) && $index->getName() === $options['name']) {
585
                throw new \MongoResultException(sprintf('index with name: %s already exists', $index->getName()));
586
            }
587
588
            if ($index->getKey() == $keys) {
589
                $currentIndexOptions = array_intersect_key($index->__debugInfo(), $neededOptions);
590
591
                unset($currentIndexOptions['name']);
592
                if ($currentIndexOptions != $indexOptions) {
593
                    throw new \MongoResultException('Index with same keys but different options already exists');
594
                }
595
596
                return [
597
                    'createdCollectionAutomatically' => false,
598
                    'numIndexesBefore' => count($indexes),
599
                    'numIndexesAfter' => count($indexes),
600
                    'note' => 'all indexes already exist',
601
                    'ok' => 1.0
602
                ];
603
            }
604
        }
605
606
        try {
607
            $this->collection->createIndex($keys, $this->convertWriteConcernOptions($options));
608
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
609
            throw ExceptionConverter::toLegacy($e);
610
        }
611
612
        return [
613
            'createdCollectionAutomatically' => true,
614
            'numIndexesBefore' => count($indexes),
615
            'numIndexesAfter' => count($indexes) + 1,
616
            'ok' => 1.0
617
        ];
618
    }
619
620
    /**
621
     * Creates an index on the given field(s), or does nothing if the index already exists
622
     *
623
     * @link http://www.php.net/manual/en/mongocollection.ensureindex.php
624
     * @param array $keys Field or fields to use as index.
625
     * @param array $options [optional] This parameter is an associative array of the form array("optionname" => <boolean>, ...).
626
     * @return boolean always true
627
     * @deprecated Use MongoCollection::createIndex() instead.
628
     */
629
    public function ensureIndex(array $keys, array $options = [])
630
    {
631
        $this->createIndex($keys, $options);
632
633
        return true;
634
    }
635
636
    /**
637
     * Deletes an index from this collection
638
     *
639
     * @link http://www.php.net/manual/en/mongocollection.deleteindex.php
640
     * @param string|array $keys Field or fields from which to delete the index.
641
     * @return array Returns the database response.
642
     */
643
    public function deleteIndex($keys)
644
    {
645
        if (is_string($keys)) {
646
            $indexName = $keys;
647
        } elseif (is_array($keys)) {
648
            $indexName = \MongoDB\generate_index_name($keys);
649
        } else {
650
            throw new \InvalidArgumentException();
651
        }
652
653
        return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
654
    }
655
656
    /**
657
     * Delete all indexes for this collection
658
     *
659
     * @link http://www.php.net/manual/en/mongocollection.deleteindexes.php
660
     * @return array Returns the database response.
661
     */
662
    public function deleteIndexes()
663
    {
664
        return TypeConverter::toLegacy($this->collection->dropIndexes());
665
    }
666
667
    /**
668
     * Returns an array of index names for this collection
669
     *
670
     * @link http://www.php.net/manual/en/mongocollection.getindexinfo.php
671
     * @return array Returns a list of index names.
672
     */
673
    public function getIndexInfo()
674
    {
675
        $convertIndex = function(\MongoDB\Model\IndexInfo $indexInfo) {
676
            return [
677
                'v' => $indexInfo->getVersion(),
678
                'key' => $indexInfo->getKey(),
679
                'name' => $indexInfo->getName(),
680
                'ns' => $indexInfo->getNamespace(),
681
            ];
682
        };
683
684
        return array_map($convertIndex, iterator_to_array($this->collection->listIndexes()));
685
    }
686
687
    /**
688
     * Counts the number of documents in this collection
689
     *
690
     * @link http://www.php.net/manual/en/mongocollection.count.php
691
     * @param array|stdClass $query
692
     * @param array $options
693
     * @return int Returns the number of documents matching the query.
694
     */
695
    public function count($query = [], array $options = [])
696
    {
697
        try {
698
            return $this->collection->count(TypeConverter::fromLegacy($query), $options);
699
        } catch (\MongoDB\Driver\Exception\Exception $e) {
1 ignored issue
show
Bug introduced by
The class MongoDB\Driver\Exception\Exception does not exist. Did you forget a USE statement, or did you not list all dependencies?

Scrutinizer analyzes your composer.json/composer.lock file if available to determine the classes, and functions that are defined by your dependencies.

It seems like the listed class was neither found in your dependencies, nor was it found in the analyzed files in your repository. If you are using some other form of dependency management, you might want to disable this analysis.

Loading history...
700
            throw ExceptionConverter::toLegacy($e);
701
        }
702
    }
703
704
    /**
705
     * Saves an object to this collection
706
     *
707
     * @link http://www.php.net/manual/en/mongocollection.save.php
708
     * @param array|object $a Array to save. If an object is used, it may not have protected or private properties.
709
     * @param array $options Options for the save.
710
     * @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.
711
     * @throws MongoCursorException if the "w" option is set and the write fails.
712
     * @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.
713
     * @return array|boolean If w was set, returns an array containing the status of the save.
714
     * Otherwise, returns a boolean representing if the array was not empty (an empty array will not be inserted).
715
     */
716
    public function save(&$a, array $options = [])
717
    {
718
        $id = $this->ensureDocumentHasMongoId($a);
719
720
        $document = (array) $a;
721
        unset($document['_id']);
722
723
        $options['upsert'] = true;
724
725
        $result = $this->update(['_id' => $id], ['$set' => $a], $options);
726
        if ($result['ok'] == 0.0) {
727
            throw new \MongoCursorException();
728
        }
729
730
        return $result;
731
    }
732
733
    /**
734
     * Creates a database reference
735
     *
736
     * @link http://www.php.net/manual/en/mongocollection.createdbref.php
737
     * @param array|object $document_or_id Object to which to create a reference.
738
     * @return array Returns a database reference array.
739
     */
740 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...
741
    {
742
        if ($document_or_id instanceof \MongoId) {
743
            $id = $document_or_id;
744
        } elseif (is_object($document_or_id)) {
745
            if (! isset($document_or_id->_id)) {
746
                return null;
747
            }
748
749
            $id = $document_or_id->_id;
750
        } elseif (is_array($document_or_id)) {
751
            if (! isset($document_or_id['_id'])) {
752
                return null;
753
            }
754
755
            $id = $document_or_id['_id'];
756
        } else {
757
            $id = $document_or_id;
758
        }
759
760
        return MongoDBRef::create($this->name, $id);
761
    }
762
763
    /**
764
     * Fetches the document pointed to by a database reference
765
     *
766
     * @link http://www.php.net/manual/en/mongocollection.getdbref.php
767
     * @param array $ref A database reference.
768
     * @return array Returns the database document pointed to by the reference.
769
     */
770
    public function getDBRef(array $ref)
771
    {
772
        return $this->db->getDBRef($ref);
773
    }
774
775
    /**
776
     * Performs an operation similar to SQL's GROUP BY command
777
     *
778
     * @link http://www.php.net/manual/en/mongocollection.group.php
779
     * @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.
780
     * @param array $initial Initial value of the aggregation counter object.
781
     * @param MongoCode|string $reduce A function that aggregates (reduces) the objects iterated.
782
     * @param array $condition An condition that must be true for a row to be considered.
783
     * @return array
784
     */
785
    public function group($keys, array $initial, $reduce, array $condition = [])
786
    {
787
        if (is_string($reduce)) {
788
            $reduce = new MongoCode($reduce);
789
        }
790
791
        $command = [
792
            'group' => [
793
                'ns' => $this->name,
794
                '$reduce' => (string)$reduce,
795
                'initial' => $initial,
796
                'cond' => $condition,
797
            ],
798
        ];
799
800
        if ($keys instanceof MongoCode) {
801
            $command['group']['$keyf'] = (string)$keys;
802
        } else {
803
            $command['group']['key'] = $keys;
804
        }
805
        if (array_key_exists('condition', $condition)) {
806
            $command['group']['cond'] = $condition['condition'];
807
        }
808
        if (array_key_exists('finalize', $condition)) {
809
            if ($condition['finalize'] instanceof MongoCode) {
810
                $condition['finalize'] = (string)$condition['finalize'];
811
            }
812
            $command['group']['finalize'] = $condition['finalize'];
813
        }
814
815
        return $this->db->command($command);
816
    }
817
818
    /**
819
     * Returns an array of cursors to iterator over a full collection in parallel
820
     *
821
     * @link http://www.php.net/manual/en/mongocollection.parallelcollectionscan.php
822
     * @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.
823
     * @return MongoCommandCursor[]
824
     */
825
    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...
826
    {
827
        $this->notImplemented();
828
    }
829
830
    protected function notImplemented()
831
    {
832
        throw new \Exception('Not implemented');
833
    }
834
835
    /**
836
     * @return \MongoDB\Collection
837
     */
838 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...
839
    {
840
        $options = [
841
            'readPreference' => $this->readPreference,
842
            'writeConcern' => $this->writeConcern,
843
        ];
844
845
        if ($this->collection === null) {
846
            $this->collection = $this->db->getDb()->selectCollection($this->name, $options);
847
        } else {
848
            $this->collection = $this->collection->withOptions($options);
849
        }
850
    }
851
852
    /**
853
     * Converts legacy write concern options to a WriteConcern object
854
     *
855
     * @param array $options
856
     * @return array
857
     */
858
    private function convertWriteConcernOptions(array $options)
859
    {
860
        if (isset($options['safe'])) {
861
            $options['w'] = ($options['safe']) ? 1 : 0;
862
        }
863
864
        if (isset($options['wtimeout']) && !isset($options['wTimeoutMS'])) {
865
            $options['wTimeoutMS'] = $options['wtimeout'];
866
        }
867
868
        if (isset($options['w']) || !isset($options['wTimeoutMS'])) {
869
            $collectionWriteConcern = $this->getWriteConcern();
870
            $writeConcern = $this->createWriteConcernFromParameters(
871
                isset($options['w']) ? $options['w'] : $collectionWriteConcern['w'],
872
                isset($options['wTimeoutMS']) ? $options['wTimeoutMS'] : $collectionWriteConcern['wtimeout']
873
            );
874
875
            $options['writeConcern'] = $writeConcern;
876
        }
877
878
        unset($options['safe']);
879
        unset($options['w']);
880
        unset($options['wTimeout']);
881
        unset($options['wTimeoutMS']);
882
883
        return $options;
884
    }
885
886
    /**
887
     * @param array|object $document
888
     * @return MongoId
889
     */
890
    private function ensureDocumentHasMongoId(&$document)
891
    {
892
        $checkKeys = function($array) {
893
            foreach (array_keys($array) as $key) {
894
                if (empty($key) || strpos($key, '*') === 1) {
895
                    throw new \MongoException('document contain invalid key');
896
                }
897
            }
898
        };
899
900
        if (is_array($document)) {
901
            if (! isset($document['_id'])) {
902
                $document['_id'] = new \MongoId();
903
            }
904
905
            $checkKeys($document);
906
907
            return $document['_id'];
908
        } elseif (is_object($document)) {
909
            if (! isset($document->_id)) {
910
                $document->_id = new \MongoId();
911
            }
912
913
            $checkKeys((array) $document);
914
915
            return $document->_id;
916
        }
917
918
        return null;
919
    }
920
921
    private function checkCollectionName($name)
922
    {
923
        if (empty($name)) {
924
            throw new Exception('Collection name cannot be empty');
925
        } elseif (strpos($name, chr(0)) !== false) {
926
            throw new Exception('Collection name cannot contain null bytes');
927
        }
928
    }
929
}
930
931