Skip to content
Browse files

Cursor should be reset and limit should be restored after calling get…

…SingleResult.
  • Loading branch information...
1 parent fdf44d8 commit 5fb41c66de96cec3cc9a09217b4a6969ae02bfaf @Parad0X Parad0X committed
Showing with 68 additions and 2 deletions.
  1. +4 −2 lib/Doctrine/MongoDB/Cursor.php
  2. +64 −0 tests/Doctrine/MongoDB/Tests/CursorTest.php
View
6 lib/Doctrine/MongoDB/Cursor.php
@@ -334,8 +334,10 @@ public function getSingleResult()
{
$originalLimit = $this->limit;
$this->limit(1);
- $results = $this->toArray();
- return $results ? current($results) : null;
+ $result = current($this->toArray()) ?: null;
+ $this->reset();
+ $this->limit($originalLimit);
+ return $result;
}
protected function retry(\Closure $retry, $recreate = false)
View
64 tests/Doctrine/MongoDB/Tests/CursorTest.php
@@ -0,0 +1,64 @@
+<?php
+
+namespace Doctrine\MongoDB\Tests;
+
+class CursorTest extends BaseTest
+{
+ private $doc1;
+ private $doc2;
+ private $doc3;
+
+ private $cursor;
+
+ public function setUp()
+ {
+ parent::setUp();
+
+ $this->doc1 = array('name' => 'A');
+ $this->doc2 = array('name' => 'B');
+ $this->doc3 = array('name' => 'C');
+
+ $collection = $this->conn->selectCollection(self::$dbName, 'docs');
+ $collection->insert($this->doc1);
+ $collection->insert($this->doc2);
+ $collection->insert($this->doc3);
+
+ $this->cursor = $collection->createQueryBuilder()->getQuery()->execute();
+ $this->cursor->sort(array('name' => 1));
+ }
+
+ /**
+ * @covers Doctrine\MongoDB\Cursor::getSingleResult
+ */
+ public function testGetSingleResult()
+ {
+ $this->assertEquals($this->doc1, $this->cursor->getSingleResult());
+ }
+
+ /**
+ * @covers Doctrine\MongoDB\Cursor::getSingleResult
+ */
+ public function testCursorIsResetAfterGetSingleResult()
+ {
+ $this->assertEquals($this->doc1, $this->cursor->getSingleResult());
+
+ // Make sure limit is restored and cursor is rewound
+ $expected = array($this->doc1, $this->doc2, $this->doc3);
+ $actual = array();
+ foreach ($this->cursor as $entry) {
+ $actual[] = $entry;
+ }
+ $this->assertEquals($expected, $actual);
+ }
+
+ /**
+ * @covers Doctrine\MongoDB\Cursor::getSingleResult
+ */
+ public function testGetSingleResultReturnsNull()
+ {
+ $collection = $this->conn->selectCollection(self::$dbName, 'tmp');
+ $collection->remove(array());
+ $cursor = $collection->createQueryBuilder()->getQuery()->execute();
+ $this->assertNull($cursor->getSingleResult());
+ }
+}

0 comments on commit 5fb41c6

Please sign in to comment.
Something went wrong with that request. Please try again.