Permalink
Browse files

Update GridFS adapter

  • Loading branch information...
1 parent f1e6849 commit 7b0362af3557f0db38c77223e8fdb8e5a462e02d @Herzult Herzult committed Apr 16, 2012
Showing with 86 additions and 139 deletions.
  1. +6 −0 phpunit.xml.dist
  2. +8 −0 src/Gaufrette/Adapter/Base.php
  3. +49 −93 src/Gaufrette/Adapter/GridFS.php
  4. +23 −46 tests/Gaufrette/Adapter/GridFSTest.php
View
@@ -11,6 +11,12 @@
syntaxCheck="false"
bootstrap="tests/bootstrap.php.dist"
>
+
+ <php>
+ <server name="MONGO_SERVER" value="localhost:27017" />
+ <server name="MONGO_DATABASE" value="gaufrette" />
+ </php>
+
<testsuites>
<testsuite name="SimplePHPEasyPlus Test Suite">
<directory>./tests</directory>
@@ -24,4 +24,12 @@ public function createFileStream($key, Filesystem $filesystem)
{
return new FileStream\InMemoryBuffer($this, $key);
}
+
+ /**
+ * {@inheritDoc}
+ */
+ public function supportsMetadata()
+ {
+ return false;
+ }
}
@@ -2,172 +2,128 @@
namespace Gaufrette\Adapter;
-use Gaufrette\Checksum;
-use Gaufrette\Path;
-use Gaufrette\File;
-
-use Gaufrette\FileCursor\GridFS as GridFSFileCursor;
-use Gaufrette\Filesystem;
-
/**
* Adapter for the GridFS filesystem on MongoDB database
*
* @author Tomi Saarinen <tomi.saarinen@rohea.com>
+ * @author Antoine Hérault <antoine.herault@gmail.com>
*/
class GridFS extends Base
{
- /**
- * GridFS Instance
- * @var \MongoGridFS instance
- */
- protected $gridfsInstance = null;
+ protected $gridFS = null;
/**
* Constructor
*
- * @param \MongoGridFS instance
+ * @param \MongoGridFS $gridFS
*/
- public function __construct(\MongoGridFS $instance)
+ public function __construct(\MongoGridFS $gridFS)
{
- $this->gridfsInstance = $instance;
- }
-
- /**
- * Gets file object by key
- *
- * @param string $key
- * @return File file object
- */
- public function get($key, $filesystem)
- {
- $gridfsFile = $this->gridfsInstance->findOne(array('key' => $key));
- $file = new File($key, $filesystem);
- $file->setName($gridfsFile->file['filename']);
- $file->setCreated(new \DateTime("@".$gridfsFile->file['uploadDate']->sec));
- $file->setSize($gridfsFile->file['length']);
- if (isset($gridfsFile->file['metadata'])) {
- $file->setMetadata($gridfsFile->file['metadata']);
- }
-
- return $file;
+ $this->gridFS = $gridFS;
}
/**
- * {@InheritDoc}
+ * {@inheritDoc}
*/
public function read($key)
{
- //TODO: Normalize key somehow
- //var_dump( Path::normalize($key));
- $gridfsFile = $this->gridfsInstance->findOne(array('key'=>$key));
-
- return $gridfsFile->getBytes();
+ return $this->findOrError($key)->getBytes();
}
/**
- * {@InheritDoc}
- * @param array metadata any metadata in assoc array format
- * @param string filename human readable (e.g. someImage.jpg) NOT IN USE ATM.
+ * {@inheritDoc}
*/
- public function write($key, $content, array $metadata=null)
+ public function write($key, $content, array $metadata = null)
{
- //If a file exists with the same key, delete it
if ($this->exists($key)) {
$this->delete($key);
}
- //Break down key, assume '/' is used for delimiter and last part is the filename
- $keyParts = array_filter(explode('/', $key));
- $dataArray = array(
- 'key' => $key,
- 'filename' => isset($keyParts[count($keyParts)]) ? $keyParts[count($keyParts)] : '',
- 'uploadDate' => new \MongoDate(),
- 'metadata' => $metadata,
- );
- $mongoId = $this->gridfsInstance->storeBytes($content, $dataArray);
- //TODO: How to do better counting of bytes for gridfs insertion
- $numBytes = strlen($content);
-
- return $numBytes;
+
+ $id = $this->gridFS->storeBytes($content, array('filename' => $key, 'date' => new \MongoDate()));
+ $file = $this->gridFS->findOne(array('_id' => $id));
+
+ return $file->getSize();
}
/**
- * Rename = fetch old + write new + delete old
- *
- * @param key Current key (from)
- * @param new New key (to)
- * @return boolean
+ * {@inheritDoc}
*/
public function rename($key, $new)
{
- $gridfsFile = $this->gridfsInstance->findOne(array('key' => $key));
-
- if (is_object($gridfsFile)) {
- $retval = $this->write($new, $gridfsFile->getBytes(), $gridfsFile->file['metadata']);
+ $file = $this->findOrError($key);
- if ($retval > 0) {
- return $this->delete($key);
- }
- }
-
- return false;
+ $this->write($new, $file->getBytes());
+ $this->delete($key);
}
/**
* {@InheritDoc}
*/
public function exists($key)
{
- return is_object($this->gridfsInstance->findOne(array('key'=>$key)));
+ return null !== $this->gridFS->findOne($key);
}
/**
* {@InheritDoc}
*/
public function keys()
{
- /**
- * This seems to work but performance is a big question...
- */
- $cursor = $this->gridfsInstance->find(array(), array('key'));
- $temp = array();
- foreach($cursor as $f) {
- $temp[] = $f->file['key'];
+ $keys = array();
+ $cursor = $this->gridFS->find(array(), array('filename'));
+
+ foreach ($cursor as $file) {
+ $keys[] = $file->getFilename();
}
- return $temp;
+ return $keys;
}
/**
* {@InheritDoc}
*/
public function mtime($key)
{
- throw new \BadMethodCallException("Method not implemented yet.");
+ return $this->findOrError($key, array('date'))->file['date']->sec;
}
/**
* {@inheritDoc}
*/
public function checksum($key)
{
- throw new \BadMethodCallException("Method not implemented yet.");
+ return $this->findOrError($key, array('md5'))->file['md5'];
}
/**
- * {@InheritDoc}
+ * {@inheritDoc}
*/
public function delete($key)
{
- $success = $this->gridfsInstance->remove(array('key'=>$key));
+ if (!$this->gridFS->remove(array('filename' => $key))) {
+ throw new \RuntimeException(sprintf(
+ 'Cannot delete file "%s" from the Mongo GridFS.',
+ $key
+ ));
+ }
+ }
- return $success;
+ private function findOrError($key, array $fields = array())
+ {
+ $file = $this->find($key, $fields);
+
+ if (null === $file) {
+ throw new \InvalidArgumentException(sprintf(
+ 'The file "%s" was not found in the Mongo GridFS.',
+ $key
+ ));
+ }
+
+ return $file;
}
- /**
- * {@InheritDoc}
- */
- public function supportsMetadata()
+ private function find($key, array $fields = array())
{
- return true;
+ return $this->gridFS->findOne($key, $fields);
}
}
@@ -7,67 +7,44 @@
class GridFSTest extends \PHPUnit_Framework_TestCase
{
- protected $testHost = 'localhost:27017';
- protected $testDatabase = 'gaufrette_test';
-
- private $testFileKey = '/testkey/memo.txt';
- private $testFileContent = 'Lorem Ipsum...';
- private $testFileMetadata = array('foo' => 'bar');
-
- protected $gridfs;
+ protected $adapter;
public function setUp()
{
if (!class_exists('\Mongo')) {
$this->markTestSkipped('Mongo class not found.');
}
- // Connect to MongoDB
- $connection = new \Mongo($this->testHost);
+ $mongo = new \Mongo($_SERVER['MONGO_SERVER']);
- if (!$connection->connected) {
- $this->markTestSkipped('Cannot connect to Mongo server.');
+ if (!$mongo->connected) {
+ $this->markTestSkipped(sprintf(
+ 'Cannot connect to Mongo server (%s).',
+ $_SERVER['MONGO_SERVER']
+ ));
}
- // Get MongoGridFS object
- $obj = $connection->selectDB($this->testDatabase)->getGridFS();
-
- if (!($obj instanceof \MongoGridFS)) {
- $this->markTestSkipped('Cannot fetch MongoGridFS object.');
- }
+ $db = $mongo->selectDB($_SERVER['MONGO_DATABASE']);
- // Create instance of the adapter
- $this->gridfs = new GridFS($obj);
+ $grid = $db->getGridFS();
+ $grid->remove();
- if (!is_object($this->gridfs)) {
- $this->markTestSkipped('Cannot create object from adapter.');
- }
+ $this->adapter = new GridFS($grid);
}
public function testWriteReadDelete()
{
- $this->assertGreaterThan(0, $this->gridfs->write($this->testFileKey, $this->testFileContent, $this->testFileMetadata));
- $this->assertTrue($this->gridfs->exists($this->testFileKey));
-
- $this->assertEquals($this->gridfs->read($this->testFileKey), $this->testFileContent);
-
- $this->assertTrue($this->gridfs->delete($this->testFileKey));
- $this->assertFalse($this->gridfs->exists($this->testFileKey));
- }
-
- public function testRename()
- {
- $newTestFileKey = '/newtestkey/updated_memo.txt';
-
- $this->assertGreaterThan(0, $this->gridfs->write($this->testFileKey, $this->testFileContent, $this->testFileMetadata));
- $this->assertTrue($this->gridfs->exists($this->testFileKey));
-
- $this->assertTrue($this->gridfs->rename($this->testFileKey, $newTestFileKey));
- $this->assertTrue($this->gridfs->exists($newTestFileKey));
-
- $this->assertEquals($this->gridfs->read($newTestFileKey), $this->testFileContent);
-
- $this->assertFalse($this->gridfs->exists($this->testFileKey));
- $this->assertTrue($this->gridfs->delete($newTestFileKey));
+ $this->assertFalse($this->adapter->exists('foo'));
+ $this->adapter->write('foo', 'The content of foo');
+ $this->assertTrue($this->adapter->exists('foo'));
+ $this->assertEquals('The content of foo', $this->adapter->read('foo'));
+ $this->assertEquals(md5('The content of foo'), $this->adapter->checksum('foo'));
+ $this->assertEquals(time(), $this->adapter->mtime('foo'), null, 1);
+ $this->adapter->rename('foo', 'bar');
+ $this->assertFalse($this->adapter->exists('foo'));
+ $this->assertTrue($this->adapter->exists('bar'));
+ $this->assertEquals('The content of foo', $this->adapter->read('bar'));
+ $this->adapter->delete('bar');
+ $this->assertFalse($this->adapter->exists('bar'));
}
}

0 comments on commit 7b0362a

Please sign in to comment.