public function _getReadProtocol(array $readPreference = array())
{
if (empty($readPreference)) {
$readPreference = $this->getReadPreference();
}
$this->connect();
if (!$this->replSet) {
return reset($this->protocols);
}
// Statically cache which protocol is chosen for a given read preference (request association)
$cache_key = json_encode($readPreference);
static $cache = [];
if (isset($cache[$cache_key])) {
return $cache[$cache_key];
}
switch ($readPreference['type']) {
case self::RP_PRIMARY:
return $cache[$cache_key] = $this->_getWriteProtocol();
case self::RP_PRIMARY_PREFERRED:
try {
return $cache[$cache_key] = $this->_getWriteProtocol();
} catch (MongoConnectionException $e) {
// Fall through to reading from secondary
}
case self::RP_SECONDARY:
return $cache[$cache_key] = $this->getNearestHostProtocol([static::STATE_STR_SECONDARY], $readPreference);
case self::RP_SECONDARY_PREFERRED:
try {
return $cache[$cache_key] = $this->getNearestHostProtocol([static::STATE_STR_SECONDARY], $readPreference);
} catch (MongoConnectionException $e) {
return $cache[$cache_key] = $this->_getWriteProtocol();
}
case self::RP_NEAREST:
return $cache[$cache_key] = $this->getNearestHostProtocol([static::STATE_STR_PRIMARY, static::STATE_STR_SECONDARY], $readPreference);
default:
throw new MongoConnectionException("Invalid read preference ({$readPreference['type']}");
}
}