|
7 | 7 | use MongoDB\Driver\ReadPreference;
|
8 | 8 | use MongoDB\Driver\Result;
|
9 | 9 | use MongoDB\Driver\WriteConcern;
|
| 10 | +use ArrayIterator; |
| 11 | +use stdClass; |
| 12 | +use UnexpectedValueException; |
10 | 13 |
|
11 | 14 | class Client
|
12 | 15 | {
|
@@ -47,6 +50,39 @@ public function dropDatabase($databaseName)
|
47 | 50 | return $this->manager->executeCommand($databaseName, $command, $readPreference);
|
48 | 51 | }
|
49 | 52 |
|
| 53 | + /** |
| 54 | + * List databases. |
| 55 | + * |
| 56 | + * @see http://docs.mongodb.org/manual/reference/command/listDatabases/ |
| 57 | + * @return Traversable |
| 58 | + * @throws UnexpectedValueException if the command result is malformed |
| 59 | + */ |
| 60 | + public function listDatabases() |
| 61 | + { |
| 62 | + $command = new Command(array('listDatabases' => 1)); |
| 63 | + |
| 64 | + $result = $this->manager->executeCommand('admin', $command); |
| 65 | + $result = iterator_to_array($result); |
| 66 | + $result = current($result); |
| 67 | + |
| 68 | + if ( ! isset($result['databases']) || ! is_array($result['databases'])) { |
| 69 | + throw new UnexpectedValueException('listDatabases command did not return a "databases" array'); |
| 70 | + } |
| 71 | + |
| 72 | + $databases = array_map( |
| 73 | + function(stdClass $database) { return (array) $database; }, |
| 74 | + $result['databases'] |
| 75 | + ); |
| 76 | + |
| 77 | + /* Return a Traversable instead of an array in case listDatabases is |
| 78 | + * eventually changed to return a command cursor, like the collection |
| 79 | + * and index enumeration commands. This makes the "totalSize" command |
| 80 | + * field inaccessible, but users can manually invoke the command if they |
| 81 | + * need that value. |
| 82 | + */ |
| 83 | + return new ArrayIterator($databases); |
| 84 | + } |
| 85 | + |
50 | 86 | /**
|
51 | 87 | * Select a database.
|
52 | 88 | *
|
|
0 commit comments