-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathMongoCursor.php
502 lines (441 loc) · 13.6 KB
/
MongoCursor.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
<?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (class_exists('MongoCursor', false)) {
return;
}
use Alcaeus\MongoDbAdapter\AbstractCursor;
use Alcaeus\MongoDbAdapter\TypeConverter;
use Alcaeus\MongoDbAdapter\ExceptionConverter;
use MongoDB\Driver\Cursor;
use MongoDB\Driver\ReadPreference;
use MongoDB\Operation\Find;
/**
* Result object for database query.
* @link http://www.php.net/manual/en/class.mongocursor.php
*/
class MongoCursor extends AbstractCursor implements Iterator
{
/**
* @var bool
*/
public static $slaveOkay = false;
/**
* @var int
*/
public static $timeout = 30000;
/**
* @var array
*/
protected $optionNames = [
'allowPartialResults',
'batchSize',
'cursorType',
'limit',
'maxTimeMS',
'modifiers',
'noCursorTimeout',
'projection',
'readPreference',
'skip',
'sort',
];
/**
* @var array
*/
protected $projection;
/**
* @var array
*/
protected $query;
protected $allowPartialResults;
protected $awaitData;
protected $flags = 0;
protected $hint;
protected $limit;
protected $maxTimeMS;
protected $noCursorTimeout;
protected $options = [];
protected $skip;
protected $snapshot;
protected $sort;
protected $tailable;
/**
* Create a new cursor
* @link http://www.php.net/manual/en/mongocursor.construct.php
* @param MongoClient $connection Database connection.
* @param string $ns Full name of database and collection.
* @param array $query Database query.
* @param array $fields Fields to return.
*/
public function __construct(MongoClient $connection, $ns, array $query = array(), array $fields = array())
{
parent::__construct($connection, $ns);
$this->query = $query;
$this->projection = $fields;
}
/**
* Adds a top-level key/value pair to a query
* @link http://www.php.net/manual/en/mongocursor.addoption.php
* @param string $key Fieldname to add.
* @param mixed $value Value to add.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function addOption($key, $value)
{
$this->errorIfOpened();
$this->options[$key] = $value;
return $this;
}
/**
* (PECL mongo >= 1.2.11)<br/>
* Sets whether this cursor will wait for a while for a tailable cursor to return more data
* @param bool $wait [optional] <p>If the cursor should wait for more data to become available.</p>
* @return MongoCursor Returns this cursor.
*/
public function awaitData($wait = true)
{
$this->errorIfOpened();
$this->awaitData = $wait;
return $this;
}
/**
* Counts the number of results for this query
* @link http://www.php.net/manual/en/mongocursor.count.php
* @param bool $foundOnly Send cursor limit and skip information to the count function, if applicable.
* @return int The number of documents returned by this cursor's query.
*/
public function count($foundOnly = false)
{
$optionNames = ['hint', 'maxTimeMS'];
if ($foundOnly) {
$optionNames = array_merge($optionNames, ['limit', 'skip']);
}
$options = $this->getOptions($optionNames) + $this->options;
try {
$count = $this->collection->count(TypeConverter::fromLegacy($this->query), $options);
} catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
} catch (\MongoDB\Driver\Exception\Exception $e) {
throw ExceptionConverter::toLegacy($e);
}
return $count;
}
/**
* Execute the query
* @link http://www.php.net/manual/en/mongocursor.doquery.php
* @throws MongoConnectionException if it cannot reach the database.
* @return void
*/
protected function doQuery()
{
$options = $this->getOptions() + $this->options;
try {
$this->cursor = $this->collection->find(TypeConverter::fromLegacy($this->query), $options);
} catch (\MongoDB\Driver\Exception\ExecutionTimeoutException $e) {
throw new MongoCursorTimeoutException($e->getMessage(), $e->getCode(), $e);
} catch (\MongoDB\Driver\Exception\Exception $e) {
throw ExceptionConverter::toLegacy($e);
}
}
/**
* Return an explanation of the query, often useful for optimization and debugging
* @link http://www.php.net/manual/en/mongocursor.explain.php
* @return array Returns an explanation of the query.
*/
public function explain()
{
$this->notImplemented();
}
/**
* Sets the fields for a query
* @link http://www.php.net/manual/en/mongocursor.fields.php
* @param array $f Fields to return (or not return).
* @throws MongoCursorException
* @return MongoCursor
*/
public function fields(array $f)
{
$this->errorIfOpened();
$this->projection = $f;
return $this;
}
/**
* Advances the cursor to the next result, and returns that result
* @link http://www.php.net/manual/en/mongocursor.getnext.php
* @throws MongoConnectionException
* @throws MongoCursorTimeoutException
* @return array Returns the next object
*/
public function getNext()
{
return $this->next();
}
/**
* Checks if there are any more elements in this cursor
* @link http://www.php.net/manual/en/mongocursor.hasnext.php
* @throws MongoConnectionException
* @throws MongoCursorTimeoutException
* @return bool Returns true if there is another element
*/
public function hasNext()
{
if (! $this->startedIterating) {
$this->ensureIterator();
$this->startedIterating = true;
$this->storeIteratorState();
$this->cursorNeedsAdvancing = false;
} elseif ($this->cursorNeedsAdvancing) {
$this->ensureIterator()->next();
$this->cursorNeedsAdvancing = false;
}
return $this->ensureIterator()->valid();
}
/**
* Gives the database a hint about the query
* @link http://www.php.net/manual/en/mongocursor.hint.php
* @param array|string $keyPattern Indexes to use for the query.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function hint($keyPattern)
{
$this->errorIfOpened();
$this->hint = $keyPattern;
return $this;
}
/**
* Sets whether this cursor will timeout
* @link http://www.php.net/manual/en/mongocursor.immortal.php
* @param bool $liveForever If the cursor should be immortal.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function immortal($liveForever = true)
{
$this->errorIfOpened();
$this->noCursorTimeout = $liveForever;
return $this;
}
/**
* Limits the number of results returned
* @link http://www.php.net/manual/en/mongocursor.limit.php
* @param int $num The number of results to return.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function limit($num)
{
$this->errorIfOpened();
$this->limit = $num;
return $this;
}
/**
* @param int $ms
* @return $this
* @throws MongoCursorException
*/
public function maxTimeMS($ms)
{
$this->errorIfOpened();
$this->maxTimeMS = $ms;
return $this;
}
/**
* @link http://www.php.net/manual/en/mongocursor.partial.php
* @param bool $okay [optional] <p>If receiving partial results is okay.</p>
* @return MongoCursor Returns this cursor.
*/
public function partial($okay = true)
{
$this->allowPartialResults = $okay;
return $this;
}
/**
* Clears the cursor
* @link http://www.php.net/manual/en/mongocursor.reset.php
* @return void
*/
public function reset()
{
parent::reset();
}
/**
* @link http://www.php.net/manual/en/mongocursor.setflag.php
* @param int $flag
* @param bool $set
* @return MongoCursor
*/
public function setFlag($flag, $set = true)
{
$this->notImplemented();
}
/**
* Skips a number of results
* @link http://www.php.net/manual/en/mongocursor.skip.php
* @param int $num The number of results to skip.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function skip($num)
{
$this->errorIfOpened();
$this->skip = $num;
return $this;
}
/**
* Sets whether this query can be done on a slave
* This method will override the static class variable slaveOkay.
* @link http://www.php.net/manual/en/mongocursor.slaveOkay.php
* @param boolean $okay If it is okay to query the slave.
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function slaveOkay($okay = true)
{
$this->errorIfOpened();
$this->setReadPreferenceFromSlaveOkay($okay);
return $this;
}
/**
* Use snapshot mode for the query
* @link http://www.php.net/manual/en/mongocursor.snapshot.php
* @throws MongoCursorException
* @return MongoCursor Returns this cursor
*/
public function snapshot()
{
$this->errorIfOpened();
$this->snapshot = true;
return $this;
}
/**
* Sorts the results by given fields
* @link http://www.php.net/manual/en/mongocursor.sort.php
* @param array $fields An array of fields by which to sort. Each element in the array has as key the field name, and as value either 1 for ascending sort, or -1 for descending sort
* @throws MongoCursorException
* @return MongoCursor Returns the same cursor that this method was called on
*/
public function sort(array $fields)
{
$this->errorIfOpened();
$this->sort = $fields;
return $this;
}
/**
* Sets whether this cursor will be left open after fetching the last results
* @link http://www.php.net/manual/en/mongocursor.tailable.php
* @param bool $tail If the cursor should be tailable.
* @return MongoCursor Returns this cursor
*/
public function tailable($tail = true)
{
$this->errorIfOpened();
$this->tailable = $tail;
return $this;
}
/**
* @return int|null
*/
protected function convertCursorType()
{
if (! $this->tailable) {
return null;
}
return $this->awaitData ? Find::TAILABLE_AWAIT : Find::TAILABLE;
}
/**
* @return array
*/
protected function convertModifiers()
{
$modifiers = array_key_exists('modifiers', $this->options) ? $this->options['modifiers'] : [];
foreach (['hint', 'snapshot'] as $modifier) {
if ($this->$modifier === null) {
continue;
}
$modifiers['$' . $modifier] = $this->$modifier;
}
return $modifiers;
}
/**
* @return array
*/
protected function convertProjection()
{
return TypeConverter::convertProjection($this->projection);
}
/**
* @return Cursor
*/
protected function ensureCursor()
{
if ($this->cursor === null) {
$this->doQuery();
}
return $this->cursor;
}
/**
* @param \Traversable $traversable
* @return \Generator
*/
protected function wrapTraversable(\Traversable $traversable)
{
foreach ($traversable as $key => $value) {
if (isset($value->_id) && ($value->_id instanceof \MongoDB\BSON\ObjectID || !is_object($value->_id))) {
$key = (string) $value->_id;
}
yield $key => $value;
}
}
/**
* @return array
*/
protected function getCursorInfo()
{
return [
'ns' => $this->ns,
'limit' => $this->limit,
'batchSize' => $this->batchSize,
'skip' => $this->skip,
'flags' => $this->flags,
'query' => $this->query,
'fields' => $this->projection,
];
}
/**
* @return array
*/
public function __sleep()
{
return [
'allowPartialResults',
'awaitData',
'flags',
'hint',
'limit',
'maxTimeMS',
'noCursorTimeout',
'optionNames',
'options',
'projection',
'query',
'skip',
'snapshot',
'sort',
'tailable',
] + parent::__sleep();
}
}