public function connect($connectionName = null)
{
$requestedConnectionChange = $connectionName !== null;
$connectionName = $connectionName ?: 'slave';
if ($connectionName !== 'slave' && $connectionName !== 'master') {
throw new \InvalidArgumentException("Invalid option to connect(), only master or slave allowed.");
}
// If we have a connection open, and this is not an explicit connection
// change request, then abort right here, because we are already done.
// This prevents writes to the slave in case of "keepSlave" option enabled.
if (isset($this->_conn) && $this->_conn && !$requestedConnectionChange) {
return false;
}
$forceMasterAsSlave = false;
if ($this->getTransactionNestingLevel() > 0) {
$connectionName = 'master';
$forceMasterAsSlave = true;
}
if (isset($this->connections[$connectionName]) && $this->connections[$connectionName]) {
$this->_conn = $this->connections[$connectionName];
if ($forceMasterAsSlave && !$this->keepSlave) {
$this->connections['slave'] = $this->_conn;
}
return false;
}
if ($connectionName === 'master') {
// Set slave connection to master to avoid invalid reads
if ($this->connections['slave'] && !$this->keepSlave) {
unset($this->connections['slave']);
}
$this->connections['master'] = $this->_conn = $this->connectTo($connectionName);
if (!$this->keepSlave) {
$this->connections['slave'] = $this->connections['master'];
}
} else {
$this->connections['slave'] = $this->_conn = $this->connectTo($connectionName);
}
if ($this->_eventManager->hasListeners(Events::postConnect)) {
$eventArgs = new ConnectionEventArgs($this);
$this->_eventManager->dispatchEvent(Events::postConnect, $eventArgs);
}
return true;
}