Skip to content

Commit 21fb2c9

Browse files
author
Will Banfield
committed
Rename function added to bucket
1 parent 60d5e88 commit 21fb2c9

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

src/GridFS/Bucket.php

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,11 @@ public function find($filter, array $options =[])
163163
{
164164
return $this->collectionsWrapper->getFilesCollection()->find($filter, $options);
165165
}
166-
166+
/**
167+
* Gets the id of the GridFs file associated with $stream
168+
*
169+
* @param resource $stream wrapped gridFsStream
170+
*/
167171
public function getIdFromStream($stream)
168172
{
169173
$metadata = stream_get_meta_data($stream);
@@ -172,7 +176,23 @@ public function getIdFromStream($stream)
172176
}
173177
return null;
174178
}
175-
179+
/**
180+
* Gets the id of the GridFs file associated with $stream
181+
*
182+
* @param \MongoDB\BSON\ObjectId $id id of the file to rename
183+
* @param string $newFilename new name for the file
184+
* @throws \MongoDB\Exception\GridFSFileNotFoundException
185+
*/
186+
public function rename(\MongoDB\BSON\ObjectId $id, $newFilename)
187+
{
188+
$filesCollection = $this->collectionsWrapper->getFilesCollection();
189+
$file = $filesCollection->findOne(["_id" => $id]);
190+
if (is_null($file)) {
191+
throw new \MongoDB\Exception\GridFSFileNotFoundException($id, $this->collectionsWrapper->getFilesCollection()->getNameSpace());
192+
}
193+
$file->filename = $newFilename;
194+
$filesCollection->replaceOne(["_id"=> $id], $file);
195+
}
176196
public function getCollectionsWrapper()
177197
{
178198
return $this->collectionsWrapper;

tests/GridFS/BucketFunctionalTest.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,24 @@ public function testGetIdFromStream()
220220
fclose($download);
221221
$this->assertTrue($id instanceof \MongoDB\BSON\ObjectId);
222222
}
223+
public function testRename()
224+
{
225+
$id = $this->bucket->uploadFromStream("first_name", $this->generateStream("testing"));
226+
$this->assertEquals("testing", stream_get_contents($this->bucket->openDownloadStream($id)));
227+
228+
$this->bucket->rename($id, "second_name");
229+
230+
$error = null;
231+
try{
232+
$this->bucket->openDownloadStreamByName("first_name");
233+
} catch(\MongoDB\Exception\Exception $e) {
234+
$error = $e;
235+
}
236+
$fileNotFound = '\MongoDB\Exception\GridFSFileNotFoundException';
237+
$this->assertTrue($error instanceof $fileNotFound);
238+
239+
$this->assertEquals("testing", stream_get_contents($this->bucket->openDownloadStreamByName("second_name")));
240+
}
223241
/**
224242
*@dataProvider provideInsertChunks
225243
*/

0 commit comments

Comments
 (0)