Selaa lähdekoodia

Allow string parameters for MongoGridFS::findOne

Andreas Braun 10 vuotta sitten
vanhempi
commit
75e972716f

+ 7 - 1
lib/Mongo/MongoCollection.php

@@ -527,8 +527,14 @@ class MongoCollection
      * @param array $options
      * @return array|null
      */
-    public function findOne(array $query = [], array $fields = [], array $options = [])
+    public function findOne($query = [], array $fields = [], array $options = [])
     {
+        // Can't typehint for array since MongoGridFS extends and accepts strings
+        if (! is_array($query)) {
+            trigger_error(sprintf('MongoCollection::findOne(): expects parameter 1 to be an array or object, %s given', gettype($query)), E_WARNING);
+            return;
+        }
+
         $options = ['projection' => $fields] + $options;
         try {
             $document = $this->collection->findOne(TypeConverter::fromLegacy($query), $options);

+ 4 - 4
lib/Mongo/MongoGridFS.php

@@ -120,15 +120,15 @@ class MongoGridFS extends MongoCollection
      * Returns a single file matching the criteria
      *
      * @link http://www.php.net/manual/en/mongogridfs.findone.php
-     * @param array $query The fields for which to search.
+     * @param mixed $query The fields for which to search or a filename to search for.
      * @param array $fields Fields of the results to return.
      * @param array $options Options for the find command
      * @return MongoGridFSFile|null
      */
-    public function findOne(array $query = [], array $fields = [], array $options = [])
+    public function findOne($query = [], array $fields = [], array $options = [])
     {
-        if (is_string($query)) {
-            $query = ['filename' => $query];
+        if (! is_array($query)) {
+            $query = ['filename' => (string) $query];
         }
 
         $items = iterator_to_array($this->find($query, $fields)->limit(1));

+ 13 - 0
tests/Alcaeus/MongoDbAdapter/Mongo/MongoGridFSTest.php

@@ -287,6 +287,19 @@ class MongoGridFSTest extends TestCase
         $this->assertInstanceOf('MongoGridFSFile', $result);
     }
 
+    public function testFindOneWithFilenameReturnsFile()
+    {
+        $collection = $this->getGridFS();
+        $this->prepareFile('abcd', ['filename' => 'abcd']);
+        $this->prepareFile('test', ['filename' => 'test']);
+        $this->prepareFile('zyxv', ['filename' => 'zyxv']);
+
+        $result = $collection->findOne('test');
+
+        $this->assertInstanceOf('MongoGridFSFile', $result);
+        $this->assertSame('test', $result->getBytes());
+    }
+
     public function testFindOneNotFoundReturnsNull()
     {
         $collection = $this->getGridFS();