<?php
 namespace MongoDB\Operation;
 use MongoDB\Driver\Command;
 use MongoDB\Driver\Exception\RuntimeException as DriverRuntimeException;
 use MongoDB\Driver\Server;
 use MongoDB\Driver\Session;
 use MongoDB\Exception\InvalidArgumentException;
 use MongoDB\Exception\UnexpectedValueException;
 use MongoDB\Model\DatabaseInfoIterator;
 use MongoDB\Model\DatabaseInfoLegacyIterator;
 use function current;
 use function is_array;
 use function is_integer;
 use function is_object;
 class ListDatabases implements Executable {
 private $options;
 public function __construct(array $options = []) {
 if (isset($options['filter']) && ! is_array($options['filter']) && ! is_object($options['filter'])) {
 throw InvalidArgumentException::invalidType('"filter" option', $options['filter'], 'array or object');
 }
 if (isset($options['maxTimeMS']) && ! is_integer($options['maxTimeMS'])) {
 throw InvalidArgumentException::invalidType('"maxTimeMS" option', $options['maxTimeMS'], 'integer');
 }
 if (isset($options['session']) && ! $options['session'] instanceof Session) {
 throw InvalidArgumentException::invalidType('"session" option', $options['session'], Session::class);
 }
 $this->options = $options;
 }
 public function execute(Server $server) {
 $cmd = ['listDatabases' => 1];
 if (! empty($this->options['filter'])) {
 $cmd['filter'] = (object) $this->options['filter'];
 }
 if (isset($this->options['maxTimeMS'])) {
 $cmd['maxTimeMS'] = $this->options['maxTimeMS'];
 }
 $cursor = $server->executeReadCommand('admin', new Command($cmd), $this->createOptions());
 $cursor->setTypeMap(['root' => 'array', 'document' => 'array']);
 $result = current($cursor->toArray());
 if (! isset($result['databases']) || ! is_array($result['databases'])) {
 throw new UnexpectedValueException('listDatabases command did not return a "databases" array');
 }
 return new DatabaseInfoLegacyIterator($result['databases']);
 }
 private function createOptions() {
 $options = [];
 if (isset($this->options['session'])) {
 $options['session'] = $this->options['session'];
 }
 return $options;
 }
 }
 