Explorar el Código

Ensure cursor inherits readPreference

Andreas Braun hace 10 años
padre
commit
c7595b0c83

+ 6 - 0
lib/Alcaeus/MongoDbAdapter/Helper/ReadPreference.php

@@ -75,6 +75,12 @@ trait ReadPreference
      */
     protected function setReadPreferenceFromParameters($readPreference, $tags = null)
     {
+        // @internal Passing an array for $readPreference is necessary to avoid conversion voodoo
+        // It should not be used externally!
+        if (is_array($readPreference)) {
+            return $this->setReadPreferenceFromArray($readPreference);
+        }
+
         switch ($readPreference) {
             case \MongoClient::RP_PRIMARY:
                 $mode = \MongoDB\Driver\ReadPreference::RP_PRIMARY;

+ 8 - 2
lib/Mongo/MongoCollection.php

@@ -171,7 +171,10 @@ class MongoCollection
 
         $command += $options;
 
-        return new MongoCommandCursor($this->db->getConnection(), (string) $this, $command);
+        $cursor = new MongoCommandCursor($this->db->getConnection(), (string)$this, $command);
+        $cursor->setReadPreference($this->getReadPreference());
+
+        return $cursor;
     }
 
     /**
@@ -371,7 +374,10 @@ class MongoCollection
      */
     public function find(array $query = array(), array $fields = array())
     {
-        return new MongoCursor($this->db->getConnection(), (string) $this, $query, $fields);
+        $cursor = new MongoCursor($this->db->getConnection(), (string)$this, $query, $fields);
+        $cursor->setReadPreference($this->getReadPreference());
+
+        return $cursor;
     }
 
     /**

+ 1 - 0
lib/Mongo/MongoDB.php

@@ -385,6 +385,7 @@ class MongoDB
     {
         try {
             $cursor = new \MongoCommandCursor($this->connection, $this->name, $data);
+            $cursor->setReadPreference($this->getReadPreference());
 
             return iterator_to_array($cursor)[0];
         } catch (\MongoDB\Driver\Exception\RuntimeException $e) {

+ 9 - 0
tests/Alcaeus/MongoDbAdapter/MongoCursorTest.php

@@ -238,6 +238,15 @@ class MongoCursorTest extends TestCase
         $this->assertSame($expected, $cursor->info());
     }
 
+    public function testReadPreferenceIsInherited()
+    {
+        $collection = $this->getCollection();
+        $collection->setReadPreference(\MongoClient::RP_SECONDARY, ['a' => 'b']);
+
+        $cursor = $collection->find(['foo' => 'bar']);
+        $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => ['a' => 'b']], $cursor->getReadPreference());
+    }
+
     /**
      * @param string $name
      * @return \MongoCollection