public function connect()
{
if ($this->server && $this->server->getConnections() && $this->connection) {
return $this->_isConnected = true;
}
$cfg = $this->_config;
$this->_isConnected = false;
$host = is_array($cfg['host']) ? join(',', $cfg['host']) : $cfg['host'];
$login = $cfg['login'] ? "{$cfg['login']}:{$cfg['password']}@" : '';
$connection = "mongodb://{$login}{$host}" . ($login ? "/{$cfg['database']}" : '');
$options = array('connect' => true, 'connectTimeoutMS' => $cfg['timeout'], 'replicaSet' => $cfg['replicaSet']);
try {
if ($persist = $cfg['persistent']) {
$options['persist'] = $persist === true ? 'default' : $persist;
}
$server = $this->_classes['server'];
$this->server = new $server($connection, $options);
if ($prefs = $cfg['readPreference']) {
$prefs = !is_array($prefs) ? array($prefs, array()) : $prefs;
$this->server->setReadPreference($prefs[0], $prefs[1]);
}
if ($this->connection = $this->server->{$cfg['database']}) {
$this->_isConnected = true;
}
} catch (Exception $e) {
throw new NetworkException("Could not connect to the database.", 503, $e);
}
return $this->_isConnected;
}