Commit 6c1d6ac1 authored by Jeremy Mikola's avatar Jeremy Mikola

PHPLIB-72: Database enumeration method

parent e9a5e8a7
......@@ -7,6 +7,9 @@ use MongoDB\Driver\Manager;
use MongoDB\Driver\ReadPreference;
use MongoDB\Driver\Result;
use MongoDB\Driver\WriteConcern;
use ArrayIterator;
use stdClass;
use UnexpectedValueException;
class Client
{
......@@ -47,6 +50,39 @@ class Client
return $this->manager->executeCommand($databaseName, $command, $readPreference);
}
/**
* List databases.
*
* @see http://docs.mongodb.org/manual/reference/command/listDatabases/
* @return Traversable
* @throws UnexpectedValueException if the command result is malformed
*/
public function listDatabases()
{
$command = new Command(array('listDatabases' => 1));
$result = $this->manager->executeCommand('admin', $command);
$result = iterator_to_array($result);
$result = current($result);
if ( ! isset($result['databases']) || ! is_array($result['databases'])) {
throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
}
$databases = array_map(
function(stdClass $database) { return (array) $database; },
$result['databases']
);
/* Return a Traversable instead of an array in case listDatabases is
* eventually changed to return a command cursor, like the collection
* and index enumeration commands. This makes the "totalSize" command
* field inaccessible, but users can manually invoke the command if they
* need that value.
*/
return new ArrayIterator($databases);
}
/**
* Select a database.
*
......
......@@ -19,4 +19,28 @@ class ClientFunctionalTest extends FunctionalTestCase
$this->assertCommandSucceeded($commandResult);
$this->assertCollectionCount($this->getNamespace(), 0);
}
public function testListDatabases()
{
$writeResult = $this->manager->executeInsert($this->getNamespace(), array('x' => 1));
$this->assertEquals(1, $writeResult->getInsertedCount());
$client = new Client($this->getUri());
$databases = $client->listDatabases();
$this->assertInstanceOf('Traversable', $databases);
$foundDatabase = null;
foreach ($databases as $database) {
if ($database['name'] === $this->getDatabaseName()) {
$foundDatabase = $database;
break;
}
}
$this->assertNotNull($foundDatabase, 'Found test database in list of databases');
$this->assertFalse($foundDatabase['empty'], 'Test database is not empty');
$this->assertGreaterThan(0, $foundDatabase['sizeOnDisk'], 'Test database takes up disk space');
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment