Browse Source

Merge pull request #56 from alcaeus/fix-gridfs-findone

Ensure MongoGridFS::findOne returns null when no results are found
Andreas 10 years ago
parent
commit
6354403216

+ 1 - 1
lib/Mongo/MongoGridFS.php

@@ -132,7 +132,7 @@ class MongoGridFS extends MongoCollection
         }
 
         $items = iterator_to_array($this->find($query, $fields)->limit(1));
-        return current($items);
+        return count($items) ? current($items) : null;
     }
 
     /**

+ 6 - 0
tests/Alcaeus/MongoDbAdapter/MongoCollectionTest.php

@@ -449,6 +449,12 @@ class MongoCollectionTest extends TestCase
         $this->assertSame(['foo' => 'foo'], $document);
     }
 
+    public function testFindOneNotFound()
+    {
+        $document = $this->getCollection()->findOne(['foo' => 'foo'], ['_id' => false]);
+        $this->assertNull($document);
+    }
+
     public function testFindOneConnectionIssue()
     {
         $this->setExpectedException('MongoConnectionException');

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

@@ -280,6 +280,15 @@ class MongoGridFSTest extends TestCase
         $this->assertInstanceOf('MongoGridFSFile', $result);
     }
 
+    public function testFindOneNotFoundReturnsNull()
+    {
+        $collection = $this->getGridFS();
+
+        $result = $collection->findOne();
+
+        $this->assertNull($result);
+    }
+
     public function testPut()
     {
         $collection = $this->getGridFS();