_id stringlengths 2 7 | title stringlengths 3 151 | partition stringclasses 3
values | text stringlengths 83 13k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q13900 | ReplicationStrategy.isGeoradiusReadOnly | train | protected function isGeoradiusReadOnly(CommandInterface $command)
{
$arguments = $command->getArguments();
$argc = count($arguments);
$startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4;
if ($argc > $startIndex) {
for ($i = $startIndex; $i < $argc; ++$i) {
$argument = strtoupper($arguments[$i]);
if ($argument === 'STORE' || $argument === 'STOREDIST') {
return false;
}
}
}
return true;
} | php | {
"resource": ""
} |
q13901 | ReplicationStrategy.setCommandReadOnly | train | public function setCommandReadOnly($commandID, $readonly = true)
{
$commandID = strtoupper($commandID);
if ($readonly) {
$this->readonly[$commandID] = $readonly;
} else {
unset($this->readonly[$commandID]);
}
} | php | {
"resource": ""
} |
q13902 | ReplicationStrategy.setScriptReadOnly | train | public function setScriptReadOnly($script, $readonly = true)
{
$sha1 = sha1($script);
if ($readonly) {
$this->readonlySHA1[$sha1] = $readonly;
} else {
unset($this->readonlySHA1[$sha1]);
}
} | php | {
"resource": ""
} |
q13903 | ReplicationStrategy.getDisallowedOperations | train | protected function getDisallowedOperations()
{
return array(
'SHUTDOWN' => true,
'INFO' => true,
'DBSIZE' => true,
'LASTSAVE' => true,
'CONFIG' => true,
'MONITOR' => true,
'SLAVEOF' => true,
'SAVE' => true,
'BGSAVE' => true,
'BGREWRITEAOF' => true,
'SLOWLOG' => true,
);
} | php | {
"resource": ""
} |
q13904 | ReplicationStrategy.getReadOnlyOperations | train | protected function getReadOnlyOperations()
{
return array(
'EXISTS' => true,
'TYPE' => true,
'KEYS' => true,
'SCAN' => true,
'RANDOMKEY' => true,
'TTL' => true,
'GET' => true,
'MGET' => true,
'SUBSTR' => true,
'STRLEN' => true,
'GETRANGE' => true,
'GETBIT' => true,
'LLEN' => true,
'LRANGE' => true,
'LINDEX' => true,
'SCARD' => true,
'SISMEMBER' => true,
'SINTER' => true,
'SUNION' => true,
'SDIFF' => true,
'SMEMBERS' => true,
'SSCAN' => true,
'SRANDMEMBER' => true,
'ZRANGE' => true,
'ZREVRANGE' => true,
'ZRANGEBYSCORE' => true,
'ZREVRANGEBYSCORE' => true,
'ZCARD' => true,
'ZSCORE' => true,
'ZCOUNT' => true,
'ZRANK' => true,
'ZREVRANK' => true,
'ZSCAN' => true,
'ZLEXCOUNT' => true,
'ZRANGEBYLEX' => true,
'ZREVRANGEBYLEX' => true,
'HGET' => true,
'HMGET' => true,
'HEXISTS' => true,
'HLEN' => true,
'HKEYS' => true,
'HVALS' => true,
'HGETALL' => true,
'HSCAN' => true,
'HSTRLEN' => true,
'PING' => true,
'AUTH' => true,
'SELECT' => true,
'ECHO' => true,
'QUIT' => true,
'OBJECT' => true,
'BITCOUNT' => true,
'BITPOS' => true,
'TIME' => true,
'PFCOUNT' => true,
'SORT' => array($this, 'isSortReadOnly'),
'BITFIELD' => array($this, 'isBitfieldReadOnly'),
'GEOHASH' => true,
'GEOPOS' => true,
'GEODIST' => true,
'GEORADIUS' => array($this, 'isGeoradiusReadOnly'),
'GEORADIUSBYMEMBER' => array($this, 'isGeoradiusReadOnly'),
);
} | php | {
"resource": ""
} |
q13905 | Client.createOptions | train | protected function createOptions($options)
{
if (is_array($options)) {
return new Options($options);
}
if ($options instanceof OptionsInterface) {
return $options;
}
throw new \InvalidArgumentException('Invalid type for client options.');
} | php | {
"resource": ""
} |
q13906 | Client.getConnectionById | train | public function getConnectionById($connectionID)
{
if (!$this->connection instanceof AggregateConnectionInterface) {
throw new NotSupportedException(
'Retrieving connections by ID is supported only by aggregate connections.'
);
}
return $this->connection->getConnectionById($connectionID);
} | php | {
"resource": ""
} |
q13907 | Client.createPipeline | train | protected function createPipeline(array $options = null, $callable = null)
{
if (isset($options['atomic']) && $options['atomic']) {
$class = 'Predis\Pipeline\Atomic';
} elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
$class = 'Predis\Pipeline\FireAndForget';
} else {
$class = 'Predis\Pipeline\Pipeline';
}
/*
* @var ClientContextInterface
*/
$pipeline = new $class($this);
if (isset($callable)) {
return $pipeline->execute($callable);
}
return $pipeline;
} | php | {
"resource": ""
} |
q13908 | Client.createTransaction | train | protected function createTransaction(array $options = null, $callable = null)
{
$transaction = new MultiExecTransaction($this, $options);
if (isset($callable)) {
return $transaction->execute($callable);
}
return $transaction;
} | php | {
"resource": ""
} |
q13909 | ListKey.reset | train | protected function reset()
{
$this->valid = true;
$this->fetchmore = true;
$this->elements = array();
$this->position = -1;
$this->current = null;
} | php | {
"resource": ""
} |
q13910 | ListKey.executeCommand | train | protected function executeCommand()
{
return $this->client->lrange($this->key, $this->position + 1, $this->position + $this->count);
} | php | {
"resource": ""
} |
q13911 | PhpiredisStreamConnection.createReader | train | private function createReader()
{
$reader = phpiredis_reader_create();
phpiredis_reader_set_status_handler($reader, $this->getStatusHandler());
phpiredis_reader_set_error_handler($reader, $this->getErrorHandler());
return $reader;
} | php | {
"resource": ""
} |
q13912 | MasterSlaveReplication.handleInfoResponse | train | private function handleInfoResponse($response)
{
$info = array();
foreach (preg_split('/\r?\n/', $response) as $row) {
if (strpos($row, ':') === false) {
continue;
}
list($k, $v) = explode(':', $row, 2);
$info[$k] = $v;
}
return $info;
} | php | {
"resource": ""
} |
q13913 | MasterSlaveReplication.discover | train | public function discover()
{
if (!$this->connectionFactory) {
throw new ClientException('Discovery requires a connection factory');
}
RETRY_FETCH: {
try {
if ($connection = $this->getMaster()) {
$this->discoverFromMaster($connection, $this->connectionFactory);
} elseif ($connection = $this->pickSlave()) {
$this->discoverFromSlave($connection, $this->connectionFactory);
} else {
throw new ClientException('No connection available for discovery');
}
} catch (ConnectionException $exception) {
$this->remove($connection);
goto RETRY_FETCH;
}
}
} | php | {
"resource": ""
} |
q13914 | MasterSlaveReplication.discoverFromMaster | train | protected function discoverFromMaster(NodeConnectionInterface $connection, FactoryInterface $connectionFactory)
{
$response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION'));
$replication = $this->handleInfoResponse($response);
if ($replication['role'] !== 'master') {
throw new ClientException("Role mismatch (expected master, got slave) [$connection]");
}
$this->slaves = array();
foreach ($replication as $k => $v) {
$parameters = null;
if (strpos($k, 'slave') === 0 && preg_match('/ip=(?P<host>.*),port=(?P<port>\d+)/', $v, $parameters)) {
$slaveConnection = $connectionFactory->create(array(
'host' => $parameters['host'],
'port' => $parameters['port'],
));
$this->add($slaveConnection);
}
}
} | php | {
"resource": ""
} |
q13915 | MasterSlaveReplication.discoverFromSlave | train | protected function discoverFromSlave(NodeConnectionInterface $connection, FactoryInterface $connectionFactory)
{
$response = $connection->executeCommand(RawCommand::create('INFO', 'REPLICATION'));
$replication = $this->handleInfoResponse($response);
if ($replication['role'] !== 'slave') {
throw new ClientException("Role mismatch (expected slave, got master) [$connection]");
}
$masterConnection = $connectionFactory->create(array(
'host' => $replication['master_host'],
'port' => $replication['master_port'],
'alias' => 'master',
));
$this->add($masterConnection);
$this->discoverFromMaster($masterConnection, $connectionFactory);
} | php | {
"resource": ""
} |
q13916 | MasterSlaveReplication.retryCommandOnFailure | train | private function retryCommandOnFailure(CommandInterface $command, $method)
{
RETRY_COMMAND: {
try {
$connection = $this->getConnection($command);
$response = $connection->$method($command);
if ($response instanceof ResponseErrorInterface && $response->getErrorType() === 'LOADING') {
throw new ConnectionException($connection, "Redis is loading the dataset in memory [$connection]");
}
} catch (ConnectionException $exception) {
$connection = $exception->getConnection();
$connection->disconnect();
if ($connection === $this->master && !$this->autoDiscovery) {
// Throw immediately when master connection is failing, even
// when the command represents a read-only operation, unless
// automatic discovery has been enabled.
throw $exception;
} else {
// Otherwise remove the failing slave and attempt to execute
// the command again on one of the remaining slaves...
$this->remove($connection);
}
// ... that is, unless we have no more connections to use.
if (!$this->slaves && !$this->master) {
throw $exception;
} elseif ($this->autoDiscovery) {
$this->discover();
}
goto RETRY_COMMAND;
} catch (MissingMasterException $exception) {
if ($this->autoDiscovery) {
$this->discover();
} else {
throw $exception;
}
goto RETRY_COMMAND;
}
}
return $response;
} | php | {
"resource": ""
} |
q13917 | AbstractConsumer.subscribe | train | public function subscribe($channel /*, ... */)
{
$this->writeRequest(self::SUBSCRIBE, func_get_args());
$this->statusFlags |= self::STATUS_SUBSCRIBED;
} | php | {
"resource": ""
} |
q13918 | AbstractConsumer.psubscribe | train | public function psubscribe($pattern /* ... */)
{
$this->writeRequest(self::PSUBSCRIBE, func_get_args());
$this->statusFlags |= self::STATUS_PSUBSCRIBED;
} | php | {
"resource": ""
} |
q13919 | AbstractConsumer.stop | train | public function stop($drop = false)
{
if (!$this->valid()) {
return false;
}
if ($drop) {
$this->invalidate();
$this->disconnect();
} else {
if ($this->isFlagSet(self::STATUS_SUBSCRIBED)) {
$this->unsubscribe();
}
if ($this->isFlagSet(self::STATUS_PSUBSCRIBED)) {
$this->punsubscribe();
}
}
return !$drop;
} | php | {
"resource": ""
} |
q13920 | AbstractConsumer.valid | train | public function valid()
{
$isValid = $this->isFlagSet(self::STATUS_VALID);
$subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED;
$hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0;
return $isValid && $hasSubscriptions;
} | php | {
"resource": ""
} |
q13921 | PredisCluster.removeById | train | public function removeById($connectionID)
{
if ($connection = $this->getConnectionById($connectionID)) {
return $this->remove($connection);
}
return false;
} | php | {
"resource": ""
} |
q13922 | PredisCluster.getConnectionByKey | train | public function getConnectionByKey($key)
{
$hash = $this->strategy->getSlotByKey($key);
$node = $this->distributor->getBySlot($hash);
return $node;
} | php | {
"resource": ""
} |
q13923 | PredisCluster.executeCommandOnNodes | train | public function executeCommandOnNodes(CommandInterface $command)
{
$responses = array();
foreach ($this->pool as $connection) {
$responses[] = $connection->executeCommand($command);
}
return $responses;
} | php | {
"resource": ""
} |
q13924 | ServerInfo.parseRow | train | protected function parseRow($row)
{
list($k, $v) = explode(':', $row, 2);
if (preg_match('/^db\d+$/', $k)) {
$v = $this->parseDatabaseStats($v);
}
return array($k, $v);
} | php | {
"resource": ""
} |
q13925 | ServerInfo.parseDatabaseStats | train | protected function parseDatabaseStats($str)
{
$db = array();
foreach (explode(',', $str) as $dbvar) {
list($dbvk, $dbvv) = explode('=', $dbvar);
$db[trim($dbvk)] = $dbvv;
}
return $db;
} | php | {
"resource": ""
} |
q13926 | ServerInfo.parseAllocationStats | train | protected function parseAllocationStats($str)
{
$stats = array();
foreach (explode(',', $str) as $kv) {
@list($size, $objects, $extra) = explode('=', $kv);
// hack to prevent incorrect values when parsing the >=256 key
if (isset($extra)) {
$size = ">=$objects";
$objects = $extra;
}
$stats[$size] = $objects;
}
return $stats;
} | php | {
"resource": ""
} |
q13927 | Command.normalizeVariadic | train | public static function normalizeVariadic(array $arguments)
{
if (count($arguments) === 2 && is_array($arguments[1])) {
return array_merge(array($arguments[0]), $arguments[1]);
}
return $arguments;
} | php | {
"resource": ""
} |
q13928 | Parameters.parse | train | public static function parse($uri)
{
if (stripos($uri, 'unix://') === 0) {
// parse_url() can parse unix:/path/to/sock so we do not need the
// unix:///path/to/sock hack, we will support it anyway until 2.0.
$uri = str_ireplace('unix://', 'unix:', $uri);
}
if (!$parsed = parse_url($uri)) {
throw new \InvalidArgumentException("Invalid parameters URI: $uri");
}
if (
isset($parsed['host'])
&& false !== strpos($parsed['host'], '[')
&& false !== strpos($parsed['host'], ']')
) {
$parsed['host'] = substr($parsed['host'], 1, -1);
}
if (isset($parsed['query'])) {
parse_str($parsed['query'], $queryarray);
unset($parsed['query']);
$parsed = array_merge($parsed, $queryarray);
}
if (stripos($uri, 'redis') === 0) {
if (isset($parsed['pass'])) {
$parsed['password'] = $parsed['pass'];
unset($parsed['pass']);
}
if (isset($parsed['path']) && preg_match('/^\/(\d+)(\/.*)?/', $parsed['path'], $path)) {
$parsed['database'] = $path[1];
if (isset($path[2])) {
$parsed['path'] = $path[2];
} else {
unset($parsed['path']);
}
}
}
return $parsed;
} | php | {
"resource": ""
} |
q13929 | PhpiredisSocketConnection.emitSocketError | train | private function emitSocketError()
{
$errno = socket_last_error();
$errstr = socket_strerror($errno);
$this->disconnect();
$this->onConnectionError(trim($errstr), $errno);
} | php | {
"resource": ""
} |
q13930 | PhpiredisSocketConnection.getAddress | train | protected static function getAddress(ParametersInterface $parameters)
{
if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
return $host;
}
if ($host === $address = gethostbyname($host)) {
return false;
}
return $address;
} | php | {
"resource": ""
} |
q13931 | PhpiredisSocketConnection.setSocketOptions | train | private function setSocketOptions($socket, ParametersInterface $parameters)
{
if ($parameters->scheme !== 'unix') {
if (!socket_set_option($socket, SOL_TCP, TCP_NODELAY, 1)) {
$this->emitSocketError();
}
if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) {
$this->emitSocketError();
}
}
if (isset($parameters->read_write_timeout)) {
$rwtimeout = (float) $parameters->read_write_timeout;
$timeoutSec = floor($rwtimeout);
$timeoutUsec = ($rwtimeout - $timeoutSec) * 1000000;
$timeout = array(
'sec' => $timeoutSec,
'usec' => $timeoutUsec,
);
if (!socket_set_option($socket, SOL_SOCKET, SO_SNDTIMEO, $timeout)) {
$this->emitSocketError();
}
if (!socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout)) {
$this->emitSocketError();
}
}
} | php | {
"resource": ""
} |
q13932 | PhpiredisSocketConnection.connectWithTimeout | train | private function connectWithTimeout($socket, $address, ParametersInterface $parameters)
{
socket_set_nonblock($socket);
if (@socket_connect($socket, $address, (int) $parameters->port) === false) {
$error = socket_last_error();
if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) {
$this->emitSocketError();
}
}
socket_set_block($socket);
$null = null;
$selectable = array($socket);
$timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);
$timeoutSecs = floor($timeout);
$timeoutUSecs = ($timeout - $timeoutSecs) * 1000000;
$selected = socket_select($selectable, $selectable, $null, $timeoutSecs, $timeoutUSecs);
if ($selected === 2) {
$this->onConnectionError('Connection refused.', SOCKET_ECONNREFUSED);
}
if ($selected === 0) {
$this->onConnectionError('Connection timed out.', SOCKET_ETIMEDOUT);
}
if ($selected === false) {
$this->emitSocketError();
}
} | php | {
"resource": ""
} |
q13933 | WebdisConnection.createCurl | train | private function createCurl()
{
$parameters = $this->getParameters();
$timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0) * 1000;
if (filter_var($host = $parameters->host, FILTER_VALIDATE_IP)) {
$host = "[$host]";
}
$options = array(
CURLOPT_FAILONERROR => true,
CURLOPT_CONNECTTIMEOUT_MS => $timeout,
CURLOPT_URL => "$parameters->scheme://$host:$parameters->port",
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_POST => true,
CURLOPT_WRITEFUNCTION => array($this, 'feedReader'),
);
if (isset($parameters->user, $parameters->pass)) {
$options[CURLOPT_USERPWD] = "{$parameters->user}:{$parameters->pass}";
}
curl_setopt_array($resource = curl_init(), $options);
return $resource;
} | php | {
"resource": ""
} |
q13934 | MultiExec.assertClient | train | private function assertClient(ClientInterface $client)
{
if ($client->getConnection() instanceof AggregateConnectionInterface) {
throw new NotSupportedException(
'Cannot initialize a MULTI/EXEC transaction over aggregate connections.'
);
}
if (!$client->getProfile()->supportsCommands(array('MULTI', 'EXEC', 'DISCARD'))) {
throw new NotSupportedException(
'The current profile does not support MULTI, EXEC and DISCARD.'
);
}
} | php | {
"resource": ""
} |
q13935 | MultiExec.configure | train | protected function configure(ClientInterface $client, array $options)
{
if (isset($options['exceptions'])) {
$this->exceptions = (bool) $options['exceptions'];
} else {
$this->exceptions = $client->getOptions()->exceptions;
}
if (isset($options['cas'])) {
$this->modeCAS = (bool) $options['cas'];
}
if (isset($options['watch']) && $keys = $options['watch']) {
$this->watchKeys = $keys;
}
if (isset($options['retry'])) {
$this->attempts = (int) $options['retry'];
}
} | php | {
"resource": ""
} |
q13936 | MultiExec.call | train | protected function call($commandID, array $arguments = array())
{
$response = $this->client->executeCommand(
$this->client->createCommand($commandID, $arguments)
);
if ($response instanceof ErrorResponseInterface) {
throw new ServerException($response->getMessage());
}
return $response;
} | php | {
"resource": ""
} |
q13937 | MultiExec.watch | train | public function watch($keys)
{
if (!$this->client->getProfile()->supportsCommand('WATCH')) {
throw new NotSupportedException('WATCH is not supported by the current profile.');
}
if ($this->state->isWatchAllowed()) {
throw new ClientException('Sending WATCH after MULTI is not allowed.');
}
$response = $this->call('WATCH', is_array($keys) ? $keys : array($keys));
$this->state->flag(MultiExecState::WATCH);
return $response;
} | php | {
"resource": ""
} |
q13938 | MultiExec.multi | train | public function multi()
{
if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) {
$this->state->unflag(MultiExecState::CAS);
$this->call('MULTI');
} else {
$this->initialize();
}
return $this;
} | php | {
"resource": ""
} |
q13939 | MultiExec.discard | train | public function discard()
{
if ($this->state->isInitialized()) {
$this->call($this->state->isCAS() ? 'UNWATCH' : 'DISCARD');
$this->reset();
$this->state->flag(MultiExecState::DISCARDED);
}
return $this;
} | php | {
"resource": ""
} |
q13940 | MultiExec.checkBeforeExecution | train | private function checkBeforeExecution($callable)
{
if ($this->state->isExecuting()) {
throw new ClientException(
'Cannot invoke "execute" or "exec" inside an active transaction context.'
);
}
if ($callable) {
if (!is_callable($callable)) {
throw new \InvalidArgumentException('The argument must be a callable object.');
}
if (!$this->commands->isEmpty()) {
$this->discard();
throw new ClientException(
'Cannot execute a transaction block after using fluent interface.'
);
}
} elseif ($this->attempts) {
$this->discard();
throw new ClientException(
'Automatic retries are supported only when a callable block is provided.'
);
}
} | php | {
"resource": ""
} |
q13941 | MultiExec.executeTransactionBlock | train | protected function executeTransactionBlock($callable)
{
$exception = null;
$this->state->flag(MultiExecState::INSIDEBLOCK);
try {
call_user_func($callable, $this);
} catch (CommunicationException $exception) {
// NOOP
} catch (ServerException $exception) {
// NOOP
} catch (\Exception $exception) {
$this->discard();
}
$this->state->unflag(MultiExecState::INSIDEBLOCK);
if ($exception) {
throw $exception;
}
} | php | {
"resource": ""
} |
q13942 | ResponseReader.getDefaultHandlers | train | protected function getDefaultHandlers()
{
return array(
'+' => new Handler\StatusResponse(),
'-' => new Handler\ErrorResponse(),
':' => new Handler\IntegerResponse(),
'$' => new Handler\BulkResponse(),
'*' => new Handler\MultiBulkResponse(),
);
} | php | {
"resource": ""
} |
q13943 | MultiBulkTuple.checkPreconditions | train | protected function checkPreconditions(MultiBulk $iterator)
{
if ($iterator->getPosition() !== 0) {
throw new \InvalidArgumentException(
'Cannot initialize a tuple iterator using an already initiated iterator.'
);
}
if (($size = count($iterator)) % 2 !== 0) {
throw new \UnexpectedValueException('Invalid response size for a tuple iterator.');
}
} | php | {
"resource": ""
} |
q13944 | CursorBasedIterator.getScanOptions | train | protected function getScanOptions()
{
$options = array();
if (strlen($this->match) > 0) {
$options['MATCH'] = $this->match;
}
if ($this->count > 0) {
$options['COUNT'] = $this->count;
}
return $options;
} | php | {
"resource": ""
} |
q13945 | KeyPrefixProcessor.first | train | public static function first(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$arguments[0] = "$prefix{$arguments[0]}";
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13946 | KeyPrefixProcessor.interleaved | train | public static function interleaved(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$length = count($arguments);
for ($i = 0; $i < $length; $i += 2) {
$arguments[$i] = "$prefix{$arguments[$i]}";
}
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13947 | KeyPrefixProcessor.sort | train | public static function sort(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$arguments[0] = "$prefix{$arguments[0]}";
if (($count = count($arguments)) > 1) {
for ($i = 1; $i < $count; ++$i) {
switch (strtoupper($arguments[$i])) {
case 'BY':
case 'STORE':
$arguments[$i] = "$prefix{$arguments[++$i]}";
break;
case 'GET':
$value = $arguments[++$i];
if ($value !== '#') {
$arguments[$i] = "$prefix$value";
}
break;
case 'LIMIT';
$i += 2;
break;
}
}
}
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13948 | KeyPrefixProcessor.evalKeys | train | public static function evalKeys(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
for ($i = 2; $i < $arguments[1] + 2; ++$i) {
$arguments[$i] = "$prefix{$arguments[$i]}";
}
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13949 | KeyPrefixProcessor.migrate | train | public static function migrate(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$arguments[2] = "$prefix{$arguments[2]}";
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13950 | KeyPrefixProcessor.georadius | train | public static function georadius(CommandInterface $command, $prefix)
{
if ($arguments = $command->getArguments()) {
$arguments[0] = "$prefix{$arguments[0]}";
$startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4;
if (($count = count($arguments)) > $startIndex) {
for ($i = $startIndex; $i < $count; ++$i) {
switch (strtoupper($arguments[$i])) {
case 'STORE':
case 'STOREDIST':
$arguments[$i] = "$prefix{$arguments[++$i]}";
break;
}
}
}
$command->setRawArguments($arguments);
}
} | php | {
"resource": ""
} |
q13951 | HashRing.add | train | public function add($node, $weight = null)
{
// In case of collisions in the hashes of the nodes, the node added
// last wins, thus the order in which nodes are added is significant.
$this->nodes[] = array(
'object' => $node,
'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT,
);
$this->reset();
} | php | {
"resource": ""
} |
q13952 | HashRing.initialize | train | private function initialize()
{
if ($this->isInitialized()) {
return;
}
if (!$this->nodes) {
throw new EmptyRingException('Cannot initialize an empty hashring.');
}
$this->ring = array();
$totalWeight = $this->computeTotalWeight();
$nodesCount = count($this->nodes);
foreach ($this->nodes as $node) {
$weightRatio = $node['weight'] / $totalWeight;
$this->addNodeToRing($this->ring, $node, $nodesCount, $this->replicas, $weightRatio);
}
ksort($this->ring, SORT_NUMERIC);
$this->ringKeys = array_keys($this->ring);
$this->ringKeysCount = count($this->ringKeys);
} | php | {
"resource": ""
} |
q13953 | HashRing.addNodeToRing | train | protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio)
{
$nodeObject = $node['object'];
$nodeHash = $this->getNodeHash($nodeObject);
$replicas = (int) round($weightRatio * $totalNodes * $replicas);
for ($i = 0; $i < $replicas; ++$i) {
$key = crc32("$nodeHash:$i");
$ring[$key] = $nodeObject;
}
} | php | {
"resource": ""
} |
q13954 | AbstractConnection.createExceptionMessage | train | private function createExceptionMessage($message)
{
$parameters = $this->parameters;
if ($parameters->scheme === 'unix') {
return "$message [$parameters->scheme:$parameters->path]";
}
if (filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
return "$message [$parameters->scheme://[$parameters->host]:$parameters->port]";
}
return "$message [$parameters->scheme://$parameters->host:$parameters->port]";
} | php | {
"resource": ""
} |
q13955 | AbstractConnection.onConnectionError | train | protected function onConnectionError($message, $code = null)
{
CommunicationException::handle(
new ConnectionException($this, static::createExceptionMessage($message), $code)
);
} | php | {
"resource": ""
} |
q13956 | ServerClient.parseClientList | train | protected function parseClientList($data)
{
$clients = array();
foreach (explode("\n", $data, -1) as $clientData) {
$client = array();
foreach (explode(' ', $clientData) as $kv) {
@list($k, $v) = explode('=', $kv);
$client[$k] = $v;
}
$clients[] = $client;
}
return $clients;
} | php | {
"resource": ""
} |
q13957 | Pipeline.exception | train | protected function exception(ConnectionInterface $connection, ErrorResponseInterface $response)
{
$connection->disconnect();
$message = $response->getMessage();
throw new ServerException($message);
} | php | {
"resource": ""
} |
q13958 | Pipeline.getConnection | train | protected function getConnection()
{
$connection = $this->getClient()->getConnection();
if ($connection instanceof ReplicationInterface) {
$connection->switchTo('master');
}
return $connection;
} | php | {
"resource": ""
} |
q13959 | Pipeline.executePipeline | train | protected function executePipeline(ConnectionInterface $connection, \SplQueue $commands)
{
foreach ($commands as $command) {
$connection->writeRequest($command);
}
$responses = array();
$exceptions = $this->throwServerExceptions();
while (!$commands->isEmpty()) {
$command = $commands->dequeue();
$response = $connection->readResponse($command);
if (!$response instanceof ResponseInterface) {
$responses[] = $command->parseResponse($response);
} elseif ($response instanceof ErrorResponseInterface && $exceptions) {
$this->exception($connection, $response);
} else {
$responses[] = $response;
}
}
return $responses;
} | php | {
"resource": ""
} |
q13960 | Pipeline.flushPipeline | train | public function flushPipeline($send = true)
{
if ($send && !$this->pipeline->isEmpty()) {
$responses = $this->executePipeline($this->getConnection(), $this->pipeline);
$this->responses = array_merge($this->responses, $responses);
} else {
$this->pipeline = new \SplQueue();
}
return $this;
} | php | {
"resource": ""
} |
q13961 | Pipeline.execute | train | public function execute($callable = null)
{
if ($callable && !is_callable($callable)) {
throw new \InvalidArgumentException('The argument must be a callable object.');
}
$exception = null;
$this->setRunning(true);
try {
if ($callable) {
call_user_func($callable, $this);
}
$this->flushPipeline();
} catch (\Exception $exception) {
// NOOP
}
$this->setRunning(false);
if ($exception) {
throw $exception;
}
return $this->responses;
} | php | {
"resource": ""
} |
q13962 | Handler.register | train | public function register()
{
if (PHP_VERSION_ID >= 50400) {
session_set_save_handler($this, true);
} else {
session_set_save_handler(
array($this, 'open'),
array($this, 'close'),
array($this, 'read'),
array($this, 'write'),
array($this, 'destroy'),
array($this, 'gc')
);
}
} | php | {
"resource": ""
} |
q13963 | Factory.define | train | public static function define($alias, $class)
{
$reflection = new \ReflectionClass($class);
if (!$reflection->isSubclassOf('Predis\Profile\ProfileInterface')) {
throw new \InvalidArgumentException("The class '$class' is not a valid profile class.");
}
self::$profiles[$alias] = $class;
} | php | {
"resource": ""
} |
q13964 | Factory.get | train | public static function get($version)
{
if (!isset(self::$profiles[$version])) {
throw new ClientException("Unknown server profile: '$version'.");
}
$profile = self::$profiles[$version];
return new $profile();
} | php | {
"resource": ""
} |
q13965 | Status.get | train | public static function get($payload)
{
switch ($payload) {
case 'OK':
case 'QUEUED':
if (isset(self::$$payload)) {
return self::$$payload;
}
return self::$$payload = new self($payload);
default:
return new self($payload);
}
} | php | {
"resource": ""
} |
q13966 | Factory.checkInitializer | train | protected function checkInitializer($initializer)
{
if (is_callable($initializer)) {
return $initializer;
}
$class = new \ReflectionClass($initializer);
if (!$class->isSubclassOf('Predis\Connection\NodeConnectionInterface')) {
throw new \InvalidArgumentException(
'A connection initializer must be a valid connection class or a callable object.'
);
}
return $initializer;
} | php | {
"resource": ""
} |
q13967 | Factory.createParameters | train | protected function createParameters($parameters)
{
if (is_string($parameters)) {
$parameters = Parameters::parse($parameters);
} else {
$parameters = $parameters ?: array();
}
if ($this->defaults) {
$parameters += $this->defaults;
}
return new Parameters($parameters);
} | php | {
"resource": ""
} |
q13968 | Factory.prepareConnection | train | protected function prepareConnection(NodeConnectionInterface $connection)
{
$parameters = $connection->getParameters();
if (isset($parameters->password)) {
$connection->addConnectCommand(
new RawCommand(array('AUTH', $parameters->password))
);
}
if (isset($parameters->database)) {
$connection->addConnectCommand(
new RawCommand(array('SELECT', $parameters->database))
);
}
} | php | {
"resource": ""
} |
q13969 | StreamConnection.assertSslSupport | train | protected function assertSslSupport(ParametersInterface $parameters)
{
if (
filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN) &&
version_compare(PHP_VERSION, '7.0.0beta') < 0
) {
throw new \InvalidArgumentException('Persistent SSL connections require PHP >= 7.0.0.');
}
} | php | {
"resource": ""
} |
q13970 | StreamConnection.createStreamSocket | train | protected function createStreamSocket(ParametersInterface $parameters, $address, $flags)
{
$timeout = (isset($parameters->timeout) ? (float) $parameters->timeout : 5.0);
if (!$resource = @stream_socket_client($address, $errno, $errstr, $timeout, $flags)) {
$this->onConnectionError(trim($errstr), $errno);
}
if (isset($parameters->read_write_timeout)) {
$rwtimeout = (float) $parameters->read_write_timeout;
$rwtimeout = $rwtimeout > 0 ? $rwtimeout : -1;
$timeoutSeconds = floor($rwtimeout);
$timeoutUSeconds = ($rwtimeout - $timeoutSeconds) * 1000000;
stream_set_timeout($resource, $timeoutSeconds, $timeoutUSeconds);
}
if (isset($parameters->tcp_nodelay) && function_exists('socket_import_stream')) {
$socket = socket_import_stream($resource);
socket_set_option($socket, SOL_TCP, TCP_NODELAY, (int) $parameters->tcp_nodelay);
}
return $resource;
} | php | {
"resource": ""
} |
q13971 | StreamConnection.tcpStreamInitializer | train | protected function tcpStreamInitializer(ParametersInterface $parameters)
{
if (!filter_var($parameters->host, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
$address = "tcp://$parameters->host:$parameters->port";
} else {
$address = "tcp://[$parameters->host]:$parameters->port";
}
$flags = STREAM_CLIENT_CONNECT;
if (isset($parameters->async_connect) && $parameters->async_connect) {
$flags |= STREAM_CLIENT_ASYNC_CONNECT;
}
if (isset($parameters->persistent)) {
if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$flags |= STREAM_CLIENT_PERSISTENT;
if ($persistent === null) {
$address = "{$address}/{$parameters->persistent}";
}
}
}
$resource = $this->createStreamSocket($parameters, $address, $flags);
return $resource;
} | php | {
"resource": ""
} |
q13972 | StreamConnection.unixStreamInitializer | train | protected function unixStreamInitializer(ParametersInterface $parameters)
{
if (!isset($parameters->path)) {
throw new \InvalidArgumentException('Missing UNIX domain socket path.');
}
$flags = STREAM_CLIENT_CONNECT;
if (isset($parameters->persistent)) {
if (false !== $persistent = filter_var($parameters->persistent, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)) {
$flags |= STREAM_CLIENT_PERSISTENT;
if ($persistent === null) {
throw new \InvalidArgumentException(
'Persistent connection IDs are not supported when using UNIX domain sockets.'
);
}
}
}
$resource = $this->createStreamSocket($parameters, "unix://{$parameters->path}", $flags);
return $resource;
} | php | {
"resource": ""
} |
q13973 | StreamConnection.tlsStreamInitializer | train | protected function tlsStreamInitializer(ParametersInterface $parameters)
{
$resource = $this->tcpStreamInitializer($parameters);
$metadata = stream_get_meta_data($resource);
// Detect if crypto mode is already enabled for this stream (PHP >= 7.0.0).
if (isset($metadata['crypto'])) {
return $resource;
}
if (is_array($parameters->ssl)) {
$options = $parameters->ssl;
} else {
$options = array();
}
if (!isset($options['crypto_type'])) {
$options['crypto_type'] = STREAM_CRYPTO_METHOD_TLS_CLIENT;
}
if (!stream_context_set_option($resource, array('ssl' => $options))) {
$this->onConnectionError('Error while setting SSL context options');
}
if (!stream_socket_enable_crypto($resource, true, $options['crypto_type'])) {
$this->onConnectionError('Error while switching to encrypted communication');
}
return $resource;
} | php | {
"resource": ""
} |
q13974 | StreamConnection.write | train | protected function write($buffer)
{
$socket = $this->getResource();
while (($length = strlen($buffer)) > 0) {
$written = @fwrite($socket, $buffer);
if ($length === $written) {
return;
}
if ($written === false || $written === 0) {
$this->onConnectionError('Error while writing bytes to the server.');
}
$buffer = substr($buffer, $written);
}
} | php | {
"resource": ""
} |
q13975 | RedisCluster.removeById | train | public function removeById($connectionID)
{
if (isset($this->pool[$connectionID])) {
unset(
$this->pool[$connectionID],
$this->slotsMap
);
return true;
}
return false;
} | php | {
"resource": ""
} |
q13976 | RedisCluster.buildSlotsMap | train | public function buildSlotsMap()
{
$this->slotsMap = array();
foreach ($this->pool as $connectionID => $connection) {
$parameters = $connection->getParameters();
if (!isset($parameters->slots)) {
continue;
}
foreach (explode(',', $parameters->slots) as $slotRange) {
$slots = explode('-', $slotRange, 2);
if (!isset($slots[1])) {
$slots[1] = $slots[0];
}
$this->setSlots($slots[0], $slots[1], $connectionID);
}
}
return $this->slotsMap;
} | php | {
"resource": ""
} |
q13977 | RedisCluster.retryCommandOnFailure | train | private function retryCommandOnFailure(CommandInterface $command, $method)
{
$failure = false;
RETRY_COMMAND: {
try {
$response = $this->getConnection($command)->$method($command);
} catch (ConnectionException $exception) {
$connection = $exception->getConnection();
$connection->disconnect();
$this->remove($connection);
if ($failure) {
throw $exception;
} elseif ($this->useClusterSlots) {
$this->askSlotsMap();
}
$failure = true;
goto RETRY_COMMAND;
}
}
return $response;
} | php | {
"resource": ""
} |
q13978 | ClusterStrategy.setCommandHandler | train | public function setCommandHandler($commandID, $callback = null)
{
$commandID = strtoupper($commandID);
if (!isset($callback)) {
unset($this->commands[$commandID]);
return;
}
if (!is_callable($callback)) {
throw new \InvalidArgumentException(
'The argument must be a callable object or NULL.'
);
}
$this->commands[$commandID] = $callback;
} | php | {
"resource": ""
} |
q13979 | ClusterStrategy.checkSameSlotForKeys | train | protected function checkSameSlotForKeys(array $keys)
{
if (!$count = count($keys)) {
return false;
}
$currentSlot = $this->getSlotByKey($keys[0]);
for ($i = 1; $i < $count; ++$i) {
$nextSlot = $this->getSlotByKey($keys[$i]);
if ($currentSlot !== $nextSlot) {
return false;
}
$currentSlot = $nextSlot;
}
return true;
} | php | {
"resource": ""
} |
q13980 | SentinelReplication.createSentinelConnection | train | protected function createSentinelConnection($parameters)
{
if ($parameters instanceof NodeConnectionInterface) {
return $parameters;
}
if (is_string($parameters)) {
$parameters = Parameters::parse($parameters);
}
if (is_array($parameters)) {
// We explicitly set "database" and "password" to null,
// so that no AUTH and SELECT command is send to the sentinels.
$parameters['database'] = null;
$parameters['password'] = null;
if (!isset($parameters['timeout'])) {
$parameters['timeout'] = $this->sentinelTimeout;
}
}
$connection = $this->connectionFactory->create($parameters);
return $connection;
} | php | {
"resource": ""
} |
q13981 | SentinelReplication.getSentinelConnection | train | public function getSentinelConnection()
{
if (!$this->sentinelConnection) {
if (!$this->sentinels) {
throw new \Predis\ClientException('No sentinel server available for autodiscovery.');
}
$sentinel = array_shift($this->sentinels);
$this->sentinelConnection = $this->createSentinelConnection($sentinel);
}
return $this->sentinelConnection;
} | php | {
"resource": ""
} |
q13982 | SentinelReplication.handleSentinelErrorResponse | train | private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error)
{
if ($error->getErrorType() === 'IDONTKNOW') {
throw new ConnectionException($sentinel, $error->getMessage());
} else {
throw new ServerException($error->getMessage());
}
} | php | {
"resource": ""
} |
q13983 | SentinelReplication.querySentinelForMaster | train | protected function querySentinelForMaster(NodeConnectionInterface $sentinel, $service)
{
$payload = $sentinel->executeCommand(
RawCommand::create('SENTINEL', 'get-master-addr-by-name', $service)
);
if ($payload === null) {
throw new ServerException('ERR No such master with that name');
}
if ($payload instanceof ErrorResponseInterface) {
$this->handleSentinelErrorResponse($sentinel, $payload);
}
return array(
'host' => $payload[0],
'port' => $payload[1],
'alias' => 'master',
);
} | php | {
"resource": ""
} |
q13984 | SentinelReplication.querySentinelForSlaves | train | protected function querySentinelForSlaves(NodeConnectionInterface $sentinel, $service)
{
$slaves = array();
$payload = $sentinel->executeCommand(
RawCommand::create('SENTINEL', 'slaves', $service)
);
if ($payload instanceof ErrorResponseInterface) {
$this->handleSentinelErrorResponse($sentinel, $payload);
}
foreach ($payload as $slave) {
$flags = explode(',', $slave[9]);
if (array_intersect($flags, array('s_down', 'o_down', 'disconnected'))) {
continue;
}
$slaves[] = array(
'host' => $slave[3],
'port' => $slave[5],
'alias' => "slave-$slave[1]",
);
}
return $slaves;
} | php | {
"resource": ""
} |
q13985 | SentinelReplication.getConnectionInternal | train | private function getConnectionInternal(CommandInterface $command)
{
if (!$this->current) {
if ($this->strategy->isReadOperation($command) && $slave = $this->pickSlave()) {
$this->current = $slave;
} else {
$this->current = $this->getMaster();
}
return $this->current;
}
if ($this->current === $this->master) {
return $this->current;
}
if (!$this->strategy->isReadOperation($command)) {
$this->current = $this->getMaster();
}
return $this->current;
} | php | {
"resource": ""
} |
q13986 | SentinelReplication.assertConnectionRole | train | protected function assertConnectionRole(NodeConnectionInterface $connection, $role)
{
$role = strtolower($role);
$actualRole = $connection->executeCommand(RawCommand::create('ROLE'));
if ($role !== $actualRole[0]) {
throw new RoleException($connection, "Expected $role but got $actualRole[0] [$connection]");
}
} | php | {
"resource": ""
} |
q13987 | MultiBulk.drop | train | public function drop($disconnect = false)
{
if ($disconnect) {
if ($this->valid()) {
$this->position = $this->size;
$this->connection->disconnect();
}
} else {
while ($this->valid()) {
$this->next();
}
}
} | php | {
"resource": ""
} |
q13988 | ServerSentinel.processMastersOrSlaves | train | protected static function processMastersOrSlaves(array $servers)
{
foreach ($servers as $idx => $node) {
$processed = array();
$count = count($node);
for ($i = 0; $i < $count; ++$i) {
$processed[$node[$i]] = $node[++$i];
}
$servers[$idx] = $processed;
}
return $servers;
} | php | {
"resource": ""
} |
q13989 | Consumer.getValue | train | private function getValue()
{
$database = 0;
$client = null;
$event = $this->client->getConnection()->read();
$callback = function ($matches) use (&$database, &$client) {
if (2 === $count = count($matches)) {
// Redis <= 2.4
$database = (int) $matches[1];
}
if (4 === $count) {
// Redis >= 2.6
$database = (int) $matches[2];
$client = $matches[3];
}
return ' ';
};
$event = preg_replace_callback('/ \(db (\d+)\) | \[(\d+) (.*?)\] /', $callback, $event, 1);
@list($timestamp, $command, $arguments) = explode(' ', $event, 3);
return (object) array(
'timestamp' => (float) $timestamp,
'database' => $database,
'client' => $client,
'command' => substr($command, 1, -1),
'arguments' => $arguments,
);
} | php | {
"resource": ""
} |
q13990 | PubSubPubsub.processNumsub | train | protected static function processNumsub(array $channels)
{
$processed = array();
$count = count($channels);
for ($i = 0; $i < $count; ++$i) {
$processed[$channels[$i]] = $channels[++$i];
}
return $processed;
} | php | {
"resource": ""
} |
q13991 | DispatcherLoop.attachCallback | train | public function attachCallback($channel, $callback)
{
$callbackName = $this->getPrefixKeys().$channel;
$this->assertCallback($callback);
$this->callbacks[$callbackName] = $callback;
$this->pubsub->subscribe($channel);
} | php | {
"resource": ""
} |
q13992 | DispatcherLoop.detachCallback | train | public function detachCallback($channel)
{
$callbackName = $this->getPrefixKeys().$channel;
if (isset($this->callbacks[$callbackName])) {
unset($this->callbacks[$callbackName]);
$this->pubsub->unsubscribe($channel);
}
} | php | {
"resource": ""
} |
q13993 | DispatcherLoop.run | train | public function run()
{
foreach ($this->pubsub as $message) {
$kind = $message->kind;
if ($kind !== Consumer::MESSAGE && $kind !== Consumer::PMESSAGE) {
if (isset($this->subscriptionCallback)) {
$callback = $this->subscriptionCallback;
call_user_func($callback, $message);
}
continue;
}
if (isset($this->callbacks[$message->channel])) {
$callback = $this->callbacks[$message->channel];
call_user_func($callback, $message->payload);
} elseif (isset($this->defaultCallback)) {
$callback = $this->defaultCallback;
call_user_func($callback, $message);
}
}
} | php | {
"resource": ""
} |
q13994 | DispatcherLoop.getPrefixKeys | train | protected function getPrefixKeys()
{
$options = $this->pubsub->getClient()->getOptions();
if (isset($options->prefix)) {
return $options->prefix->getPrefix();
}
return '';
} | php | {
"resource": ""
} |
q13995 | Consumer.genericSubscribeInit | train | private function genericSubscribeInit($subscribeAction)
{
if (isset($this->options[$subscribeAction])) {
$this->$subscribeAction($this->options[$subscribeAction]);
}
} | php | {
"resource": ""
} |
q13996 | CommunicationException.handle | train | public static function handle(CommunicationException $exception)
{
if ($exception->shouldResetConnection()) {
$connection = $exception->getConnection();
if ($connection->isConnected()) {
$connection->disconnect();
}
}
throw $exception;
} | php | {
"resource": ""
} |
q13997 | ProfileOption.setProcessors | train | protected function setProcessors(OptionsInterface $options, ProfileInterface $profile)
{
if (isset($options->prefix) && $profile instanceof RedisProfile) {
// NOTE: directly using __get('prefix') is actually a workaround for
// HHVM 2.3.0. It's correct and respects the options interface, it's
// just ugly. We will remove this hack when HHVM will fix re-entrant
// calls to __get() once and for all.
$profile->setProcessor($options->__get('prefix'));
}
} | php | {
"resource": ""
} |
q13998 | RedisProfile.getCommandClass | train | public function getCommandClass($commandID)
{
if (isset($this->commands[$commandID = strtoupper($commandID)])) {
return $this->commands[$commandID];
}
} | php | {
"resource": ""
} |
q13999 | RedisProfile.defineCommand | train | public function defineCommand($commandID, $class)
{
$reflection = new \ReflectionClass($class);
if (!$reflection->isSubclassOf('Predis\Command\CommandInterface')) {
throw new \InvalidArgumentException("The class '$class' is not a valid command class.");
}
$this->commands[strtoupper($commandID)] = $class;
} | php | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.