Permalink
Browse files

Fetch MongoGridFSFile after storage instead of manual construction

Manually constructing a MongoGridFSFile to save on GridFSFile causes problems if we end up calling getSize() on that object later. Fetch the actual object using the driver to ensure the internal state is sound.

See: 45016c7#commitcomment-2126151
  • Loading branch information...
1 parent 7f81f21 commit 29f47eb3b969269264cd44b695fa5fec992f161c @jmikola jmikola committed Nov 30, 2012
Showing with 18 additions and 7 deletions.
  1. +8 −2 lib/Doctrine/MongoDB/GridFS.php
  2. +10 −5 tests/Doctrine/MongoDB/Tests/GridFSTest.php
@@ -195,16 +195,22 @@ protected function doSave(array &$a, array $options = array())
*/
public function storeFile($file, array &$document, array $options = array())
{
- if (is_string($file)) {
+ if (!$file instanceof GridFSFile) {
$file = new GridFSFile($file);
}
+
if ($file->hasUnpersistedFile()) {
$id = $this->getMongoCollection()->storeFile($file->getFilename(), $document, $options);
} else {
$id = $this->getMongoCollection()->storeBytes($file->getBytes(), $document, $options);
}
+
$document = array_merge(array('_id' => $id), $document);
- $file->setMongoGridFSFile(new \MongoGridFSFile($this->getMongoCollection(), $document));
+ $gridFsFile = $this->getMongoCollection()->get($id);
+
+ // TODO: Consider throwing exception if file cannot be fetched
+ $file->setMongoGridFSFile($this->getMongoCollection()->get($id));
+
return $file;
}
@@ -38,14 +38,19 @@ public function testInsertFindOneAndWrite()
public function testStoreFile()
{
+ $document = array('foo' => 'bar');
+
$gridFS = $this->getGridFS();
+ $file = $gridFS->storeFile(__FILE__, $document);
+
+ $this->assertTrue(isset($document['_id']));
+ $this->assertEquals('bar', $document['foo']);
- $metadata = array(
- 'test' => 'file'
- );
- $file = $gridFS->storeFile(__DIR__.'/file.txt', $metadata);
$this->assertInstanceOf('Doctrine\MongoDB\GridFSFile', $file);
- $this->assertTrue(isset($metadata['_id']));
+ $this->assertFalse($file->isDirty());
+ $this->assertEquals(__FILE__, $file->getFilename());
+ $this->assertStringEqualsFile(__FILE__, $file->getBytes());
+ $this->assertEquals(filesize(__FILE__), $file->getSize());
}
public function testUpdate()

0 comments on commit 29f47eb

Please sign in to comment.