Kaynağa Gözat

Merge pull request #60 from alcaeus/catch-delete-index-exception

Properly convert exceptions when deleting all indexes
Andreas 10 yıl önce
ebeveyn
işleme
a164a9d47c

+ 15 - 0
lib/Alcaeus/MongoDbAdapter/ExceptionConverter.php

@@ -82,4 +82,19 @@ class ExceptionConverter
 
         return new $class($message, $code, $e);
     }
+
+    /**
+     * Converts an exception to
+     *
+     * @param Exception\Exception $e
+     * @return array
+     */
+    public static function toResultArray(Exception\Exception $e)
+    {
+        return [
+            'ok' => 0.0,
+            'errmsg' => $e->getMessage(),
+            'code' => $e->getCode(),
+        ];
+    }
 }

+ 6 - 7
lib/Mongo/MongoCollection.php

@@ -655,12 +655,7 @@ class MongoCollection
         try {
             return TypeConverter::toLegacy($this->collection->dropIndex($indexName));
         } catch (\MongoDB\Driver\Exception\Exception $e) {
-            return [
-                'nIndexesWas' => count($this->getIndexInfo()),
-                'errmsg' => $e->getMessage(),
-                'ok' => 0.0,
-                'code' => $e->getCode(),
-            ];
+            return ExceptionConverter::toResultArray($e) + ['nIndexesWas' => count($this->getIndexInfo())];
         }
     }
 
@@ -672,7 +667,11 @@ class MongoCollection
      */
     public function deleteIndexes()
     {
-        return TypeConverter::toLegacy($this->collection->dropIndexes());
+        try {
+            return TypeConverter::toLegacy($this->collection->dropIndexes());
+        } catch (\MongoDB\Driver\Exception\Exception $e) {
+            return ExceptionConverter::toResultArray($e);
+        }
     }
 
     /**

+ 1 - 5
lib/Mongo/MongoDB.php

@@ -404,11 +404,7 @@ class MongoDB
 
             return iterator_to_array($cursor)[0];
         } catch (\MongoDB\Driver\Exception\Exception $e) {
-            return [
-                'ok' => 0.0,
-                'errmsg' => $e->getMessage(),
-                'code' => $e->getCode(),
-            ];
+            return ExceptionConverter::toResultArray($e);
         }
     }
 

+ 10 - 0
tests/Alcaeus/MongoDbAdapter/Mongo/MongoCollectionTest.php

@@ -928,6 +928,16 @@ class MongoCollectionTest extends TestCase
         $this->assertCount(1, iterator_to_array($newCollection->listIndexes())); // ID index is present by default
     }
 
+    public function testDeleteIndexesForNonExistingCollection()
+    {
+        $expected = [
+            'ok' => 0.0,
+            'errmsg' => 'ns not found',
+            'code' => 26,
+        ];
+        $this->assertSame($expected, $this->getcollection('nonExisting')->deleteIndexes());
+    }
+
     public function testGetIndexInfo()
     {
         $collection = $this->getCollection();