repo
stringlengths
6
63
path
stringlengths
5
140
func_name
stringlengths
3
151
original_string
stringlengths
84
13k
language
stringclasses
1 value
code
stringlengths
84
13k
code_tokens
sequence
docstring
stringlengths
3
47.2k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
91
247
partition
stringclasses
1 value
nrk/predis
src/Connection/Aggregate/MasterSlaveReplication.php
MasterSlaveReplication.discoverFromMaster
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Discovers the replication configuration by contacting the master node. @param NodeConnectionInterface $connection Connection to the master node. @param FactoryInterface $connectionFactory Connection factory instance.
[ "Discovers", "the", "replication", "configuration", "by", "contacting", "the", "master", "node", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/MasterSlaveReplication.php#L372-L395
train
nrk/predis
src/Connection/Aggregate/MasterSlaveReplication.php
MasterSlaveReplication.discoverFromSlave
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
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); }
[ "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", ")", ";", "}" ]
Discovers the replication configuration by contacting one of the slaves. @param NodeConnectionInterface $connection Connection to one of the slaves. @param FactoryInterface $connectionFactory Connection factory instance.
[ "Discovers", "the", "replication", "configuration", "by", "contacting", "one", "of", "the", "slaves", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/MasterSlaveReplication.php#L403-L421
train
nrk/predis
src/Connection/Aggregate/MasterSlaveReplication.php
MasterSlaveReplication.retryCommandOnFailure
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
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; }
[ "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", ";", "}" ]
Retries the execution of a command upon slave failure. @param CommandInterface $command Command instance. @param string $method Actual method. @return mixed
[ "Retries", "the", "execution", "of", "a", "command", "upon", "slave", "failure", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/MasterSlaveReplication.php#L431-L476
train
nrk/predis
src/PubSub/AbstractConsumer.php
AbstractConsumer.subscribe
public function subscribe($channel /*, ... */) { $this->writeRequest(self::SUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_SUBSCRIBED; }
php
public function subscribe($channel /*, ... */) { $this->writeRequest(self::SUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_SUBSCRIBED; }
[ "public", "function", "subscribe", "(", "$", "channel", "/*, ... */", ")", "{", "$", "this", "->", "writeRequest", "(", "self", "::", "SUBSCRIBE", ",", "func_get_args", "(", ")", ")", ";", "$", "this", "->", "statusFlags", "|=", "self", "::", "STATUS_SUBSCRIBED", ";", "}" ]
Subscribes to the specified channels. @param mixed $channel,... One or more channel names.
[ "Subscribes", "to", "the", "specified", "channels", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/AbstractConsumer.php#L61-L65
train
nrk/predis
src/PubSub/AbstractConsumer.php
AbstractConsumer.psubscribe
public function psubscribe($pattern /* ... */) { $this->writeRequest(self::PSUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_PSUBSCRIBED; }
php
public function psubscribe($pattern /* ... */) { $this->writeRequest(self::PSUBSCRIBE, func_get_args()); $this->statusFlags |= self::STATUS_PSUBSCRIBED; }
[ "public", "function", "psubscribe", "(", "$", "pattern", "/* ... */", ")", "{", "$", "this", "->", "writeRequest", "(", "self", "::", "PSUBSCRIBE", ",", "func_get_args", "(", ")", ")", ";", "$", "this", "->", "statusFlags", "|=", "self", "::", "STATUS_PSUBSCRIBED", ";", "}" ]
Subscribes to the specified channels using a pattern. @param mixed $pattern,... One or more channel name patterns.
[ "Subscribes", "to", "the", "specified", "channels", "using", "a", "pattern", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/AbstractConsumer.php#L82-L86
train
nrk/predis
src/PubSub/AbstractConsumer.php
AbstractConsumer.stop
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
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; }
[ "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", ";", "}" ]
Closes the context by unsubscribing from all the subscribed channels. The context can be forcefully closed by dropping the underlying connection. @param bool $drop Indicates if the context should be closed by dropping the connection. @return bool Returns false when there are no pending messages.
[ "Closes", "the", "context", "by", "unsubscribing", "from", "all", "the", "subscribed", "channels", ".", "The", "context", "can", "be", "forcefully", "closed", "by", "dropping", "the", "underlying", "connection", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/AbstractConsumer.php#L117-L136
train
nrk/predis
src/PubSub/AbstractConsumer.php
AbstractConsumer.valid
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
public function valid() { $isValid = $this->isFlagSet(self::STATUS_VALID); $subscriptionFlags = self::STATUS_SUBSCRIBED | self::STATUS_PSUBSCRIBED; $hasSubscriptions = ($this->statusFlags & $subscriptionFlags) > 0; return $isValid && $hasSubscriptions; }
[ "public", "function", "valid", "(", ")", "{", "$", "isValid", "=", "$", "this", "->", "isFlagSet", "(", "self", "::", "STATUS_VALID", ")", ";", "$", "subscriptionFlags", "=", "self", "::", "STATUS_SUBSCRIBED", "|", "self", "::", "STATUS_PSUBSCRIBED", ";", "$", "hasSubscriptions", "=", "(", "$", "this", "->", "statusFlags", "&", "$", "subscriptionFlags", ")", ">", "0", ";", "return", "$", "isValid", "&&", "$", "hasSubscriptions", ";", "}" ]
Checks if the the consumer is still in a valid state to continue. @return bool
[ "Checks", "if", "the", "the", "consumer", "is", "still", "in", "a", "valid", "state", "to", "continue", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/AbstractConsumer.php#L195-L202
train
nrk/predis
src/Connection/Aggregate/PredisCluster.php
PredisCluster.removeById
public function removeById($connectionID) { if ($connection = $this->getConnectionById($connectionID)) { return $this->remove($connection); } return false; }
php
public function removeById($connectionID) { if ($connection = $this->getConnectionById($connectionID)) { return $this->remove($connection); } return false; }
[ "public", "function", "removeById", "(", "$", "connectionID", ")", "{", "if", "(", "$", "connection", "=", "$", "this", "->", "getConnectionById", "(", "$", "connectionID", ")", ")", "{", "return", "$", "this", "->", "remove", "(", "$", "connection", ")", ";", "}", "return", "false", ";", "}" ]
Removes a connection instance using its alias or index. @param string $connectionID Alias or index of a connection. @return bool Returns true if the connection was in the pool.
[ "Removes", "a", "connection", "instance", "using", "its", "alias", "or", "index", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/PredisCluster.php#L117-L124
train
nrk/predis
src/Connection/Aggregate/PredisCluster.php
PredisCluster.getConnectionByKey
public function getConnectionByKey($key) { $hash = $this->strategy->getSlotByKey($key); $node = $this->distributor->getBySlot($hash); return $node; }
php
public function getConnectionByKey($key) { $hash = $this->strategy->getSlotByKey($key); $node = $this->distributor->getBySlot($hash); return $node; }
[ "public", "function", "getConnectionByKey", "(", "$", "key", ")", "{", "$", "hash", "=", "$", "this", "->", "strategy", "->", "getSlotByKey", "(", "$", "key", ")", ";", "$", "node", "=", "$", "this", "->", "distributor", "->", "getBySlot", "(", "$", "hash", ")", ";", "return", "$", "node", ";", "}" ]
Retrieves a connection instance from the cluster using a key. @param string $key Key string. @return NodeConnectionInterface
[ "Retrieves", "a", "connection", "instance", "from", "the", "cluster", "using", "a", "key", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/PredisCluster.php#L159-L165
train
nrk/predis
src/Connection/Aggregate/PredisCluster.php
PredisCluster.executeCommandOnNodes
public function executeCommandOnNodes(CommandInterface $command) { $responses = array(); foreach ($this->pool as $connection) { $responses[] = $connection->executeCommand($command); } return $responses; }
php
public function executeCommandOnNodes(CommandInterface $command) { $responses = array(); foreach ($this->pool as $connection) { $responses[] = $connection->executeCommand($command); } return $responses; }
[ "public", "function", "executeCommandOnNodes", "(", "CommandInterface", "$", "command", ")", "{", "$", "responses", "=", "array", "(", ")", ";", "foreach", "(", "$", "this", "->", "pool", "as", "$", "connection", ")", "{", "$", "responses", "[", "]", "=", "$", "connection", "->", "executeCommand", "(", "$", "command", ")", ";", "}", "return", "$", "responses", ";", "}" ]
Executes the specified Redis command on all the nodes of a cluster. @param CommandInterface $command A Redis command. @return array
[ "Executes", "the", "specified", "Redis", "command", "on", "all", "the", "nodes", "of", "a", "cluster", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/PredisCluster.php#L225-L234
train
nrk/predis
src/Command/ServerInfo.php
ServerInfo.parseRow
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
protected function parseRow($row) { list($k, $v) = explode(':', $row, 2); if (preg_match('/^db\d+$/', $k)) { $v = $this->parseDatabaseStats($v); } return array($k, $v); }
[ "protected", "function", "parseRow", "(", "$", "row", ")", "{", "list", "(", "$", "k", ",", "$", "v", ")", "=", "explode", "(", "':'", ",", "$", "row", ",", "2", ")", ";", "if", "(", "preg_match", "(", "'/^db\\d+$/'", ",", "$", "k", ")", ")", "{", "$", "v", "=", "$", "this", "->", "parseDatabaseStats", "(", "$", "v", ")", ";", "}", "return", "array", "(", "$", "k", ",", "$", "v", ")", ";", "}" ]
Parses a single row of the response and returns the key-value pair. @param string $row Single row of the response. @return array
[ "Parses", "a", "single", "row", "of", "the", "response", "and", "returns", "the", "key", "-", "value", "pair", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/ServerInfo.php#L56-L65
train
nrk/predis
src/Command/ServerInfo.php
ServerInfo.parseDatabaseStats
protected function parseDatabaseStats($str) { $db = array(); foreach (explode(',', $str) as $dbvar) { list($dbvk, $dbvv) = explode('=', $dbvar); $db[trim($dbvk)] = $dbvv; } return $db; }
php
protected function parseDatabaseStats($str) { $db = array(); foreach (explode(',', $str) as $dbvar) { list($dbvk, $dbvv) = explode('=', $dbvar); $db[trim($dbvk)] = $dbvv; } return $db; }
[ "protected", "function", "parseDatabaseStats", "(", "$", "str", ")", "{", "$", "db", "=", "array", "(", ")", ";", "foreach", "(", "explode", "(", "','", ",", "$", "str", ")", "as", "$", "dbvar", ")", "{", "list", "(", "$", "dbvk", ",", "$", "dbvv", ")", "=", "explode", "(", "'='", ",", "$", "dbvar", ")", ";", "$", "db", "[", "trim", "(", "$", "dbvk", ")", "]", "=", "$", "dbvv", ";", "}", "return", "$", "db", ";", "}" ]
Extracts the statistics of each logical DB from the string buffer. @param string $str Response buffer. @return array
[ "Extracts", "the", "statistics", "of", "each", "logical", "DB", "from", "the", "string", "buffer", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/ServerInfo.php#L74-L84
train
nrk/predis
src/Command/ServerInfo.php
ServerInfo.parseAllocationStats
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
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; }
[ "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", ";", "}" ]
Parses the response and extracts the allocation statistics. @param string $str Response buffer. @return array
[ "Parses", "the", "response", "and", "extracts", "the", "allocation", "statistics", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/ServerInfo.php#L93-L110
train
nrk/predis
src/Command/Command.php
Command.normalizeVariadic
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
public static function normalizeVariadic(array $arguments) { if (count($arguments) === 2 && is_array($arguments[1])) { return array_merge(array($arguments[0]), $arguments[1]); } return $arguments; }
[ "public", "static", "function", "normalizeVariadic", "(", "array", "$", "arguments", ")", "{", "if", "(", "count", "(", "$", "arguments", ")", "===", "2", "&&", "is_array", "(", "$", "arguments", "[", "1", "]", ")", ")", "{", "return", "array_merge", "(", "array", "(", "$", "arguments", "[", "0", "]", ")", ",", "$", "arguments", "[", "1", "]", ")", ";", "}", "return", "$", "arguments", ";", "}" ]
Normalizes the arguments array passed to a variadic Redis command. @param array $arguments Arguments for a command. @return array
[ "Normalizes", "the", "arguments", "array", "passed", "to", "a", "variadic", "Redis", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Command.php#L121-L128
train
nrk/predis
src/Connection/Parameters.php
Parameters.parse
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
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; }
[ "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", ";", "}" ]
Parses an URI string returning an array of connection parameters. When using the "redis" and "rediss" schemes the URI is parsed according to the rules defined by the provisional registration documents approved by IANA. If the URI has a password in its "user-information" part or a database number in the "path" part these values override the values of "password" and "database" if they are present in the "query" part. @link http://www.iana.org/assignments/uri-schemes/prov/redis @link http://www.iana.org/assignments/uri-schemes/prov/rediss @param string $uri URI string. @throws \InvalidArgumentException @return array
[ "Parses", "an", "URI", "string", "returning", "an", "array", "of", "connection", "parameters", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Parameters.php#L84-L129
train
nrk/predis
src/Connection/PhpiredisSocketConnection.php
PhpiredisSocketConnection.emitSocketError
private function emitSocketError() { $errno = socket_last_error(); $errstr = socket_strerror($errno); $this->disconnect(); $this->onConnectionError(trim($errstr), $errno); }
php
private function emitSocketError() { $errno = socket_last_error(); $errstr = socket_strerror($errno); $this->disconnect(); $this->onConnectionError(trim($errstr), $errno); }
[ "private", "function", "emitSocketError", "(", ")", "{", "$", "errno", "=", "socket_last_error", "(", ")", ";", "$", "errstr", "=", "socket_strerror", "(", "$", "errno", ")", ";", "$", "this", "->", "disconnect", "(", ")", ";", "$", "this", "->", "onConnectionError", "(", "trim", "(", "$", "errstr", ")", ",", "$", "errno", ")", ";", "}" ]
Helper method used to throw exceptions on socket errors.
[ "Helper", "method", "used", "to", "throw", "exceptions", "on", "socket", "errors", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/PhpiredisSocketConnection.php#L180-L188
train
nrk/predis
src/Connection/PhpiredisSocketConnection.php
PhpiredisSocketConnection.getAddress
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
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; }
[ "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", ";", "}" ]
Gets the address of an host from connection parameters. @param ParametersInterface $parameters Parameters used to initialize the connection. @return string
[ "Gets", "the", "address", "of", "an", "host", "from", "connection", "parameters", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/PhpiredisSocketConnection.php#L197-L208
train
nrk/predis
src/Connection/PhpiredisSocketConnection.php
PhpiredisSocketConnection.setSocketOptions
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
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(); } } }
[ "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", "(", ")", ";", "}", "}", "}" ]
Sets options on the socket resource from the connection parameters. @param resource $socket Socket resource. @param ParametersInterface $parameters Parameters used to initialize the connection.
[ "Sets", "options", "on", "the", "socket", "resource", "from", "the", "connection", "parameters", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/PhpiredisSocketConnection.php#L248-L278
train
nrk/predis
src/Connection/PhpiredisSocketConnection.php
PhpiredisSocketConnection.connectWithTimeout
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
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(); } }
[ "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", "(", ")", ";", "}", "}" ]
Opens the actual connection to the server with a timeout. @param resource $socket Socket resource. @param string $address IP address (DNS-resolved from hostname) @param ParametersInterface $parameters Parameters used to initialize the connection. @return string
[ "Opens", "the", "actual", "connection", "to", "the", "server", "with", "a", "timeout", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/PhpiredisSocketConnection.php#L289-L323
train
nrk/predis
src/Connection/WebdisConnection.php
WebdisConnection.createCurl
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
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; }
[ "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", ";", "}" ]
Initializes cURL. @return resource
[ "Initializes", "cURL", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/WebdisConnection.php#L117-L142
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.assertClient
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
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.' ); } }
[ "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.'", ")", ";", "}", "}" ]
Checks if the passed client instance satisfies the required conditions needed to initialize the transaction object. @param ClientInterface $client Client instance used by the transaction object. @throws NotSupportedException
[ "Checks", "if", "the", "passed", "client", "instance", "satisfies", "the", "required", "conditions", "needed", "to", "initialize", "the", "transaction", "object", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L67-L80
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.configure
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
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']; } }
[ "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'", "]", ";", "}", "}" ]
Configures the transaction using the provided options. @param ClientInterface $client Underlying client instance. @param array $options Array of options for the transaction.
[ "Configures", "the", "transaction", "using", "the", "provided", "options", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L88-L107
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.call
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
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; }
[ "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", ";", "}" ]
Executes a Redis command bypassing the transaction logic. @param string $commandID Command ID. @param array $arguments Arguments for the command. @throws ServerException @return mixed
[ "Executes", "a", "Redis", "command", "bypassing", "the", "transaction", "logic", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L175-L186
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.watch
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
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; }
[ "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", ";", "}" ]
Executes WATCH against one or more keys. @param string|array $keys One or more keys. @throws NotSupportedException @throws ClientException @return mixed
[ "Executes", "WATCH", "against", "one", "or", "more", "keys", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L229-L243
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.multi
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
public function multi() { if ($this->state->check(MultiExecState::INITIALIZED | MultiExecState::CAS)) { $this->state->unflag(MultiExecState::CAS); $this->call('MULTI'); } else { $this->initialize(); } return $this; }
[ "public", "function", "multi", "(", ")", "{", "if", "(", "$", "this", "->", "state", "->", "check", "(", "MultiExecState", "::", "INITIALIZED", "|", "MultiExecState", "::", "CAS", ")", ")", "{", "$", "this", "->", "state", "->", "unflag", "(", "MultiExecState", "::", "CAS", ")", ";", "$", "this", "->", "call", "(", "'MULTI'", ")", ";", "}", "else", "{", "$", "this", "->", "initialize", "(", ")", ";", "}", "return", "$", "this", ";", "}" ]
Finalizes the transaction by executing MULTI on the server. @return MultiExec
[ "Finalizes", "the", "transaction", "by", "executing", "MULTI", "on", "the", "server", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L250-L260
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.discard
public function discard() { if ($this->state->isInitialized()) { $this->call($this->state->isCAS() ? 'UNWATCH' : 'DISCARD'); $this->reset(); $this->state->flag(MultiExecState::DISCARDED); } return $this; }
php
public function discard() { if ($this->state->isInitialized()) { $this->call($this->state->isCAS() ? 'UNWATCH' : 'DISCARD'); $this->reset(); $this->state->flag(MultiExecState::DISCARDED); } return $this; }
[ "public", "function", "discard", "(", ")", "{", "if", "(", "$", "this", "->", "state", "->", "isInitialized", "(", ")", ")", "{", "$", "this", "->", "call", "(", "$", "this", "->", "state", "->", "isCAS", "(", ")", "?", "'UNWATCH'", ":", "'DISCARD'", ")", ";", "$", "this", "->", "reset", "(", ")", ";", "$", "this", "->", "state", "->", "flag", "(", "MultiExecState", "::", "DISCARDED", ")", ";", "}", "return", "$", "this", ";", "}" ]
Resets the transaction by UNWATCH-ing the keys that are being WATCHed and DISCARD-ing pending commands that have been already sent to the server. @return MultiExec
[ "Resets", "the", "transaction", "by", "UNWATCH", "-", "ing", "the", "keys", "that", "are", "being", "WATCHed", "and", "DISCARD", "-", "ing", "pending", "commands", "that", "have", "been", "already", "sent", "to", "the", "server", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L289-L299
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.checkBeforeExecution
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
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.' ); } }
[ "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.'", ")", ";", "}", "}" ]
Checks the state of the transaction before execution. @param mixed $callable Callback for execution. @throws \InvalidArgumentException @throws ClientException
[ "Checks", "the", "state", "of", "the", "transaction", "before", "execution", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L319-L346
train
nrk/predis
src/Transaction/MultiExec.php
MultiExec.executeTransactionBlock
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
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; } }
[ "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", ";", "}", "}" ]
Passes the current transaction object to a callable block for execution. @param mixed $callable Callback. @throws CommunicationException @throws ServerException
[ "Passes", "the", "current", "transaction", "object", "to", "a", "callable", "block", "for", "execution", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Transaction/MultiExec.php#L425-L445
train
nrk/predis
src/Protocol/Text/ResponseReader.php
ResponseReader.getDefaultHandlers
protected function getDefaultHandlers() { return array( '+' => new Handler\StatusResponse(), '-' => new Handler\ErrorResponse(), ':' => new Handler\IntegerResponse(), '$' => new Handler\BulkResponse(), '*' => new Handler\MultiBulkResponse(), ); }
php
protected function getDefaultHandlers() { return array( '+' => new Handler\StatusResponse(), '-' => new Handler\ErrorResponse(), ':' => new Handler\IntegerResponse(), '$' => new Handler\BulkResponse(), '*' => new Handler\MultiBulkResponse(), ); }
[ "protected", "function", "getDefaultHandlers", "(", ")", "{", "return", "array", "(", "'+'", "=>", "new", "Handler", "\\", "StatusResponse", "(", ")", ",", "'-'", "=>", "new", "Handler", "\\", "ErrorResponse", "(", ")", ",", "':'", "=>", "new", "Handler", "\\", "IntegerResponse", "(", ")", ",", "'$'", "=>", "new", "Handler", "\\", "BulkResponse", "(", ")", ",", "'*'", "=>", "new", "Handler", "\\", "MultiBulkResponse", "(", ")", ",", ")", ";", "}" ]
Returns the default handlers for the supported type of responses. @return array
[ "Returns", "the", "default", "handlers", "for", "the", "supported", "type", "of", "responses", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Protocol/Text/ResponseReader.php#L43-L52
train
nrk/predis
src/Response/Iterator/MultiBulkTuple.php
MultiBulkTuple.checkPreconditions
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
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.'); } }
[ "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.'", ")", ";", "}", "}" ]
Checks for valid preconditions. @param MultiBulk $iterator Inner multibulk response iterator. @throws \InvalidArgumentException @throws \UnexpectedValueException
[ "Checks", "for", "valid", "preconditions", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Response/Iterator/MultiBulkTuple.php#L48-L59
train
nrk/predis
src/Collection/Iterator/CursorBasedIterator.php
CursorBasedIterator.getScanOptions
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
protected function getScanOptions() { $options = array(); if (strlen($this->match) > 0) { $options['MATCH'] = $this->match; } if ($this->count > 0) { $options['COUNT'] = $this->count; } return $options; }
[ "protected", "function", "getScanOptions", "(", ")", "{", "$", "options", "=", "array", "(", ")", ";", "if", "(", "strlen", "(", "$", "this", "->", "match", ")", ">", "0", ")", "{", "$", "options", "[", "'MATCH'", "]", "=", "$", "this", "->", "match", ";", "}", "if", "(", "$", "this", "->", "count", ">", "0", ")", "{", "$", "options", "[", "'COUNT'", "]", "=", "$", "this", "->", "count", ";", "}", "return", "$", "options", ";", "}" ]
Returns an array of options for the `SCAN` command. @return array
[ "Returns", "an", "array", "of", "options", "for", "the", "SCAN", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Collection/Iterator/CursorBasedIterator.php#L91-L104
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.first
public static function first(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $command->setRawArguments($arguments); } }
php
public static function first(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[0] = "$prefix{$arguments[0]}"; $command->setRawArguments($arguments); } }
[ "public", "static", "function", "first", "(", "CommandInterface", "$", "command", ",", "$", "prefix", ")", "{", "if", "(", "$", "arguments", "=", "$", "command", "->", "getArguments", "(", ")", ")", "{", "$", "arguments", "[", "0", "]", "=", "\"$prefix{$arguments[0]}\"", ";", "$", "command", "->", "setRawArguments", "(", "$", "arguments", ")", ";", "}", "}" ]
Applies the specified prefix only the first argument. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "only", "the", "first", "argument", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L253-L259
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.interleaved
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
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); } }
[ "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", ")", ";", "}", "}" ]
Applies the specified prefix only to even arguments in the list. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "only", "to", "even", "arguments", "in", "the", "list", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L284-L295
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.sort
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
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); } }
[ "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", ")", ";", "}", "}" ]
Applies the specified prefix to the keys of a SORT command. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "to", "the", "keys", "of", "a", "SORT", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L341-L370
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.evalKeys
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
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); } }
[ "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", ")", ";", "}", "}" ]
Applies the specified prefix to the keys of an EVAL-based command. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "to", "the", "keys", "of", "an", "EVAL", "-", "based", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L378-L387
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.migrate
public static function migrate(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[2] = "$prefix{$arguments[2]}"; $command->setRawArguments($arguments); } }
php
public static function migrate(CommandInterface $command, $prefix) { if ($arguments = $command->getArguments()) { $arguments[2] = "$prefix{$arguments[2]}"; $command->setRawArguments($arguments); } }
[ "public", "static", "function", "migrate", "(", "CommandInterface", "$", "command", ",", "$", "prefix", ")", "{", "if", "(", "$", "arguments", "=", "$", "command", "->", "getArguments", "(", ")", ")", "{", "$", "arguments", "[", "2", "]", "=", "\"$prefix{$arguments[2]}\"", ";", "$", "command", "->", "setRawArguments", "(", "$", "arguments", ")", ";", "}", "}" ]
Applies the specified prefix to the key of a MIGRATE command. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "to", "the", "key", "of", "a", "MIGRATE", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L415-L421
train
nrk/predis
src/Command/Processor/KeyPrefixProcessor.php
KeyPrefixProcessor.georadius
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
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); } }
[ "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", ")", ";", "}", "}" ]
Applies the specified prefix to the key of a GEORADIUS command. @param CommandInterface $command Command instance. @param string $prefix Prefix string.
[ "Applies", "the", "specified", "prefix", "to", "the", "key", "of", "a", "GEORADIUS", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/Processor/KeyPrefixProcessor.php#L429-L449
train
nrk/predis
src/Cluster/Distributor/HashRing.php
HashRing.add
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
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(); }
[ "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", "(", ")", ";", "}" ]
Adds a node to the ring with an optional weight. @param mixed $node Node object. @param int $weight Weight for the node.
[ "Adds", "a", "node", "to", "the", "ring", "with", "an", "optional", "weight", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Cluster/Distributor/HashRing.php#L52-L62
train
nrk/predis
src/Cluster/Distributor/HashRing.php
HashRing.initialize
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
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); }
[ "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", ")", ";", "}" ]
Initializes the distributor.
[ "Initializes", "the", "distributor", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Cluster/Distributor/HashRing.php#L124-L146
train
nrk/predis
src/Cluster/Distributor/HashRing.php
HashRing.addNodeToRing
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
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; } }
[ "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", ";", "}", "}" ]
Implements the logic needed to add a node to the hashring. @param array $ring Source hashring. @param mixed $node Node object to be added. @param int $totalNodes Total number of nodes. @param int $replicas Number of replicas in the ring. @param float $weightRatio Weight ratio for the node.
[ "Implements", "the", "logic", "needed", "to", "add", "a", "node", "to", "the", "hashring", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Cluster/Distributor/HashRing.php#L157-L167
train
nrk/predis
src/Connection/AbstractConnection.php
AbstractConnection.createExceptionMessage
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
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]"; }
[ "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]\"", ";", "}" ]
Helper method that returns an exception message augmented with useful details from the connection parameters. @param string $message Error message. @return string
[ "Helper", "method", "that", "returns", "an", "exception", "message", "augmented", "with", "useful", "details", "from", "the", "connection", "parameters", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/AbstractConnection.php#L131-L144
train
nrk/predis
src/Connection/AbstractConnection.php
AbstractConnection.onConnectionError
protected function onConnectionError($message, $code = null) { CommunicationException::handle( new ConnectionException($this, static::createExceptionMessage($message), $code) ); }
php
protected function onConnectionError($message, $code = null) { CommunicationException::handle( new ConnectionException($this, static::createExceptionMessage($message), $code) ); }
[ "protected", "function", "onConnectionError", "(", "$", "message", ",", "$", "code", "=", "null", ")", "{", "CommunicationException", "::", "handle", "(", "new", "ConnectionException", "(", "$", "this", ",", "static", "::", "createExceptionMessage", "(", "$", "message", ")", ",", "$", "code", ")", ")", ";", "}" ]
Helper method to handle connection errors. @param string $message Error message. @param int $code Error code.
[ "Helper", "method", "to", "handle", "connection", "errors", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/AbstractConnection.php#L152-L157
train
nrk/predis
src/Command/ServerClient.php
ServerClient.parseClientList
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
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; }
[ "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", ";", "}" ]
Parses the response to CLIENT LIST and returns a structured list. @param string $data Response buffer. @return array
[ "Parses", "the", "response", "to", "CLIENT", "LIST", "and", "returns", "a", "structured", "list", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/ServerClient.php#L57-L73
train
nrk/predis
src/Pipeline/Pipeline.php
Pipeline.exception
protected function exception(ConnectionInterface $connection, ErrorResponseInterface $response) { $connection->disconnect(); $message = $response->getMessage(); throw new ServerException($message); }
php
protected function exception(ConnectionInterface $connection, ErrorResponseInterface $response) { $connection->disconnect(); $message = $response->getMessage(); throw new ServerException($message); }
[ "protected", "function", "exception", "(", "ConnectionInterface", "$", "connection", ",", "ErrorResponseInterface", "$", "response", ")", "{", "$", "connection", "->", "disconnect", "(", ")", ";", "$", "message", "=", "$", "response", "->", "getMessage", "(", ")", ";", "throw", "new", "ServerException", "(", "$", "message", ")", ";", "}" ]
Throws an exception on -ERR responses returned by Redis. @param ConnectionInterface $connection Redis connection that returned the error. @param ErrorResponseInterface $response Instance of the error response. @throws ServerException
[ "Throws", "an", "exception", "on", "-", "ERR", "responses", "returned", "by", "Redis", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Pipeline/Pipeline.php#L97-L103
train
nrk/predis
src/Pipeline/Pipeline.php
Pipeline.getConnection
protected function getConnection() { $connection = $this->getClient()->getConnection(); if ($connection instanceof ReplicationInterface) { $connection->switchTo('master'); } return $connection; }
php
protected function getConnection() { $connection = $this->getClient()->getConnection(); if ($connection instanceof ReplicationInterface) { $connection->switchTo('master'); } return $connection; }
[ "protected", "function", "getConnection", "(", ")", "{", "$", "connection", "=", "$", "this", "->", "getClient", "(", ")", "->", "getConnection", "(", ")", ";", "if", "(", "$", "connection", "instanceof", "ReplicationInterface", ")", "{", "$", "connection", "->", "switchTo", "(", "'master'", ")", ";", "}", "return", "$", "connection", ";", "}" ]
Returns the underlying connection to be used by the pipeline. @return ConnectionInterface
[ "Returns", "the", "underlying", "connection", "to", "be", "used", "by", "the", "pipeline", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Pipeline/Pipeline.php#L110-L119
train
nrk/predis
src/Pipeline/Pipeline.php
Pipeline.executePipeline
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
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; }
[ "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", ";", "}" ]
Implements the logic to flush the queued commands and read the responses from the current connection. @param ConnectionInterface $connection Current connection instance. @param \SplQueue $commands Queued commands. @return array
[ "Implements", "the", "logic", "to", "flush", "the", "queued", "commands", "and", "read", "the", "responses", "from", "the", "current", "connection", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Pipeline/Pipeline.php#L130-L153
train
nrk/predis
src/Pipeline/Pipeline.php
Pipeline.flushPipeline
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
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; }
[ "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", ";", "}" ]
Flushes the buffer holding all of the commands queued so far. @param bool $send Specifies if the commands in the buffer should be sent to Redis. @return $this
[ "Flushes", "the", "buffer", "holding", "all", "of", "the", "commands", "queued", "so", "far", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Pipeline/Pipeline.php#L162-L172
train
nrk/predis
src/Pipeline/Pipeline.php
Pipeline.execute
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
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; }
[ "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", ";", "}" ]
Handles the actual execution of the whole pipeline. @param mixed $callable Optional callback for execution. @throws \Exception @throws \InvalidArgumentException @return array
[ "Handles", "the", "actual", "execution", "of", "the", "whole", "pipeline", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Pipeline/Pipeline.php#L200-L226
train
nrk/predis
src/Session/Handler.php
Handler.register
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
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') ); } }
[ "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'", ")", ")", ";", "}", "}" ]
Registers this instance as the current session handler.
[ "Registers", "this", "instance", "as", "the", "current", "session", "handler", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Session/Handler.php#L49-L63
train
nrk/predis
src/Profile/Factory.php
Factory.define
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
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; }
[ "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", ";", "}" ]
Registers a new server profile. @param string $alias Profile version or alias. @param string $class FQN of a class implementing Predis\Profile\ProfileInterface. @throws \InvalidArgumentException
[ "Registers", "a", "new", "server", "profile", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Profile/Factory.php#L71-L80
train
nrk/predis
src/Profile/Factory.php
Factory.get
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
public static function get($version) { if (!isset(self::$profiles[$version])) { throw new ClientException("Unknown server profile: '$version'."); } $profile = self::$profiles[$version]; return new $profile(); }
[ "public", "static", "function", "get", "(", "$", "version", ")", "{", "if", "(", "!", "isset", "(", "self", "::", "$", "profiles", "[", "$", "version", "]", ")", ")", "{", "throw", "new", "ClientException", "(", "\"Unknown server profile: '$version'.\"", ")", ";", "}", "$", "profile", "=", "self", "::", "$", "profiles", "[", "$", "version", "]", ";", "return", "new", "$", "profile", "(", ")", ";", "}" ]
Returns the specified server profile. @param string $version Profile version or alias. @throws ClientException @return ProfileInterface
[ "Returns", "the", "specified", "server", "profile", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Profile/Factory.php#L91-L100
train
nrk/predis
src/Response/Status.php
Status.get
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
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); } }
[ "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", ")", ";", "}", "}" ]
Returns an instance of a status response object. Common status responses such as OK or QUEUED are cached in order to lower the global memory usage especially when using pipelines. @param string $payload Status response payload. @return string
[ "Returns", "an", "instance", "of", "a", "status", "response", "object", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Response/Status.php#L64-L78
train
nrk/predis
src/Connection/Factory.php
Factory.checkInitializer
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
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; }
[ "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", ";", "}" ]
Checks if the provided argument represents a valid connection class implementing Predis\Connection\NodeConnectionInterface. Optionally, callable objects are used for lazy initialization of connection objects. @param mixed $initializer FQN of a connection class or a callable for lazy initialization. @throws \InvalidArgumentException @return mixed
[ "Checks", "if", "the", "provided", "argument", "represents", "a", "valid", "connection", "class", "implementing", "Predis", "\\", "Connection", "\\", "NodeConnectionInterface", ".", "Optionally", "callable", "objects", "are", "used", "for", "lazy", "initialization", "of", "connection", "objects", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Factory.php#L45-L60
train
nrk/predis
src/Connection/Factory.php
Factory.createParameters
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
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); }
[ "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", ")", ";", "}" ]
Creates a connection parameters instance from the supplied argument. @param mixed $parameters Original connection parameters. @return ParametersInterface
[ "Creates", "a", "connection", "parameters", "instance", "from", "the", "supplied", "argument", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Factory.php#L152-L165
train
nrk/predis
src/Connection/Factory.php
Factory.prepareConnection
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
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)) ); } }
[ "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", ")", ")", ")", ";", "}", "}" ]
Prepares a connection instance after its initialization. @param NodeConnectionInterface $connection Connection instance.
[ "Prepares", "a", "connection", "instance", "after", "its", "initialization", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Factory.php#L172-L187
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.assertSslSupport
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
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.'); } }
[ "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.'", ")", ";", "}", "}" ]
Checks needed conditions for SSL-encrypted connections. @param ParametersInterface $parameters Initialization parameters for the connection. @throws \InvalidArgumentException
[ "Checks", "needed", "conditions", "for", "SSL", "-", "encrypted", "connections", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L82-L90
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.createStreamSocket
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
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; }
[ "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", ";", "}" ]
Creates a connected stream socket resource. @param ParametersInterface $parameters Connection parameters. @param string $address Address for stream_socket_client(). @param int $flags Flags for stream_socket_client(). @return resource
[ "Creates", "a", "connected", "stream", "socket", "resource", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L123-L145
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.tcpStreamInitializer
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
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; }
[ "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", ";", "}" ]
Initializes a TCP stream resource. @param ParametersInterface $parameters Initialization parameters for the connection. @return resource
[ "Initializes", "a", "TCP", "stream", "resource", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L154-L181
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.unixStreamInitializer
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
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; }
[ "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", ";", "}" ]
Initializes a UNIX stream resource. @param ParametersInterface $parameters Initialization parameters for the connection. @return resource
[ "Initializes", "a", "UNIX", "stream", "resource", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L190-L213
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.tlsStreamInitializer
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
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; }
[ "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", ";", "}" ]
Initializes a SSL-encrypted TCP stream resource. @param ParametersInterface $parameters Initialization parameters for the connection. @return resource
[ "Initializes", "a", "SSL", "-", "encrypted", "TCP", "stream", "resource", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L222-L251
train
nrk/predis
src/Connection/StreamConnection.php
StreamConnection.write
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
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); } }
[ "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", ")", ";", "}", "}" ]
Performs a write operation over the stream of the buffer containing a command serialized with the Redis wire protocol. @param string $buffer Representation of a command in the Redis wire protocol.
[ "Performs", "a", "write", "operation", "over", "the", "stream", "of", "the", "buffer", "containing", "a", "command", "serialized", "with", "the", "Redis", "wire", "protocol", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/StreamConnection.php#L286-L303
train
nrk/predis
src/Connection/Aggregate/RedisCluster.php
RedisCluster.removeById
public function removeById($connectionID) { if (isset($this->pool[$connectionID])) { unset( $this->pool[$connectionID], $this->slotsMap ); return true; } return false; }
php
public function removeById($connectionID) { if (isset($this->pool[$connectionID])) { unset( $this->pool[$connectionID], $this->slotsMap ); return true; } return false; }
[ "public", "function", "removeById", "(", "$", "connectionID", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "pool", "[", "$", "connectionID", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "pool", "[", "$", "connectionID", "]", ",", "$", "this", "->", "slotsMap", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
Removes a connection instance by using its identifier. @param string $connectionID Connection identifier. @return bool True if the connection was in the pool.
[ "Removes", "a", "connection", "instance", "by", "using", "its", "identifier", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/RedisCluster.php#L152-L164
train
nrk/predis
src/Connection/Aggregate/RedisCluster.php
RedisCluster.buildSlotsMap
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
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; }
[ "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", ";", "}" ]
Generates the current slots map by guessing the cluster configuration out of the connection parameters of the connections in the pool. Generation is based on the same algorithm used by Redis to generate the cluster, so it is most effective when all of the connections supplied on initialization have the "slots" parameter properly set accordingly to the current cluster configuration. @return array
[ "Generates", "the", "current", "slots", "map", "by", "guessing", "the", "cluster", "configuration", "out", "of", "the", "connection", "parameters", "of", "the", "connections", "in", "the", "pool", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/RedisCluster.php#L177-L200
train
nrk/predis
src/Connection/Aggregate/RedisCluster.php
RedisCluster.retryCommandOnFailure
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
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; }
[ "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", ";", "}" ]
Ensures that a command is executed one more time on connection failure. The connection to the node that generated the error is evicted from the pool before trying to fetch an updated slots map from another node. If the new slots map points to an unreachable server the client gives up and throws the exception as the nodes participating in the cluster may still have to agree that something changed in the configuration of the cluster. @param CommandInterface $command Command instance. @param string $method Actual method. @return mixed
[ "Ensures", "that", "a", "command", "is", "executed", "one", "more", "time", "on", "connection", "failure", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/RedisCluster.php#L544-L570
train
nrk/predis
src/Cluster/ClusterStrategy.php
ClusterStrategy.setCommandHandler
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
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; }
[ "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", ";", "}" ]
Sets an handler for the specified command ID. The signature of the callback must have a single parameter of type Predis\Command\CommandInterface. When the callback argument is omitted or NULL, the previously associated handler for the specified command ID is removed. @param string $commandID Command ID. @param mixed $callback A valid callable object, or NULL to unset the handler. @throws \InvalidArgumentException
[ "Sets", "an", "handler", "for", "the", "specified", "command", "ID", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Cluster/ClusterStrategy.php#L203-L220
train
nrk/predis
src/Cluster/ClusterStrategy.php
ClusterStrategy.checkSameSlotForKeys
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
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; }
[ "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", ";", "}" ]
Checks if the specified array of keys will generate the same hash. @param array $keys Array of keys. @return bool
[ "Checks", "if", "the", "specified", "array", "of", "keys", "will", "generate", "the", "same", "hash", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Cluster/ClusterStrategy.php#L430-L449
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.createSentinelConnection
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
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; }
[ "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", ";", "}" ]
Creates a new connection to a sentinel server. @return NodeConnectionInterface
[ "Creates", "a", "new", "connection", "to", "a", "sentinel", "server", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L231-L255
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.getSentinelConnection
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
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; }
[ "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", ";", "}" ]
Returns the current sentinel connection. If there is no active sentinel connection, a new connection is created. @return NodeConnectionInterface
[ "Returns", "the", "current", "sentinel", "connection", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L264-L276
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.handleSentinelErrorResponse
private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error) { if ($error->getErrorType() === 'IDONTKNOW') { throw new ConnectionException($sentinel, $error->getMessage()); } else { throw new ServerException($error->getMessage()); } }
php
private function handleSentinelErrorResponse(NodeConnectionInterface $sentinel, ErrorResponseInterface $error) { if ($error->getErrorType() === 'IDONTKNOW') { throw new ConnectionException($sentinel, $error->getMessage()); } else { throw new ServerException($error->getMessage()); } }
[ "private", "function", "handleSentinelErrorResponse", "(", "NodeConnectionInterface", "$", "sentinel", ",", "ErrorResponseInterface", "$", "error", ")", "{", "if", "(", "$", "error", "->", "getErrorType", "(", ")", "===", "'IDONTKNOW'", ")", "{", "throw", "new", "ConnectionException", "(", "$", "sentinel", ",", "$", "error", "->", "getMessage", "(", ")", ")", ";", "}", "else", "{", "throw", "new", "ServerException", "(", "$", "error", "->", "getMessage", "(", ")", ")", ";", "}", "}" ]
Handles error responses returned by redis-sentinel. @param NodeConnectionInterface $sentinel Connection to a sentinel server. @param ErrorResponseInterface $error Error response.
[ "Handles", "error", "responses", "returned", "by", "redis", "-", "sentinel", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L327-L334
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.querySentinelForMaster
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
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', ); }
[ "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'", ",", ")", ";", "}" ]
Fetches the details for the master server from a sentinel. @param NodeConnectionInterface $sentinel Connection to a sentinel server. @param string $service Name of the service. @return array
[ "Fetches", "the", "details", "for", "the", "master", "server", "from", "a", "sentinel", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L344-L363
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.querySentinelForSlaves
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
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; }
[ "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", ";", "}" ]
Fetches the details for the slave servers from a sentinel. @param NodeConnectionInterface $sentinel Connection to a sentinel server. @param string $service Name of the service. @return array
[ "Fetches", "the", "details", "for", "the", "slave", "servers", "from", "a", "sentinel", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L373-L400
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.getConnectionInternal
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
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; }
[ "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", ";", "}" ]
Returns the connection instance in charge for the given command. @param CommandInterface $command Command instance. @return NodeConnectionInterface
[ "Returns", "the", "connection", "instance", "in", "charge", "for", "the", "given", "command", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L492-L513
train
nrk/predis
src/Connection/Aggregate/SentinelReplication.php
SentinelReplication.assertConnectionRole
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
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]"); } }
[ "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]\"", ")", ";", "}", "}" ]
Asserts that the specified connection matches an expected role. @param NodeConnectionInterface $connection Connection to a redis server. @param string $role Expected role of the server ("master", "slave" or "sentinel"). @throws RoleException
[ "Asserts", "that", "the", "specified", "connection", "matches", "an", "expected", "role", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Connection/Aggregate/SentinelReplication.php#L523-L531
train
nrk/predis
src/Response/Iterator/MultiBulk.php
MultiBulk.drop
public function drop($disconnect = false) { if ($disconnect) { if ($this->valid()) { $this->position = $this->size; $this->connection->disconnect(); } } else { while ($this->valid()) { $this->next(); } } }
php
public function drop($disconnect = false) { if ($disconnect) { if ($this->valid()) { $this->position = $this->size; $this->connection->disconnect(); } } else { while ($this->valid()) { $this->next(); } } }
[ "public", "function", "drop", "(", "$", "disconnect", "=", "false", ")", "{", "if", "(", "$", "disconnect", ")", "{", "if", "(", "$", "this", "->", "valid", "(", ")", ")", "{", "$", "this", "->", "position", "=", "$", "this", "->", "size", ";", "$", "this", "->", "connection", "->", "disconnect", "(", ")", ";", "}", "}", "else", "{", "while", "(", "$", "this", "->", "valid", "(", ")", ")", "{", "$", "this", "->", "next", "(", ")", ";", "}", "}", "}" ]
Drop queued elements that have not been read from the connection either by consuming the rest of the multibulk response or quickly by closing the underlying connection. @param bool $disconnect Consume the iterator or drop the connection.
[ "Drop", "queued", "elements", "that", "have", "not", "been", "read", "from", "the", "connection", "either", "by", "consuming", "the", "rest", "of", "the", "multibulk", "response", "or", "quickly", "by", "closing", "the", "underlying", "connection", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Response/Iterator/MultiBulk.php#L54-L66
train
nrk/predis
src/Command/ServerSentinel.php
ServerSentinel.processMastersOrSlaves
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
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; }
[ "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", ";", "}" ]
Returns a processed response to SENTINEL MASTERS or SENTINEL SLAVES. @param array $servers List of Redis servers. @return array
[ "Returns", "a", "processed", "response", "to", "SENTINEL", "MASTERS", "or", "SENTINEL", "SLAVES", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/ServerSentinel.php#L51-L65
train
nrk/predis
src/Monitor/Consumer.php
Consumer.getValue
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
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, ); }
[ "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", ",", ")", ";", "}" ]
Waits for a new message from the server generated by MONITOR and returns it when available. @return object
[ "Waits", "for", "a", "new", "message", "from", "the", "server", "generated", "by", "MONITOR", "and", "returns", "it", "when", "available", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Monitor/Consumer.php#L141-L172
train
nrk/predis
src/Command/PubSubPubsub.php
PubSubPubsub.processNumsub
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
protected static function processNumsub(array $channels) { $processed = array(); $count = count($channels); for ($i = 0; $i < $count; ++$i) { $processed[$channels[$i]] = $channels[++$i]; } return $processed; }
[ "protected", "static", "function", "processNumsub", "(", "array", "$", "channels", ")", "{", "$", "processed", "=", "array", "(", ")", ";", "$", "count", "=", "count", "(", "$", "channels", ")", ";", "for", "(", "$", "i", "=", "0", ";", "$", "i", "<", "$", "count", ";", "++", "$", "i", ")", "{", "$", "processed", "[", "$", "channels", "[", "$", "i", "]", "]", "=", "$", "channels", "[", "++", "$", "i", "]", ";", "}", "return", "$", "processed", ";", "}" ]
Returns the processed response to PUBSUB NUMSUB. @param array $channels List of channels @return array
[ "Returns", "the", "processed", "response", "to", "PUBSUB", "NUMSUB", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Command/PubSubPubsub.php#L50-L60
train
nrk/predis
src/PubSub/DispatcherLoop.php
DispatcherLoop.attachCallback
public function attachCallback($channel, $callback) { $callbackName = $this->getPrefixKeys().$channel; $this->assertCallback($callback); $this->callbacks[$callbackName] = $callback; $this->pubsub->subscribe($channel); }
php
public function attachCallback($channel, $callback) { $callbackName = $this->getPrefixKeys().$channel; $this->assertCallback($callback); $this->callbacks[$callbackName] = $callback; $this->pubsub->subscribe($channel); }
[ "public", "function", "attachCallback", "(", "$", "channel", ",", "$", "callback", ")", "{", "$", "callbackName", "=", "$", "this", "->", "getPrefixKeys", "(", ")", ".", "$", "channel", ";", "$", "this", "->", "assertCallback", "(", "$", "callback", ")", ";", "$", "this", "->", "callbacks", "[", "$", "callbackName", "]", "=", "$", "callback", ";", "$", "this", "->", "pubsub", "->", "subscribe", "(", "$", "channel", ")", ";", "}" ]
Binds a callback to a channel. @param string $channel Channel name. @param callable $callback A callback.
[ "Binds", "a", "callback", "to", "a", "channel", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/DispatcherLoop.php#L96-L103
train
nrk/predis
src/PubSub/DispatcherLoop.php
DispatcherLoop.detachCallback
public function detachCallback($channel) { $callbackName = $this->getPrefixKeys().$channel; if (isset($this->callbacks[$callbackName])) { unset($this->callbacks[$callbackName]); $this->pubsub->unsubscribe($channel); } }
php
public function detachCallback($channel) { $callbackName = $this->getPrefixKeys().$channel; if (isset($this->callbacks[$callbackName])) { unset($this->callbacks[$callbackName]); $this->pubsub->unsubscribe($channel); } }
[ "public", "function", "detachCallback", "(", "$", "channel", ")", "{", "$", "callbackName", "=", "$", "this", "->", "getPrefixKeys", "(", ")", ".", "$", "channel", ";", "if", "(", "isset", "(", "$", "this", "->", "callbacks", "[", "$", "callbackName", "]", ")", ")", "{", "unset", "(", "$", "this", "->", "callbacks", "[", "$", "callbackName", "]", ")", ";", "$", "this", "->", "pubsub", "->", "unsubscribe", "(", "$", "channel", ")", ";", "}", "}" ]
Stops listening to a channel and removes the associated callback. @param string $channel Redis channel.
[ "Stops", "listening", "to", "a", "channel", "and", "removes", "the", "associated", "callback", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/DispatcherLoop.php#L110-L118
train
nrk/predis
src/PubSub/DispatcherLoop.php
DispatcherLoop.run
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
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); } } }
[ "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", ")", ";", "}", "}", "}" ]
Starts the dispatcher loop.
[ "Starts", "the", "dispatcher", "loop", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/DispatcherLoop.php#L123-L145
train
nrk/predis
src/PubSub/DispatcherLoop.php
DispatcherLoop.getPrefixKeys
protected function getPrefixKeys() { $options = $this->pubsub->getClient()->getOptions(); if (isset($options->prefix)) { return $options->prefix->getPrefix(); } return ''; }
php
protected function getPrefixKeys() { $options = $this->pubsub->getClient()->getOptions(); if (isset($options->prefix)) { return $options->prefix->getPrefix(); } return ''; }
[ "protected", "function", "getPrefixKeys", "(", ")", "{", "$", "options", "=", "$", "this", "->", "pubsub", "->", "getClient", "(", ")", "->", "getOptions", "(", ")", ";", "if", "(", "isset", "(", "$", "options", "->", "prefix", ")", ")", "{", "return", "$", "options", "->", "prefix", "->", "getPrefix", "(", ")", ";", "}", "return", "''", ";", "}" ]
Return the prefix used for keys. @return string
[ "Return", "the", "prefix", "used", "for", "keys", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/DispatcherLoop.php#L160-L169
train
nrk/predis
src/PubSub/Consumer.php
Consumer.genericSubscribeInit
private function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { $this->$subscribeAction($this->options[$subscribeAction]); } }
php
private function genericSubscribeInit($subscribeAction) { if (isset($this->options[$subscribeAction])) { $this->$subscribeAction($this->options[$subscribeAction]); } }
[ "private", "function", "genericSubscribeInit", "(", "$", "subscribeAction", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "options", "[", "$", "subscribeAction", "]", ")", ")", "{", "$", "this", "->", "$", "subscribeAction", "(", "$", "this", "->", "options", "[", "$", "subscribeAction", "]", ")", ";", "}", "}" ]
This method shares the logic to handle both SUBSCRIBE and PSUBSCRIBE. @param string $subscribeAction Type of subscription.
[ "This", "method", "shares", "the", "logic", "to", "handle", "both", "SUBSCRIBE", "and", "PSUBSCRIBE", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/PubSub/Consumer.php#L85-L90
train
nrk/predis
src/CommunicationException.php
CommunicationException.handle
public static function handle(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; }
php
public static function handle(CommunicationException $exception) { if ($exception->shouldResetConnection()) { $connection = $exception->getConnection(); if ($connection->isConnected()) { $connection->disconnect(); } } throw $exception; }
[ "public", "static", "function", "handle", "(", "CommunicationException", "$", "exception", ")", "{", "if", "(", "$", "exception", "->", "shouldResetConnection", "(", ")", ")", "{", "$", "connection", "=", "$", "exception", "->", "getConnection", "(", ")", ";", "if", "(", "$", "connection", "->", "isConnected", "(", ")", ")", "{", "$", "connection", "->", "disconnect", "(", ")", ";", "}", "}", "throw", "$", "exception", ";", "}" ]
Helper method to handle exceptions generated by a connection object. @param CommunicationException $exception Exception. @throws CommunicationException
[ "Helper", "method", "to", "handle", "exceptions", "generated", "by", "a", "connection", "object", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/CommunicationException.php#L68-L79
train
nrk/predis
src/Configuration/ProfileOption.php
ProfileOption.setProcessors
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
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')); } }
[ "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'", ")", ")", ";", "}", "}" ]
Sets the commands processors that need to be applied to the profile. @param OptionsInterface $options Client options. @param ProfileInterface $profile Server profile.
[ "Sets", "the", "commands", "processors", "that", "need", "to", "be", "applied", "to", "the", "profile", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Configuration/ProfileOption.php#L32-L42
train
nrk/predis
src/Profile/RedisProfile.php
RedisProfile.getCommandClass
public function getCommandClass($commandID) { if (isset($this->commands[$commandID = strtoupper($commandID)])) { return $this->commands[$commandID]; } }
php
public function getCommandClass($commandID) { if (isset($this->commands[$commandID = strtoupper($commandID)])) { return $this->commands[$commandID]; } }
[ "public", "function", "getCommandClass", "(", "$", "commandID", ")", "{", "if", "(", "isset", "(", "$", "this", "->", "commands", "[", "$", "commandID", "=", "strtoupper", "(", "$", "commandID", ")", "]", ")", ")", "{", "return", "$", "this", "->", "commands", "[", "$", "commandID", "]", ";", "}", "}" ]
Returns the fully-qualified name of a class representing the specified command ID registered in the current server profile. @param string $commandID Command ID. @return string|null
[ "Returns", "the", "fully", "-", "qualified", "name", "of", "a", "class", "representing", "the", "specified", "command", "ID", "registered", "in", "the", "current", "server", "profile", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Profile/RedisProfile.php#L73-L78
train
nrk/predis
src/Profile/RedisProfile.php
RedisProfile.defineCommand
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
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; }
[ "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", ";", "}" ]
Defines a new command in the server profile. @param string $commandID Command ID. @param string $class Fully-qualified name of a Predis\Command\CommandInterface. @throws \InvalidArgumentException
[ "Defines", "a", "new", "command", "in", "the", "server", "profile", "." ]
111d100ee389d624036b46b35ed0c9ac59c71313
https://github.com/nrk/predis/blob/111d100ee389d624036b46b35ed0c9ac59c71313/src/Profile/RedisProfile.php#L110-L119
train
laravel/telescope
src/ExtractsMailableTags.php
ExtractsMailableTags.registerMailableTagExtractor
protected static function registerMailableTagExtractor() { Mailable::buildViewDataUsing(function ($mailable) { return [ '__telescope' => ExtractTags::from($mailable), '__telescope_mailable' => get_class($mailable), '__telescope_queued' => in_array(ShouldQueue::class, class_implements($mailable)), ]; }); }
php
protected static function registerMailableTagExtractor() { Mailable::buildViewDataUsing(function ($mailable) { return [ '__telescope' => ExtractTags::from($mailable), '__telescope_mailable' => get_class($mailable), '__telescope_queued' => in_array(ShouldQueue::class, class_implements($mailable)), ]; }); }
[ "protected", "static", "function", "registerMailableTagExtractor", "(", ")", "{", "Mailable", "::", "buildViewDataUsing", "(", "function", "(", "$", "mailable", ")", "{", "return", "[", "'__telescope'", "=>", "ExtractTags", "::", "from", "(", "$", "mailable", ")", ",", "'__telescope_mailable'", "=>", "get_class", "(", "$", "mailable", ")", ",", "'__telescope_queued'", "=>", "in_array", "(", "ShouldQueue", "::", "class", ",", "class_implements", "(", "$", "mailable", ")", ")", ",", "]", ";", "}", ")", ";", "}" ]
Register a callback to extract mailable tags. @return void
[ "Register", "a", "callback", "to", "extract", "mailable", "tags", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/ExtractsMailableTags.php#L15-L24
train
laravel/telescope
src/Watchers/QueryWatcher.php
QueryWatcher.recordQuery
public function recordQuery(QueryExecuted $event) { if (! Telescope::isRecording()) { return; } $time = $event->time; $caller = $this->getCallerFromStackTrace(); Telescope::recordQuery(IncomingEntry::make([ 'connection' => $event->connectionName, 'bindings' => $this->formatBindings($event), 'sql' => $event->sql, 'time' => number_format($time, 2), 'slow' => isset($this->options['slow']) && $time >= $this->options['slow'], 'file' => $caller['file'], 'line' => $caller['line'], ])->tags($this->tags($event))); }
php
public function recordQuery(QueryExecuted $event) { if (! Telescope::isRecording()) { return; } $time = $event->time; $caller = $this->getCallerFromStackTrace(); Telescope::recordQuery(IncomingEntry::make([ 'connection' => $event->connectionName, 'bindings' => $this->formatBindings($event), 'sql' => $event->sql, 'time' => number_format($time, 2), 'slow' => isset($this->options['slow']) && $time >= $this->options['slow'], 'file' => $caller['file'], 'line' => $caller['line'], ])->tags($this->tags($event))); }
[ "public", "function", "recordQuery", "(", "QueryExecuted", "$", "event", ")", "{", "if", "(", "!", "Telescope", "::", "isRecording", "(", ")", ")", "{", "return", ";", "}", "$", "time", "=", "$", "event", "->", "time", ";", "$", "caller", "=", "$", "this", "->", "getCallerFromStackTrace", "(", ")", ";", "Telescope", "::", "recordQuery", "(", "IncomingEntry", "::", "make", "(", "[", "'connection'", "=>", "$", "event", "->", "connectionName", ",", "'bindings'", "=>", "$", "this", "->", "formatBindings", "(", "$", "event", ")", ",", "'sql'", "=>", "$", "event", "->", "sql", ",", "'time'", "=>", "number_format", "(", "$", "time", ",", "2", ")", ",", "'slow'", "=>", "isset", "(", "$", "this", "->", "options", "[", "'slow'", "]", ")", "&&", "$", "time", ">=", "$", "this", "->", "options", "[", "'slow'", "]", ",", "'file'", "=>", "$", "caller", "[", "'file'", "]", ",", "'line'", "=>", "$", "caller", "[", "'line'", "]", ",", "]", ")", "->", "tags", "(", "$", "this", "->", "tags", "(", "$", "event", ")", ")", ")", ";", "}" ]
Record a query was executed. @param \Illuminate\Database\Events\QueryExecuted $event @return void
[ "Record", "a", "query", "was", "executed", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Watchers/QueryWatcher.php#L30-L49
train
laravel/telescope
src/Http/Controllers/RecordingController.php
RecordingController.toggle
public function toggle() { if ($this->cache->get('telescope:pause-recording')) { $this->cache->forget('telescope:pause-recording'); } else { $this->cache->put('telescope:pause-recording', true, now()->addDays(30)); } }
php
public function toggle() { if ($this->cache->get('telescope:pause-recording')) { $this->cache->forget('telescope:pause-recording'); } else { $this->cache->put('telescope:pause-recording', true, now()->addDays(30)); } }
[ "public", "function", "toggle", "(", ")", "{", "if", "(", "$", "this", "->", "cache", "->", "get", "(", "'telescope:pause-recording'", ")", ")", "{", "$", "this", "->", "cache", "->", "forget", "(", "'telescope:pause-recording'", ")", ";", "}", "else", "{", "$", "this", "->", "cache", "->", "put", "(", "'telescope:pause-recording'", ",", "true", ",", "now", "(", ")", "->", "addDays", "(", "30", ")", ")", ";", "}", "}" ]
Toggle recording. @return void
[ "Toggle", "recording", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Http/Controllers/RecordingController.php#L33-L40
train
laravel/telescope
src/Watchers/EventWatcher.php
EventWatcher.recordEvent
public function recordEvent($eventName, $payload) { if (! Telescope::isRecording() || $this->shouldIgnore($eventName)) { return; } $formattedPayload = $this->extractPayload($eventName, $payload); Telescope::recordEvent(IncomingEntry::make([ 'name' => $eventName, 'payload' => empty($formattedPayload) ? null : $formattedPayload, 'listeners' => $this->formatListeners($eventName), 'broadcast' => class_exists($eventName) ? in_array(ShouldBroadcast::class, (array) class_implements($eventName)) : false, ])->tags(class_exists($eventName) && isset($payload[0]) ? ExtractTags::from($payload[0]) : [])); }
php
public function recordEvent($eventName, $payload) { if (! Telescope::isRecording() || $this->shouldIgnore($eventName)) { return; } $formattedPayload = $this->extractPayload($eventName, $payload); Telescope::recordEvent(IncomingEntry::make([ 'name' => $eventName, 'payload' => empty($formattedPayload) ? null : $formattedPayload, 'listeners' => $this->formatListeners($eventName), 'broadcast' => class_exists($eventName) ? in_array(ShouldBroadcast::class, (array) class_implements($eventName)) : false, ])->tags(class_exists($eventName) && isset($payload[0]) ? ExtractTags::from($payload[0]) : [])); }
[ "public", "function", "recordEvent", "(", "$", "eventName", ",", "$", "payload", ")", "{", "if", "(", "!", "Telescope", "::", "isRecording", "(", ")", "||", "$", "this", "->", "shouldIgnore", "(", "$", "eventName", ")", ")", "{", "return", ";", "}", "$", "formattedPayload", "=", "$", "this", "->", "extractPayload", "(", "$", "eventName", ",", "$", "payload", ")", ";", "Telescope", "::", "recordEvent", "(", "IncomingEntry", "::", "make", "(", "[", "'name'", "=>", "$", "eventName", ",", "'payload'", "=>", "empty", "(", "$", "formattedPayload", ")", "?", "null", ":", "$", "formattedPayload", ",", "'listeners'", "=>", "$", "this", "->", "formatListeners", "(", "$", "eventName", ")", ",", "'broadcast'", "=>", "class_exists", "(", "$", "eventName", ")", "?", "in_array", "(", "ShouldBroadcast", "::", "class", ",", "(", "array", ")", "class_implements", "(", "$", "eventName", ")", ")", ":", "false", ",", "]", ")", "->", "tags", "(", "class_exists", "(", "$", "eventName", ")", "&&", "isset", "(", "$", "payload", "[", "0", "]", ")", "?", "ExtractTags", "::", "from", "(", "$", "payload", "[", "0", "]", ")", ":", "[", "]", ")", ")", ";", "}" ]
Record an event was fired. @param string $eventName @param array $payload @return void
[ "Record", "an", "event", "was", "fired", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Watchers/EventWatcher.php#L35-L51
train
laravel/telescope
src/Watchers/EventWatcher.php
EventWatcher.extractPayload
protected function extractPayload($eventName, $payload) { if (class_exists($eventName) && isset($payload[0]) && is_object($payload[0])) { return ExtractProperties::from($payload[0]); } return collect($payload)->map(function ($value) { return is_object($value) ? [ 'class' => get_class($value), 'properties' => json_decode(json_encode($value), true), ] : $value; })->toArray(); }
php
protected function extractPayload($eventName, $payload) { if (class_exists($eventName) && isset($payload[0]) && is_object($payload[0])) { return ExtractProperties::from($payload[0]); } return collect($payload)->map(function ($value) { return is_object($value) ? [ 'class' => get_class($value), 'properties' => json_decode(json_encode($value), true), ] : $value; })->toArray(); }
[ "protected", "function", "extractPayload", "(", "$", "eventName", ",", "$", "payload", ")", "{", "if", "(", "class_exists", "(", "$", "eventName", ")", "&&", "isset", "(", "$", "payload", "[", "0", "]", ")", "&&", "is_object", "(", "$", "payload", "[", "0", "]", ")", ")", "{", "return", "ExtractProperties", "::", "from", "(", "$", "payload", "[", "0", "]", ")", ";", "}", "return", "collect", "(", "$", "payload", ")", "->", "map", "(", "function", "(", "$", "value", ")", "{", "return", "is_object", "(", "$", "value", ")", "?", "[", "'class'", "=>", "get_class", "(", "$", "value", ")", ",", "'properties'", "=>", "json_decode", "(", "json_encode", "(", "$", "value", ")", ",", "true", ")", ",", "]", ":", "$", "value", ";", "}", ")", "->", "toArray", "(", ")", ";", "}" ]
Extract the payload and tags from the event. @param string $eventName @param array $payload @return array
[ "Extract", "the", "payload", "and", "tags", "from", "the", "event", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Watchers/EventWatcher.php#L60-L72
train
laravel/telescope
src/Watchers/EventWatcher.php
EventWatcher.formatListeners
protected function formatListeners($eventName) { return collect(app('events')->getListeners($eventName)) ->map(function ($listener) { $listener = (new ReflectionFunction($listener)) ->getStaticVariables()['listener']; if (is_string($listener)) { return Str::contains($listener, '@') ? $listener : $listener.'@handle'; } elseif (is_array($listener)) { return get_class($listener[0]).'@'.$listener[1]; } return $this->formatClosureListener($listener); })->reject(function ($listener) { return Str::contains($listener, 'Laravel\\Telescope'); })->map(function ($listener) { if (Str::contains($listener, '@')) { $queued = in_array(ShouldQueue::class, class_implements(explode('@', $listener)[0])); } return [ 'name' => $listener, 'queued' => $queued ?? false, ]; })->values()->toArray(); }
php
protected function formatListeners($eventName) { return collect(app('events')->getListeners($eventName)) ->map(function ($listener) { $listener = (new ReflectionFunction($listener)) ->getStaticVariables()['listener']; if (is_string($listener)) { return Str::contains($listener, '@') ? $listener : $listener.'@handle'; } elseif (is_array($listener)) { return get_class($listener[0]).'@'.$listener[1]; } return $this->formatClosureListener($listener); })->reject(function ($listener) { return Str::contains($listener, 'Laravel\\Telescope'); })->map(function ($listener) { if (Str::contains($listener, '@')) { $queued = in_array(ShouldQueue::class, class_implements(explode('@', $listener)[0])); } return [ 'name' => $listener, 'queued' => $queued ?? false, ]; })->values()->toArray(); }
[ "protected", "function", "formatListeners", "(", "$", "eventName", ")", "{", "return", "collect", "(", "app", "(", "'events'", ")", "->", "getListeners", "(", "$", "eventName", ")", ")", "->", "map", "(", "function", "(", "$", "listener", ")", "{", "$", "listener", "=", "(", "new", "ReflectionFunction", "(", "$", "listener", ")", ")", "->", "getStaticVariables", "(", ")", "[", "'listener'", "]", ";", "if", "(", "is_string", "(", "$", "listener", ")", ")", "{", "return", "Str", "::", "contains", "(", "$", "listener", ",", "'@'", ")", "?", "$", "listener", ":", "$", "listener", ".", "'@handle'", ";", "}", "elseif", "(", "is_array", "(", "$", "listener", ")", ")", "{", "return", "get_class", "(", "$", "listener", "[", "0", "]", ")", ".", "'@'", ".", "$", "listener", "[", "1", "]", ";", "}", "return", "$", "this", "->", "formatClosureListener", "(", "$", "listener", ")", ";", "}", ")", "->", "reject", "(", "function", "(", "$", "listener", ")", "{", "return", "Str", "::", "contains", "(", "$", "listener", ",", "'Laravel\\\\Telescope'", ")", ";", "}", ")", "->", "map", "(", "function", "(", "$", "listener", ")", "{", "if", "(", "Str", "::", "contains", "(", "$", "listener", ",", "'@'", ")", ")", "{", "$", "queued", "=", "in_array", "(", "ShouldQueue", "::", "class", ",", "class_implements", "(", "explode", "(", "'@'", ",", "$", "listener", ")", "[", "0", "]", ")", ")", ";", "}", "return", "[", "'name'", "=>", "$", "listener", ",", "'queued'", "=>", "$", "queued", "??", "false", ",", "]", ";", "}", ")", "->", "values", "(", ")", "->", "toArray", "(", ")", ";", "}" ]
Format list of event listeners. @param string $eventName @return array
[ "Format", "list", "of", "event", "listeners", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Watchers/EventWatcher.php#L80-L106
train
laravel/telescope
src/Watchers/EventWatcher.php
EventWatcher.formatClosureListener
protected function formatClosureListener(Closure $listener) { $listener = new ReflectionFunction($listener); return sprintf('Closure at %s[%s:%s]', $listener->getFileName(), $listener->getStartLine(), $listener->getEndLine() ); }
php
protected function formatClosureListener(Closure $listener) { $listener = new ReflectionFunction($listener); return sprintf('Closure at %s[%s:%s]', $listener->getFileName(), $listener->getStartLine(), $listener->getEndLine() ); }
[ "protected", "function", "formatClosureListener", "(", "Closure", "$", "listener", ")", "{", "$", "listener", "=", "new", "ReflectionFunction", "(", "$", "listener", ")", ";", "return", "sprintf", "(", "'Closure at %s[%s:%s]'", ",", "$", "listener", "->", "getFileName", "(", ")", ",", "$", "listener", "->", "getStartLine", "(", ")", ",", "$", "listener", "->", "getEndLine", "(", ")", ")", ";", "}" ]
Format a closure-based listener. @param \Closure $listener @return string @throws \ReflectionException
[ "Format", "a", "closure", "-", "based", "listener", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Watchers/EventWatcher.php#L116-L125
train
laravel/telescope
src/Telescope.php
Telescope.start
public static function start($app) { if (! config('telescope.enabled')) { return; } static::registerWatchers($app); static::registerMailableTagExtractor(); if (static::runningApprovedArtisanCommand($app) || static::handlingApprovedRequest($app) ) { static::startRecording(); } }
php
public static function start($app) { if (! config('telescope.enabled')) { return; } static::registerWatchers($app); static::registerMailableTagExtractor(); if (static::runningApprovedArtisanCommand($app) || static::handlingApprovedRequest($app) ) { static::startRecording(); } }
[ "public", "static", "function", "start", "(", "$", "app", ")", "{", "if", "(", "!", "config", "(", "'telescope.enabled'", ")", ")", "{", "return", ";", "}", "static", "::", "registerWatchers", "(", "$", "app", ")", ";", "static", "::", "registerMailableTagExtractor", "(", ")", ";", "if", "(", "static", "::", "runningApprovedArtisanCommand", "(", "$", "app", ")", "||", "static", "::", "handlingApprovedRequest", "(", "$", "app", ")", ")", "{", "static", "::", "startRecording", "(", ")", ";", "}", "}" ]
Register the Telescope watchers and start recording if necessary. @param \Illuminate\Foundation\Application $app @return void
[ "Register", "the", "Telescope", "watchers", "and", "start", "recording", "if", "necessary", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L125-L140
train
laravel/telescope
src/Telescope.php
Telescope.runningApprovedArtisanCommand
protected static function runningApprovedArtisanCommand($app) { return $app->runningInConsole() && ! in_array( $_SERVER['argv'][1] ?? null, array_merge([ // 'migrate', 'migrate:rollback', 'migrate:fresh', // 'migrate:refresh', 'migrate:reset', 'migrate:install', 'package:discover', 'queue:listen', 'queue:work', 'horizon', 'horizon:work', 'horizon:supervisor', ], config('telescope.ignoreCommands', []), config('telescope.ignore_commands', [])) ); }
php
protected static function runningApprovedArtisanCommand($app) { return $app->runningInConsole() && ! in_array( $_SERVER['argv'][1] ?? null, array_merge([ // 'migrate', 'migrate:rollback', 'migrate:fresh', // 'migrate:refresh', 'migrate:reset', 'migrate:install', 'package:discover', 'queue:listen', 'queue:work', 'horizon', 'horizon:work', 'horizon:supervisor', ], config('telescope.ignoreCommands', []), config('telescope.ignore_commands', [])) ); }
[ "protected", "static", "function", "runningApprovedArtisanCommand", "(", "$", "app", ")", "{", "return", "$", "app", "->", "runningInConsole", "(", ")", "&&", "!", "in_array", "(", "$", "_SERVER", "[", "'argv'", "]", "[", "1", "]", "??", "null", ",", "array_merge", "(", "[", "// 'migrate',", "'migrate:rollback'", ",", "'migrate:fresh'", ",", "// 'migrate:refresh',", "'migrate:reset'", ",", "'migrate:install'", ",", "'package:discover'", ",", "'queue:listen'", ",", "'queue:work'", ",", "'horizon'", ",", "'horizon:work'", ",", "'horizon:supervisor'", ",", "]", ",", "config", "(", "'telescope.ignoreCommands'", ",", "[", "]", ")", ",", "config", "(", "'telescope.ignore_commands'", ",", "[", "]", ")", ")", ")", ";", "}" ]
Determine if the application is running an approved command. @param \Illuminate\Foundation\Application $app @return bool
[ "Determine", "if", "the", "application", "is", "running", "an", "approved", "command", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L148-L167
train
laravel/telescope
src/Telescope.php
Telescope.withoutRecording
public static function withoutRecording($callback) { $shouldRecord = static::$shouldRecord; static::$shouldRecord = false; call_user_func($callback); static::$shouldRecord = $shouldRecord; }
php
public static function withoutRecording($callback) { $shouldRecord = static::$shouldRecord; static::$shouldRecord = false; call_user_func($callback); static::$shouldRecord = $shouldRecord; }
[ "public", "static", "function", "withoutRecording", "(", "$", "callback", ")", "{", "$", "shouldRecord", "=", "static", "::", "$", "shouldRecord", ";", "static", "::", "$", "shouldRecord", "=", "false", ";", "call_user_func", "(", "$", "callback", ")", ";", "static", "::", "$", "shouldRecord", "=", "$", "shouldRecord", ";", "}" ]
Execute the given callback without recording Telescope entries. @param callable $callback @return void
[ "Execute", "the", "given", "callback", "without", "recording", "Telescope", "entries", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L216-L225
train
laravel/telescope
src/Telescope.php
Telescope.record
protected static function record(string $type, IncomingEntry $entry) { if (! static::isRecording()) { return; } $entry->type($type)->tags( static::$tagUsing ? call_user_func(static::$tagUsing, $entry) : [] ); try { if (Auth::hasUser()) { $entry->user(Auth::user()); } } catch (Throwable $e) { // Do nothing. } static::withoutRecording(function () use ($entry) { if (collect(static::$filterUsing)->every->__invoke($entry)) { static::$entriesQueue[] = $entry; } if (static::$afterRecordingHook) { call_user_func(static::$afterRecordingHook, new static); } }); }
php
protected static function record(string $type, IncomingEntry $entry) { if (! static::isRecording()) { return; } $entry->type($type)->tags( static::$tagUsing ? call_user_func(static::$tagUsing, $entry) : [] ); try { if (Auth::hasUser()) { $entry->user(Auth::user()); } } catch (Throwable $e) { // Do nothing. } static::withoutRecording(function () use ($entry) { if (collect(static::$filterUsing)->every->__invoke($entry)) { static::$entriesQueue[] = $entry; } if (static::$afterRecordingHook) { call_user_func(static::$afterRecordingHook, new static); } }); }
[ "protected", "static", "function", "record", "(", "string", "$", "type", ",", "IncomingEntry", "$", "entry", ")", "{", "if", "(", "!", "static", "::", "isRecording", "(", ")", ")", "{", "return", ";", "}", "$", "entry", "->", "type", "(", "$", "type", ")", "->", "tags", "(", "static", "::", "$", "tagUsing", "?", "call_user_func", "(", "static", "::", "$", "tagUsing", ",", "$", "entry", ")", ":", "[", "]", ")", ";", "try", "{", "if", "(", "Auth", "::", "hasUser", "(", ")", ")", "{", "$", "entry", "->", "user", "(", "Auth", "::", "user", "(", ")", ")", ";", "}", "}", "catch", "(", "Throwable", "$", "e", ")", "{", "// Do nothing.", "}", "static", "::", "withoutRecording", "(", "function", "(", ")", "use", "(", "$", "entry", ")", "{", "if", "(", "collect", "(", "static", "::", "$", "filterUsing", ")", "->", "every", "->", "__invoke", "(", "$", "entry", ")", ")", "{", "static", "::", "$", "entriesQueue", "[", "]", "=", "$", "entry", ";", "}", "if", "(", "static", "::", "$", "afterRecordingHook", ")", "{", "call_user_func", "(", "static", "::", "$", "afterRecordingHook", ",", "new", "static", ")", ";", "}", "}", ")", ";", "}" ]
Record the given entry. @param string $type @param \Laravel\Telescope\IncomingEntry $entry @return void
[ "Record", "the", "given", "entry", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L244-L271
train
laravel/telescope
src/Telescope.php
Telescope.catch
public static function catch($e, $tags = []) { if ($e instanceof Throwable && ! $e instanceof Exception) { $e = new FatalThrowableError($e); } event(new MessageLogged('error', $e->getMessage(), [ 'exception' => $e, 'telescope' => $tags, ])); }
php
public static function catch($e, $tags = []) { if ($e instanceof Throwable && ! $e instanceof Exception) { $e = new FatalThrowableError($e); } event(new MessageLogged('error', $e->getMessage(), [ 'exception' => $e, 'telescope' => $tags, ])); }
[ "public", "static", "function", "catch", "(", "$", "e", ",", "$", "tags", "=", "[", "]", ")", "{", "if", "(", "$", "e", "instanceof", "Throwable", "&&", "!", "$", "e", "instanceof", "Exception", ")", "{", "$", "e", "=", "new", "FatalThrowableError", "(", "$", "e", ")", ";", "}", "event", "(", "new", "MessageLogged", "(", "'error'", ",", "$", "e", "->", "getMessage", "(", ")", ",", "[", "'exception'", "=>", "$", "e", ",", "'telescope'", "=>", "$", "tags", ",", "]", ")", ")", ";", "}" ]
Record the given exception. @param \Throwable|\Exception $e @param array $tags @return void
[ "Record", "the", "given", "exception", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L470-L480
train
laravel/telescope
src/Telescope.php
Telescope.store
public static function store(EntriesRepository $storage) { if (empty(static::$entriesQueue) && empty(static::$updatesQueue)) { return; } if (! collect(static::$filterBatchUsing)->every->__invoke(collect(static::$entriesQueue))) { static::flushEntries(); } try { $batchId = Str::orderedUuid()->toString(); $storage->store(static::collectEntries($batchId)); $storage->update(static::collectUpdates($batchId)); if ($storage instanceof TerminableRepository) { $storage->terminate(); } } catch (Exception $e) { app(ExceptionHandler::class)->report($e); } static::$entriesQueue = []; static::$updatesQueue = []; }
php
public static function store(EntriesRepository $storage) { if (empty(static::$entriesQueue) && empty(static::$updatesQueue)) { return; } if (! collect(static::$filterBatchUsing)->every->__invoke(collect(static::$entriesQueue))) { static::flushEntries(); } try { $batchId = Str::orderedUuid()->toString(); $storage->store(static::collectEntries($batchId)); $storage->update(static::collectUpdates($batchId)); if ($storage instanceof TerminableRepository) { $storage->terminate(); } } catch (Exception $e) { app(ExceptionHandler::class)->report($e); } static::$entriesQueue = []; static::$updatesQueue = []; }
[ "public", "static", "function", "store", "(", "EntriesRepository", "$", "storage", ")", "{", "if", "(", "empty", "(", "static", "::", "$", "entriesQueue", ")", "&&", "empty", "(", "static", "::", "$", "updatesQueue", ")", ")", "{", "return", ";", "}", "if", "(", "!", "collect", "(", "static", "::", "$", "filterBatchUsing", ")", "->", "every", "->", "__invoke", "(", "collect", "(", "static", "::", "$", "entriesQueue", ")", ")", ")", "{", "static", "::", "flushEntries", "(", ")", ";", "}", "try", "{", "$", "batchId", "=", "Str", "::", "orderedUuid", "(", ")", "->", "toString", "(", ")", ";", "$", "storage", "->", "store", "(", "static", "::", "collectEntries", "(", "$", "batchId", ")", ")", ";", "$", "storage", "->", "update", "(", "static", "::", "collectUpdates", "(", "$", "batchId", ")", ")", ";", "if", "(", "$", "storage", "instanceof", "TerminableRepository", ")", "{", "$", "storage", "->", "terminate", "(", ")", ";", "}", "}", "catch", "(", "Exception", "$", "e", ")", "{", "app", "(", "ExceptionHandler", "::", "class", ")", "->", "report", "(", "$", "e", ")", ";", "}", "static", "::", "$", "entriesQueue", "=", "[", "]", ";", "static", "::", "$", "updatesQueue", "=", "[", "]", ";", "}" ]
Store the queued entries and flush the queue. @param \Laravel\Telescope\Contracts\EntriesRepository $storage @return void
[ "Store", "the", "queued", "entries", "and", "flush", "the", "queue", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L540-L565
train
laravel/telescope
src/Telescope.php
Telescope.collectEntries
protected static function collectEntries($batchId) { return collect(static::$entriesQueue) ->each(function ($entry) use ($batchId) { $entry->batchId($batchId); if ($entry->isDump()) { $entry->assignEntryPointFromBatch(static::$entriesQueue); } }); }
php
protected static function collectEntries($batchId) { return collect(static::$entriesQueue) ->each(function ($entry) use ($batchId) { $entry->batchId($batchId); if ($entry->isDump()) { $entry->assignEntryPointFromBatch(static::$entriesQueue); } }); }
[ "protected", "static", "function", "collectEntries", "(", "$", "batchId", ")", "{", "return", "collect", "(", "static", "::", "$", "entriesQueue", ")", "->", "each", "(", "function", "(", "$", "entry", ")", "use", "(", "$", "batchId", ")", "{", "$", "entry", "->", "batchId", "(", "$", "batchId", ")", ";", "if", "(", "$", "entry", "->", "isDump", "(", ")", ")", "{", "$", "entry", "->", "assignEntryPointFromBatch", "(", "static", "::", "$", "entriesQueue", ")", ";", "}", "}", ")", ";", "}" ]
Collect the entries for storage. @param string $batchId @return \Illuminate\Support\Collection
[ "Collect", "the", "entries", "for", "storage", "." ]
e5f9512a41f21319d9c99cef618baba0d9206dce
https://github.com/laravel/telescope/blob/e5f9512a41f21319d9c99cef618baba0d9206dce/src/Telescope.php#L573-L583
train