Skip to content

Commit c56abb5

Browse files
committed
Merge branch 'mongocursor-key'
Merges alcaeus#40. * mongocursor-key: Fix: MongoCursor uses _id as key if present
2 parents 93bd9de + 6cb3501 commit c56abb5

File tree

4 files changed

+24
-3
lines changed

4 files changed

+24
-3
lines changed

lib/Alcaeus/MongoDbAdapter/AbstractCursor.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -277,7 +277,7 @@ protected function ensureIterator()
277277
* @param \Traversable $traversable
278278
* @return \Generator
279279
*/
280-
private function wrapTraversable(\Traversable $traversable)
280+
protected function wrapTraversable(\Traversable $traversable)
281281
{
282282
foreach ($traversable as $key => $value) {
283283
yield $key => $value;

lib/Mongo/MongoCursor.php

+14
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,20 @@ protected function ensureCursor()
426426
return $this->cursor;
427427
}
428428

429+
/**
430+
* @param \Traversable $traversable
431+
* @return \Generator
432+
*/
433+
protected function wrapTraversable(\Traversable $traversable)
434+
{
435+
foreach ($traversable as $key => $value) {
436+
if (isset($value->_id) && ($value->_id instanceof \MongoDB\BSON\ObjectID || !is_object($value->_id))) {
437+
$key = (string) $value->_id;
438+
}
439+
yield $key => $value;
440+
}
441+
}
442+
429443
/**
430444
* @return array
431445
*/

tests/Alcaeus/MongoDbAdapter/MongoCommandCursorTest.php

+7-1
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public function testInfo()
3535
$this->assertEquals($expected, $cursor->info());
3636

3737
// Ensure cursor started iterating
38-
iterator_to_array($cursor);
38+
$array = iterator_to_array($cursor);
3939

4040
$expected['started_iterating'] = true;
4141
$expected += [
@@ -49,5 +49,11 @@ public function testInfo()
4949
];
5050

5151
$this->assertEquals($expected, $cursor->info());
52+
53+
$i = 0;
54+
foreach ($array as $key => $value) {
55+
$this->assertEquals($i, $key);
56+
$i++;
57+
}
5258
}
5359
}

tests/Alcaeus/MongoDbAdapter/MongoCursorTest.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,10 @@ public function testCursorConvertsTypes()
1919
$this->assertCount(2, $cursor);
2020

2121
$iterated = 0;
22-
foreach ($cursor as $item) {
22+
foreach ($cursor as $key => $item) {
2323
$iterated++;
2424
$this->assertInstanceOf('MongoId', $item['_id']);
25+
$this->assertEquals($key, (string) $item['_id']);
2526
$this->assertSame('bar', $item['foo']);
2627
}
2728

0 commit comments

Comments
 (0)