Переглянути джерело

Implement MongoCursor::explain()

Andreas Braun 8 роки тому
батько
коміт
ff89438b9b

+ 0 - 2
README.md

@@ -102,8 +102,6 @@ unserializing them.
  method is not yet implemented.
 
 ## MongoCursor
- - The [explain](https://php.net/manual/en/mongocursor.explain.php)
- method is not yet implemented.
  - The [info](https://php.net/manual/en/mongocursor.info.php) method does not
  reliably fill all fields in the cursor information. This includes the `numReturned`
  and `server` keys once the cursor has started iterating. The `numReturned` field

+ 25 - 1
lib/Mongo/MongoCursor.php

@@ -178,7 +178,31 @@ class MongoCursor extends AbstractCursor implements Iterator
      */
     public function explain()
     {
-        $this->notImplemented();
+        $optionNames = [
+            'allowPartialResults',
+            'batchSize',
+            'cursorType',
+            'limit',
+            'maxTimeMS',
+            'noCursorTimeout',
+            'projection',
+            'skip',
+            'sort',
+        ];
+
+        $options = $this->getOptions($optionNames);
+
+        $command = [
+            'explain' => [
+                'find' => $this->collection->getCollectionName(),
+                'filter' => $this->query,
+            ] + $options,
+        ];
+
+        $explained = TypeConverter::toLegacy(iterator_to_array($this->db->command($command))[0]);
+        unset($explained['ok']);
+
+        return $explained;
     }
 
     /**

+ 35 - 0
tests/Alcaeus/MongoDbAdapter/Mongo/MongoCursorTest.php

@@ -360,6 +360,41 @@ class MongoCursorTest extends TestCase
         $this->assertSame(['type' => \MongoClient::RP_SECONDARY, 'tagsets' => [['a' => 'b']]], $cursor->getReadPreference());
     }
 
+    public function testExplain()
+    {
+        $this->prepareData();
+
+        $collection = $this->getCollection();
+        $cursor = $collection->find(['foo' => 'bar'], ['_id' => false])->skip(1)->limit(3);
+
+        $expected = [
+            'queryPlanner' => [
+                'plannerVersion' => 1,
+                'namespace' => 'mongo-php-adapter.test',
+                'indexFilterSet' => false,
+                'parsedQuery' => [
+                    'foo' => ['$eq' => 'bar']
+                ],
+                'winningPlan' => [],
+                'rejectedPlans' => [],
+            ],
+            'executionStats' => [
+                'executionSuccess' => true,
+                'nReturned' => 1,
+                'totalKeysExamined' => 0,
+                'totalDocsExamined' => 3,
+                'executionStages' => [],
+                'allPlansExecution' => [],
+            ],
+            'serverInfo' => [
+                'port' => 27017,
+            ],
+        ];
+
+        $this->assertArraySubset($expected, $cursor->explain());
+    }
+
+
     /**
      * @return \PHPUnit_Framework_MockObject_MockObject
      */