diff --git a/src/Mongolid/Cursor/Cursor.php b/src/Mongolid/Cursor/Cursor.php index fb83503e..16eb42d0 100644 --- a/src/Mongolid/Cursor/Cursor.php +++ b/src/Mongolid/Cursor/Cursor.php @@ -3,6 +3,7 @@ namespace Mongolid\Cursor; use IteratorIterator; +use MongoDB\Driver\ReadPreference; use Serializable; use Traversable; use MongoDB\Collection; @@ -147,6 +148,24 @@ public function disableTimeout(bool $flag = true) return $this; } + /** + * This describes how the Cursor route the future read operations to the members of a replica set. + * + * @see http://php.net/manual/pt_BR/class.mongodb-driver-readpreference.php + * + * @param int $mode preference mode that the Cursor will use + * + * @see ReadPreference::class To get a glance of the constants available + * + * @return $this + */ + public function setReadPreference(int $mode) + { + $this->params[1]['readPreference'] = new ReadPreference($mode); + + return $this; + } + /** * Counts the number of results for this cursor. * diff --git a/tests/Mongolid/Cursor/CursorTest.php b/tests/Mongolid/Cursor/CursorTest.php index 48539d7a..6ff26933 100644 --- a/tests/Mongolid/Cursor/CursorTest.php +++ b/tests/Mongolid/Cursor/CursorTest.php @@ -8,6 +8,7 @@ use Mockery as m; use MongoDB\Collection; use MongoDB\Driver\Exception\LogicException; +use MongoDB\Driver\ReadPreference; use Mongolid\ActiveRecord; use Mongolid\Connection\Connection; use Mongolid\Connection\Pool; @@ -82,6 +83,19 @@ public function testShouldSetNoCursorTimeoutToTrue() ); } + public function testShouldSetReadPreferenceParameterAccordingly() + { + // Arrange + $cursor = $this->getCursor(); + $mode = ReadPreference::RP_SECONDARY; + $cursor->setReadPreference($mode); + $readPreferenceParameter = $this->getProtected($cursor, 'params')[1]['readPreference']; + + // Assert + $this->assertInstanceOf(ReadPreference::class, $readPreferenceParameter); + $this->assertSame($readPreferenceParameter->getMode(), $mode); + } + public function testShouldCountDocuments() { // Arrange