|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace MongoDB\Operation; |
| 4 | + |
| 5 | +use MongoDB\Driver\Command; |
| 6 | +use MongoDB\Driver\Server; |
| 7 | +use MongoDB\Exception\RuntimeException; |
| 8 | +use MongoDB\Exception\UnexpectedValueException; |
| 9 | +use MongoDB\Model\DatabaseInfoIterator; |
| 10 | +use MongoDB\Model\DatabaseInfoLegacyIterator; |
| 11 | + |
| 12 | +/** |
| 13 | + * Operation for the ListDatabases command. |
| 14 | + * |
| 15 | + * @api |
| 16 | + * @see MongoDB\Client::listDatabases() |
| 17 | + * @see http://docs.mongodb.org/manual/reference/command/ListDatabases/ |
| 18 | + */ |
| 19 | +class ListDatabases implements Executable |
| 20 | +{ |
| 21 | + private $options; |
| 22 | + |
| 23 | + /** |
| 24 | + * Constructs a listDatabases command. |
| 25 | + * |
| 26 | + * Supported options: |
| 27 | + * |
| 28 | + * * maxTimeMS (integer): The maximum amount of time to allow the query to |
| 29 | + * run. |
| 30 | + * |
| 31 | + * @param array $options Command options |
| 32 | + */ |
| 33 | + public function __construct(array $options = array()) |
| 34 | + { |
| 35 | + if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) { |
| 36 | + throw new InvalidArgumentTypeException('"maxTimeMS" option', $options['maxTimeMS'], 'integer'); |
| 37 | + } |
| 38 | + |
| 39 | + $this->options = $options; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Execute the operation. |
| 44 | + * |
| 45 | + * @see Executable::execute() |
| 46 | + * @param Server $server |
| 47 | + * @return DatabaseInfoIterator |
| 48 | + */ |
| 49 | + public function execute(Server $server) |
| 50 | + { |
| 51 | + $cmd = array('listDatabases' => 1); |
| 52 | + |
| 53 | + if (isset($this->options['maxTimeMS'])) { |
| 54 | + $cmd['maxTimeMS'] = $this->options['maxTimeMS']; |
| 55 | + } |
| 56 | + |
| 57 | + $cursor = $server->executeCommand('admin', new Command($cmd)); |
| 58 | + $cursor->setTypeMap(array('document' => 'array')); |
| 59 | + $result = current($cursor->toArray()); |
| 60 | + |
| 61 | + if (empty($result['ok'])) { |
| 62 | + throw new RuntimeException(isset($result['errmsg']) ? $result['errmsg'] : 'Unknown error'); |
| 63 | + } |
| 64 | + |
| 65 | + if ( ! isset($result['databases']) || ! is_array($result['databases'])) { |
| 66 | + throw new UnexpectedValueException('listDatabases command did not return a "databases" array'); |
| 67 | + } |
| 68 | + |
| 69 | + /* Return an Iterator instead of an array in case listDatabases is |
| 70 | + * eventually changed to return a command cursor, like the collection |
| 71 | + * and index enumeration commands. This makes the "totalSize" command |
| 72 | + * field inaccessible, but users can manually invoke the command if they |
| 73 | + * need that value. |
| 74 | + */ |
| 75 | + return new DatabaseInfoLegacyIterator($result['databases']); |
| 76 | + } |
| 77 | +} |
0 commit comments