Skip to content

Commit

Permalink
Merge pull request #128 from leroy-merlin-br/settable-read-preference
Browse files Browse the repository at this point in the history
Allows Cursor to choose a member of the ReplicaSet
  • Loading branch information
Ernando Souza committed Aug 23, 2018
2 parents aee296d + b4953ce commit 546e910
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Mongolid/Cursor/Cursor.php
Expand Up @@ -3,6 +3,7 @@
namespace Mongolid\Cursor;

use IteratorIterator;
use MongoDB\Driver\ReadPreference;
use Serializable;
use Traversable;
use MongoDB\Collection;
Expand Down Expand Up @@ -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.
*
Expand Down
14 changes: 14 additions & 0 deletions tests/Mongolid/Cursor/CursorTest.php
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 546e910

Please sign in to comment.