Predis.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382
  1. <?php
  2. class PredisException extends Exception { }
  3. class Predis_ClientException extends PredisException { }
  4. class Predis_ServerException extends PredisException { }
  5. class Predis_MalformedServerResponse extends Predis_ServerException { }
  6. /* ------------------------------------------------------------------------- */
  7. class Predis_Client {
  8. // TODO: command arguments should be sanitized or checked for bad arguments
  9. // (e.g. CRLF in keys for inline commands)
  10. private $_connection, $_serverProfile;
  11. public function __construct($parameters = null, Predis_RedisServerProfile $serverProfile = null) {
  12. $this->setServerProfile(
  13. $serverProfile === null
  14. ? Predis_RedisServerProfile::getDefault()
  15. : $serverProfile
  16. );
  17. $this->setupConnection($parameters);
  18. }
  19. public function __destruct() {
  20. $this->_connection->disconnect();
  21. }
  22. public static function create(/* arguments */) {
  23. $argv = func_get_args();
  24. $argc = func_num_args();
  25. $serverProfile = null;
  26. $lastArg = $argv[$argc-1];
  27. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, 'Predis_RedisServerProfile')) {
  28. $serverProfile = array_pop($argv);
  29. $argc--;
  30. }
  31. if ($argc === 0) {
  32. throw new Predis_ClientException('Missing connection parameters');
  33. }
  34. return new Predis_Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  35. }
  36. private function setupConnection($parameters) {
  37. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  38. throw new Predis_ClientException('Invalid parameters type (array or string expected)');
  39. }
  40. if (is_array($parameters) && isset($parameters[0])) {
  41. $cluster = new Predis_ConnectionCluster();
  42. foreach ($parameters as $shardParams) {
  43. $cluster->add($this->createConnection($shardParams));
  44. }
  45. $this->setConnection($cluster);
  46. }
  47. else {
  48. $this->setConnection($this->createConnection($parameters));
  49. }
  50. }
  51. private function createConnection($parameters) {
  52. $params = new Predis_ConnectionParameters($parameters);
  53. $connection = new Predis_Connection($params);
  54. if ($params->password !== null) {
  55. $connection->pushInitCommand($this->createCommandInstance(
  56. 'auth', array($params->password)
  57. ));
  58. }
  59. if ($params->database !== null) {
  60. $connection->pushInitCommand($this->createCommandInstance(
  61. 'select', array($params->database)
  62. ));
  63. }
  64. return $connection;
  65. }
  66. private function setConnection(Predis_IConnection $connection) {
  67. $this->_connection = $connection;
  68. }
  69. public function setServerProfile(Predis_RedisServerProfile $serverProfile) {
  70. $this->_serverProfile = $serverProfile;
  71. }
  72. public function connect() {
  73. $this->_connection->connect();
  74. }
  75. public function disconnect() {
  76. $this->_connection->disconnect();
  77. }
  78. public function isConnected() {
  79. return $this->_connection->isConnected();
  80. }
  81. public function getConnection() {
  82. return $this->_connection;
  83. }
  84. public function __call($method, $arguments) {
  85. $command = $this->createCommandInstance($method, $arguments);
  86. return $this->executeCommand($command);
  87. }
  88. public function createCommandInstance($method, $arguments = array()) {
  89. return $this->_serverProfile->createCommandInstance($method, $arguments);
  90. }
  91. private function executeCommandInternal(Predis_IConnection $connection, Predis_Command $command) {
  92. $connection->writeCommand($command);
  93. if ($command->closesConnection()) {
  94. return $connection->disconnect();
  95. }
  96. return $connection->readResponse($command);
  97. }
  98. public function executeCommand(Predis_Command $command) {
  99. return self::executeCommandInternal($this->_connection, $command);
  100. }
  101. public function executeCommandOnShards(Predis_Command $command) {
  102. $replies = array();
  103. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  104. foreach($this->_connection as $connection) {
  105. $replies[] = self::executeCommandInternal($connection, $command);
  106. }
  107. }
  108. else {
  109. $replies[] = self::executeCommandInternal($this->_connection, $command);
  110. }
  111. return $replies;
  112. }
  113. public function rawCommand($rawCommandData, $closesConnection = false) {
  114. // TODO: rather than check the type of a connection instance, we should
  115. // check if it does respond to the rawCommand method.
  116. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  117. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  118. }
  119. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  120. }
  121. public function pipeline() {
  122. return new Predis_CommandPipeline($this);
  123. }
  124. public function registerCommands(Array $commands) {
  125. $this->_serverProfile->registerCommands($commands);
  126. }
  127. public function registerCommand($command, $aliases) {
  128. $this->_serverProfile->registerCommand($command, $aliases);
  129. }
  130. }
  131. /* ------------------------------------------------------------------------- */
  132. abstract class Predis_Command {
  133. private $_arguments, $_hash;
  134. public abstract function getCommandId();
  135. public abstract function serializeRequest($command, $arguments);
  136. public function canBeHashed() {
  137. return true;
  138. }
  139. public function getHash() {
  140. if (isset($this->_hash)) {
  141. return $this->_hash;
  142. }
  143. else {
  144. if (isset($this->_arguments[0])) {
  145. $key = $this->_arguments[0];
  146. $start = strpos($key, '{');
  147. $end = strpos($key, '}');
  148. if ($start !== false && $end !== false) {
  149. $key = substr($key, ++$start, $end - $start);
  150. }
  151. $this->_hash = crc32($key);
  152. return $this->_hash;
  153. }
  154. }
  155. return null;
  156. }
  157. public function closesConnection() {
  158. return false;
  159. }
  160. protected function filterArguments(Array $arguments) {
  161. return $arguments;
  162. }
  163. public function setArguments(/* arguments */) {
  164. $this->_arguments = $this->filterArguments(func_get_args());
  165. }
  166. public function setArgumentsArray(Array $arguments) {
  167. $this->_arguments = $this->filterArguments($arguments);
  168. }
  169. protected function getArguments() {
  170. return isset($this->_arguments) ? $this->_arguments : array();
  171. }
  172. public function getArgument($index = 0) {
  173. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  174. }
  175. public function parseResponse($data) {
  176. return $data;
  177. }
  178. public final function invoke() {
  179. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  180. }
  181. }
  182. abstract class Predis_InlineCommand extends Predis_Command {
  183. public function serializeRequest($command, $arguments) {
  184. if (isset($arguments[0]) && is_array($arguments[0])) {
  185. $arguments[0] = implode($arguments[0], ' ');
  186. }
  187. return $command . ' ' . implode($arguments, ' ') . Predis_Response::NEWLINE;
  188. }
  189. }
  190. abstract class Predis_BulkCommand extends Predis_Command {
  191. public function serializeRequest($command, $arguments) {
  192. $data = array_pop($arguments);
  193. if (is_array($data)) {
  194. $data = implode($data, ' ');
  195. }
  196. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  197. Predis_Response::NEWLINE . $data . Predis_Response::NEWLINE;
  198. }
  199. }
  200. abstract class Predis_MultiBulkCommand extends Predis_Command {
  201. public function serializeRequest($command, $arguments) {
  202. $buffer = array();
  203. $cmd_args = null;
  204. if (count($arguments) === 1 && is_array($arguments[0])) {
  205. $cmd_args = array();
  206. foreach ($arguments[0] as $k => $v) {
  207. $cmd_args[] = $k;
  208. $cmd_args[] = $v;
  209. }
  210. }
  211. else {
  212. $cmd_args = $arguments;
  213. }
  214. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Predis_Response::NEWLINE;
  215. $buffer[] = '$' . strlen($command) . Predis_Response::NEWLINE . $command . Predis_Response::NEWLINE;
  216. foreach ($cmd_args as $argument) {
  217. $buffer[] = '$' . strlen($argument) . Predis_Response::NEWLINE . $argument . Predis_Response::NEWLINE;
  218. }
  219. return implode('', $buffer);
  220. }
  221. }
  222. /* ------------------------------------------------------------------------- */
  223. class Predis_Response {
  224. const NEWLINE = "\r\n";
  225. const OK = 'OK';
  226. const ERROR = 'ERR';
  227. const NULL = 'nil';
  228. private static $_prefixHandlers;
  229. private static function initializePrefixHandlers() {
  230. return array(
  231. // status
  232. '+' => array('Predis_Response', 'handleStatus'),
  233. // error
  234. '-' => array('Predis_Response', 'handleError'),
  235. // bulk
  236. '$' => array('Predis_Response', 'handleBulk'),
  237. // multibulk
  238. '*' => array('Predis_Response', 'handleMultiBulk'),
  239. // integer
  240. ':' => array('Predis_Response', 'handleInteger')
  241. );
  242. }
  243. public static function getPrefixHandler($prefix) {
  244. if (self::$_prefixHandlers === null) {
  245. self::$_prefixHandlers = self::initializePrefixHandlers();
  246. }
  247. $handler = self::$_prefixHandlers[$prefix];
  248. if ($handler === null) {
  249. throw new Predis_MalformedServerResponse("Unknown prefix '$prefix'");
  250. }
  251. return $handler;
  252. }
  253. public static function handleStatus($socket) {
  254. $status = rtrim(fgets($socket), Predis_Response::NEWLINE);
  255. return $status === Predis_Response::OK ? true : $status;
  256. }
  257. public static function handleError($socket) {
  258. $errorMessage = rtrim(fgets($socket), Predis_Response::NEWLINE);
  259. throw new Predis_ServerException(substr($errorMessage, 4));
  260. }
  261. public static function handleBulk($socket) {
  262. $dataLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  263. if (!is_numeric($dataLength)) {
  264. throw new Predis_ClientException("Cannot parse '$dataLength' as data length");
  265. }
  266. if ($dataLength > 0) {
  267. $value = stream_get_contents($socket, $dataLength);
  268. fread($socket, 2);
  269. return $value;
  270. }
  271. else if ($dataLength == 0) {
  272. // TODO: I just have a doubt here...
  273. fread($socket, 2);
  274. }
  275. return null;
  276. }
  277. public static function handleMultiBulk($socket) {
  278. $rawLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  279. if (!is_numeric($rawLength)) {
  280. throw new Predis_ClientException("Cannot parse '$rawLength' as data length");
  281. }
  282. $listLength = (int) $rawLength;
  283. if ($listLength === -1) {
  284. return null;
  285. }
  286. $list = array();
  287. if ($listLength > 0) {
  288. for ($i = 0; $i < $listLength; $i++) {
  289. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  290. $list[] = call_user_func($handler, $socket);
  291. }
  292. }
  293. return $list;
  294. }
  295. public static function handleInteger($socket) {
  296. $number = rtrim(fgets($socket), Predis_Response::NEWLINE);
  297. if (is_numeric($number)) {
  298. return (int) $number;
  299. }
  300. else {
  301. if ($number !== Predis_Response::NULL) {
  302. throw new Predis_ClientException("Cannot parse '$number' as numeric response");
  303. }
  304. return null;
  305. }
  306. }
  307. }
  308. class Predis_CommandPipeline {
  309. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  310. public function __construct(Predis_Client $redisClient) {
  311. $this->_redisClient = $redisClient;
  312. $this->_pipelineBuffer = array();
  313. $this->_returnValues = array();
  314. }
  315. public function __call($method, $arguments) {
  316. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  317. $this->recordCommand($command);
  318. }
  319. private function recordCommand(Predis_Command $command) {
  320. $this->_pipelineBuffer[] = $command;
  321. }
  322. private function getRecordedCommands() {
  323. return $this->_pipelineBuffer;
  324. }
  325. public function flushPipeline() {
  326. if (count($this->_pipelineBuffer) === 0) {
  327. return;
  328. }
  329. $connection = $this->_redisClient->getConnection();
  330. $commands = &$this->getRecordedCommands();
  331. foreach ($commands as $command) {
  332. $connection->writeCommand($command);
  333. }
  334. foreach ($commands as $command) {
  335. $this->_returnValues[] = $connection->readResponse($command);
  336. }
  337. $this->_pipelineBuffer = array();
  338. }
  339. private function setRunning($bool) {
  340. // TODO: I am honest when I say that I don't like this approach.
  341. if ($bool == true && $this->_running == true) {
  342. throw new Predis_ClientException("This pipeline is already opened");
  343. }
  344. $this->_running = $bool;
  345. }
  346. public function execute() {
  347. $this->setRunning(true);
  348. $pipelineBlockException = null;
  349. try {
  350. $this->flushPipeline();
  351. }
  352. catch (Exception $exception) {
  353. $pipelineBlockException = $exception;
  354. }
  355. $this->setRunning(false);
  356. if ($pipelineBlockException !== null) {
  357. throw $pipelineBlockException;
  358. }
  359. return $this->_returnValues;
  360. }
  361. }
  362. /* ------------------------------------------------------------------------- */
  363. class Predis_ConnectionParameters {
  364. const DEFAULT_HOST = '127.0.0.1';
  365. const DEFAULT_PORT = 6379;
  366. private $_parameters;
  367. public function __construct($parameters) {
  368. $parameters = $parameters !== null ? $parameters : array();
  369. $this->_parameters = is_array($parameters)
  370. ? self::filterConnectionParams($parameters)
  371. : self::parseURI($parameters);
  372. }
  373. private static function parseURI($uri) {
  374. $parsed = @parse_url($uri);
  375. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  376. throw new Predis_ClientException("Invalid URI: $uri");
  377. }
  378. if (array_key_exists('query', $parsed)) {
  379. $details = array();
  380. foreach (explode('&', $parsed['query']) as $kv) {
  381. list($k, $v) = explode('=', $kv);
  382. switch ($k) {
  383. case 'database':
  384. $details['database'] = $v;
  385. break;
  386. case 'password':
  387. $details['password'] = $v;
  388. break;
  389. }
  390. }
  391. $parsed = array_merge($parsed, $details);
  392. }
  393. return self::filterConnectionParams($parsed);
  394. }
  395. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  396. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  397. }
  398. private static function filterConnectionParams($parameters) {
  399. return array(
  400. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  401. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  402. 'database' => self::getParamOrDefault($parameters, 'database'),
  403. 'password' => self::getParamOrDefault($parameters, 'password')
  404. );
  405. }
  406. public function __get($parameter) {
  407. return $this->_parameters[$parameter];
  408. }
  409. }
  410. interface Predis_IConnection {
  411. public function connect();
  412. public function disconnect();
  413. public function isConnected();
  414. public function writeCommand(Predis_Command $command);
  415. public function readResponse(Predis_Command $command);
  416. }
  417. class Predis_Connection implements Predis_IConnection {
  418. const CONNECTION_TIMEOUT = 2;
  419. const READ_WRITE_TIMEOUT = 5;
  420. private $_params, $_socket, $_initCmds;
  421. public function __construct(Predis_ConnectionParameters $parameters) {
  422. $this->_params = $parameters;
  423. $this->_initCmds = array();
  424. }
  425. public function __destruct() {
  426. $this->disconnect();
  427. }
  428. public function isConnected() {
  429. return is_resource($this->_socket);
  430. }
  431. public function connect() {
  432. if ($this->isConnected()) {
  433. throw new Predis_ClientException('Connection already estabilished');
  434. }
  435. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  436. $this->_socket = @stream_socket_client($uri, $errno, $errstr, self::CONNECTION_TIMEOUT);
  437. if (!$this->_socket) {
  438. throw new Predis_ClientException(trim($errstr), $errno);
  439. }
  440. stream_set_timeout($this->_socket, self::READ_WRITE_TIMEOUT);
  441. if (count($this->_initCmds) > 0){
  442. $this->sendInitializationCommands();
  443. }
  444. }
  445. public function disconnect() {
  446. if ($this->isConnected()) {
  447. fclose($this->_socket);
  448. }
  449. }
  450. public function pushInitCommand(Predis_Command $command){
  451. $this->_initCmds[] = $command;
  452. }
  453. private function sendInitializationCommands() {
  454. foreach ($this->_initCmds as $command) {
  455. $this->writeCommand($command);
  456. }
  457. foreach ($this->_initCmds as $command) {
  458. $this->readResponse($command);
  459. }
  460. }
  461. public function writeCommand(Predis_Command $command) {
  462. fwrite($this->getSocket(), $command->invoke());
  463. }
  464. public function readResponse(Predis_Command $command) {
  465. $socket = $this->getSocket();
  466. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  467. $response = $command->parseResponse(call_user_func($handler, $socket));
  468. return $response;
  469. }
  470. public function rawCommand($rawCommandData, $closesConnection = false) {
  471. $socket = $this->getSocket();
  472. fwrite($socket, $rawCommandData);
  473. if ($closesConnection) {
  474. return;
  475. }
  476. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  477. return $handler($socket);
  478. }
  479. public function getSocket() {
  480. if (!$this->isConnected()) {
  481. $this->connect();
  482. }
  483. return $this->_socket;
  484. }
  485. public function __toString() {
  486. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  487. }
  488. }
  489. class Predis_ConnectionCluster implements Predis_IConnection, IteratorAggregate {
  490. // TODO: find a clean way to handle connection failures of single nodes.
  491. private $_pool, $_ring;
  492. public function __construct() {
  493. $this->_pool = array();
  494. $this->_ring = new Utilities_HashRing();
  495. }
  496. public function __destruct() {
  497. $this->disconnect();
  498. }
  499. public function isConnected() {
  500. foreach ($this->_pool as $connection) {
  501. if ($connection->isConnected()) {
  502. return true;
  503. }
  504. }
  505. return false;
  506. }
  507. public function connect() {
  508. foreach ($this->_pool as $connection) {
  509. $connection->connect();
  510. }
  511. }
  512. public function disconnect() {
  513. foreach ($this->_pool as $connection) {
  514. $connection->disconnect();
  515. }
  516. }
  517. public function add(Predis_Connection $connection) {
  518. $this->_pool[] = $connection;
  519. $this->_ring->add($connection);
  520. }
  521. private function getConnection(Predis_Command $command) {
  522. if ($command->canBeHashed() === false) {
  523. throw new Predis_ClientException(
  524. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  525. );
  526. }
  527. return $this->_ring->get($command->getHash());
  528. }
  529. public function getConnectionById($id = null) {
  530. return $this->_pool[$id === null ? 0 : $id];
  531. }
  532. public function getIterator() {
  533. return new ArrayIterator($this->_pool);
  534. }
  535. public function writeCommand(Predis_Command $command) {
  536. $this->getConnection($command)->writeCommand($command);
  537. }
  538. public function readResponse(Predis_Command $command) {
  539. return $this->getConnection($command)->readResponse($command);
  540. }
  541. }
  542. /* ------------------------------------------------------------------------- */
  543. abstract class Predis_RedisServerProfile {
  544. const DEFAULT_SERVER_PROFILE = 'Predis_RedisServer__V1_2';
  545. private $_registeredCommands;
  546. public function __construct() {
  547. $this->_registeredCommands = $this->getSupportedCommands();
  548. }
  549. public abstract function getVersion();
  550. protected abstract function getSupportedCommands();
  551. public static function getDefault() {
  552. $defaultProfile = self::DEFAULT_SERVER_PROFILE;
  553. return new $defaultProfile();
  554. }
  555. public function createCommandInstance($method, $arguments = array()) {
  556. $commandClass = $this->_registeredCommands[$method];
  557. if ($commandClass === null) {
  558. throw new Predis_ClientException("'$method' is not a registered Redis command");
  559. }
  560. $command = new $commandClass();
  561. $command->setArgumentsArray($arguments);
  562. return $command;
  563. }
  564. public function registerCommands(Array $commands) {
  565. foreach ($commands as $command => $aliases) {
  566. $this->registerCommand($command, $aliases);
  567. }
  568. }
  569. public function registerCommand($command, $aliases) {
  570. $commandReflection = new ReflectionClass($command);
  571. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  572. throw new Predis_ClientException("Cannot register '$command' as it is not a valid Redis command");
  573. }
  574. if (is_array($aliases)) {
  575. foreach ($aliases as $alias) {
  576. $this->_registeredCommands[$alias] = $command;
  577. }
  578. }
  579. else {
  580. $this->_registeredCommands[$aliases] = $command;
  581. }
  582. }
  583. }
  584. class Predis_RedisServer__V1_0 extends Predis_RedisServerProfile {
  585. public function getVersion() { return 1.0; }
  586. public function getSupportedCommands() {
  587. return array(
  588. /* miscellaneous commands */
  589. 'ping' => 'Predis_Commands_Ping',
  590. 'echo' => 'Predis_Commands_DoEcho',
  591. 'auth' => 'Predis_Commands_Auth',
  592. /* connection handling */
  593. 'quit' => 'Predis_Commands_Quit',
  594. /* commands operating on string values */
  595. 'set' => 'Predis_Commands_Set',
  596. 'setnx' => 'Predis_Commands_SetPreserve',
  597. 'setPreserve' => 'Predis_Commands_SetPreserve',
  598. 'get' => 'Predis_Commands_Get',
  599. 'mget' => 'Predis_Commands_GetMultiple',
  600. 'getMultiple' => 'Predis_Commands_GetMultiple',
  601. 'getset' => 'Predis_Commands_GetSet',
  602. 'getSet' => 'Predis_Commands_GetSet',
  603. 'incr' => 'Predis_Commands_Increment',
  604. 'increment' => 'Predis_Commands_Increment',
  605. 'incrby' => 'Predis_Commands_IncrementBy',
  606. 'incrementBy' => 'Predis_Commands_IncrementBy',
  607. 'decr' => 'Predis_Commands_Decrement',
  608. 'decrement' => 'Predis_Commands_Decrement',
  609. 'decrby' => 'Predis_Commands_DecrementBy',
  610. 'decrementBy' => 'Predis_Commands_DecrementBy',
  611. 'exists' => 'Predis_Commands_Exists',
  612. 'del' => 'Predis_Commands_Delete',
  613. 'delete' => 'Predis_Commands_Delete',
  614. 'type' => 'Predis_Commands_Type',
  615. /* commands operating on the key space */
  616. 'keys' => 'Predis_Commands_Keys',
  617. 'randomkey' => 'Predis_Commands_RandomKey',
  618. 'randomKey' => 'Predis_Commands_RandomKey',
  619. 'rename' => 'Predis_Commands_Rename',
  620. 'renamenx' => 'Predis_Commands_RenamePreserve',
  621. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  622. 'expire' => 'Predis_Commands_Expire',
  623. 'expireat' => 'Predis_Commands_ExpireAt',
  624. 'expireAt' => 'Predis_Commands_ExpireAt',
  625. 'dbsize' => 'Predis_Commands_DatabaseSize',
  626. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  627. 'ttl' => 'Predis_Commands_TimeToLive',
  628. 'timeToLive' => 'Predis_Commands_TimeToLive',
  629. /* commands operating on lists */
  630. 'rpush' => 'Predis_Commands_ListPushTail',
  631. 'pushTail' => 'Predis_Commands_ListPushTail',
  632. 'lpush' => 'Predis_Commands_ListPushHead',
  633. 'pushHead' => 'Predis_Commands_ListPushHead',
  634. 'llen' => 'Predis_Commands_ListLength',
  635. 'listLength' => 'Predis_Commands_ListLength',
  636. 'lrange' => 'Predis_Commands_ListRange',
  637. 'listRange' => 'Predis_Commands_ListRange',
  638. 'ltrim' => 'Predis_Commands_ListTrim',
  639. 'listTrim' => 'Predis_Commands_ListTrim',
  640. 'lindex' => 'Predis_Commands_ListIndex',
  641. 'listIndex' => 'Predis_Commands_ListIndex',
  642. 'lset' => 'Predis_Commands_ListSet',
  643. 'listSet' => 'Predis_Commands_ListSet',
  644. 'lrem' => 'Predis_Commands_ListRemove',
  645. 'listRemove' => 'Predis_Commands_ListRemove',
  646. 'lpop' => 'Predis_Commands_ListPopFirst',
  647. 'popFirst' => 'Predis_Commands_ListPopFirst',
  648. 'rpop' => 'Predis_Commands_ListPopLast',
  649. 'popLast' => 'Predis_Commands_ListPopLast',
  650. /* commands operating on sets */
  651. 'sadd' => 'Predis_Commands_SetAdd',
  652. 'setAdd' => 'Predis_Commands_SetAdd',
  653. 'srem' => 'Predis_Commands_SetRemove',
  654. 'setRemove' => 'Predis_Commands_SetRemove',
  655. 'spop' => 'Predis_Commands_SetPop',
  656. 'setPop' => 'Predis_Commands_SetPop',
  657. 'smove' => 'Predis_Commands_SetMove',
  658. 'setMove' => 'Predis_Commands_SetMove',
  659. 'scard' => 'Predis_Commands_SetCardinality',
  660. 'setCardinality' => 'Predis_Commands_SetCardinality',
  661. 'sismember' => 'Predis_Commands_SetIsMember',
  662. 'setIsMember' => 'Predis_Commands_SetIsMember',
  663. 'sinter' => 'Predis_Commands_SetIntersection',
  664. 'setIntersection' => 'Predis_Commands_SetIntersection',
  665. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  666. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  667. 'sunion' => 'Predis_Commands_SetUnion',
  668. 'setUnion' => 'Predis_Commands_SetUnion',
  669. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  670. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  671. 'sdiff' => 'Predis_Commands_SetDifference',
  672. 'setDifference' => 'Predis_Commands_SetDifference',
  673. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  674. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  675. 'smembers' => 'Predis_Commands_SetMembers',
  676. 'setMembers' => 'Predis_Commands_SetMembers',
  677. 'srandmember' => 'Predis_Commands_SetRandomMember',
  678. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  679. /* multiple databases handling commands */
  680. 'select' => 'Predis_Commands_SelectDatabase',
  681. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  682. 'move' => 'Predis_Commands_MoveKey',
  683. 'moveKey' => 'Predis_Commands_MoveKey',
  684. 'flushdb' => 'Predis_Commands_FlushDatabase',
  685. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  686. 'flushall' => 'Predis_Commands_FlushAll',
  687. 'flushDatabases' => 'Predis_Commands_FlushAll',
  688. /* sorting */
  689. 'sort' => 'Predis_Commands_Sort',
  690. /* remote server control commands */
  691. 'info' => 'Predis_Commands_Info',
  692. 'slaveof' => 'Predis_Commands_SlaveOf',
  693. 'slaveOf' => 'Predis_Commands_SlaveOf',
  694. /* persistence control commands */
  695. 'save' => 'Predis_Commands_Save',
  696. 'bgsave' => 'Predis_Commands_BackgroundSave',
  697. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  698. 'lastsave' => 'Predis_Commands_LastSave',
  699. 'lastSave' => 'Predis_Commands_LastSave',
  700. 'shutdown' => 'Predis_Commands_Shutdown'
  701. );
  702. }
  703. }
  704. class Predis_RedisServer__V1_2 extends Predis_RedisServer__V1_0 {
  705. public function getVersion() { return 1.2; }
  706. public function getSupportedCommands() {
  707. return array_merge(parent::getSupportedCommands(), array(
  708. /* commands operating on string values */
  709. 'mset' => 'Predis_Commands_SetMultiple',
  710. 'setMultiple' => 'Predis_Commands_SetMultiple',
  711. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  712. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  713. /* commands operating on lists */
  714. 'rpoplpush' => 'Predis_Commands_ListPushTailPopFirst',
  715. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  716. /* commands operating on sorted sets */
  717. 'zadd' => 'Predis_Commands_ZSetAdd',
  718. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  719. 'zincrby' => 'Predis_Commands_ZSetIncrementBy',
  720. 'zsetIncrementBy' => 'Predis_Commands_ZSetIncrementBy',
  721. 'zrem' => 'Predis_Commands_ZSetRemove',
  722. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  723. 'zrange' => 'Predis_Commands_ZSetRange',
  724. 'zsetRange' => 'Predis_Commands_ZSetRange',
  725. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  726. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  727. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  728. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  729. 'zcard' => 'Predis_Commands_ZSetCardinality',
  730. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  731. 'zscore' => 'Predis_Commands_ZSetScore',
  732. 'zsetScore' => 'Predis_Commands_ZSetScore',
  733. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  734. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore'
  735. ));
  736. }
  737. }
  738. /* ------------------------------------------------------------------------- */
  739. class Utilities_HashRing {
  740. const DEFAULT_REPLICAS = 128;
  741. private $_ring, $_ringKeys, $_replicas;
  742. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  743. $this->_replicas = $replicas;
  744. $this->_ring = array();
  745. $this->_ringKeys = array();
  746. }
  747. public function add($node) {
  748. $nodeHash = (string) $node;
  749. $replicas = $this->_replicas;
  750. for ($i = 0; $i < $replicas; $i++) {
  751. $key = crc32($nodeHash . ':' . $i);
  752. $this->_ring[$key] = $node;
  753. }
  754. ksort($this->_ring, SORT_NUMERIC);
  755. $this->_ringKeys = array_keys($this->_ring);
  756. }
  757. public function remove($node) {
  758. $nodeHash = (string) $node;
  759. $replicas = $this->_replicas;
  760. for ($i = 0; $i < $replicas; $i++) {
  761. $key = crc32($nodeHash . ':' . $i);
  762. unset($this->_ring[$key]);
  763. $newRing = array();
  764. foreach ($this->_ringKeys as $rk) {
  765. if ($rk !== $key) {
  766. $newRing[] = $rk;
  767. }
  768. }
  769. $this->_ringKeys = $newRing;
  770. }
  771. }
  772. public function get($key) {
  773. return $this->_ring[$this->getNodeKey($key)];
  774. }
  775. private function getNodeKey($key) {
  776. $ringKeys = $this->_ringKeys;
  777. $upper = count($ringKeys) - 1;
  778. $lower = 0;
  779. $index = 0;
  780. while ($lower <= $upper) {
  781. $index = ($lower + $upper) / 2;
  782. $item = $ringKeys[$index];
  783. if ($item > $key) {
  784. $upper = $index - 1;
  785. }
  786. else if ($item < $key) {
  787. $lower = $index + 1;
  788. }
  789. else {
  790. return $index;
  791. }
  792. }
  793. return $ringKeys[$upper];
  794. }
  795. }
  796. /* ------------------------------------------------------------------------- */
  797. /* miscellaneous commands */
  798. class Predis_Commands_Ping extends Predis_InlineCommand {
  799. public function canBeHashed() { return false; }
  800. public function getCommandId() { return 'PING'; }
  801. public function parseResponse($data) {
  802. return $data === 'PONG' ? true : false;
  803. }
  804. }
  805. class Predis_Commands_DoEcho extends Predis_BulkCommand {
  806. public function canBeHashed() { return false; }
  807. public function getCommandId() { return 'ECHO'; }
  808. }
  809. class Predis_Commands_Auth extends Predis_InlineCommand {
  810. public function canBeHashed() { return false; }
  811. public function getCommandId() { return 'AUTH'; }
  812. }
  813. /* connection handling */
  814. class Predis_Commands_Quit extends Predis_InlineCommand {
  815. public function canBeHashed() { return false; }
  816. public function getCommandId() { return 'QUIT'; }
  817. public function closesConnection() { return true; }
  818. }
  819. /* commands operating on string values */
  820. class Predis_Commands_Set extends Predis_BulkCommand {
  821. public function getCommandId() { return 'SET'; }
  822. }
  823. class Predis_Commands_SetPreserve extends Predis_BulkCommand {
  824. public function getCommandId() { return 'SETNX'; }
  825. public function parseResponse($data) { return (bool) $data; }
  826. }
  827. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  828. public function canBeHashed() { return false; }
  829. public function getCommandId() { return 'MSET'; }
  830. }
  831. class Predis_Commands_SetMultiplePreserve extends Predis_MultiBulkCommand {
  832. public function canBeHashed() { return false; }
  833. public function getCommandId() { return 'MSETNX'; }
  834. public function parseResponse($data) { return (bool) $data; }
  835. }
  836. class Predis_Commands_Get extends Predis_InlineCommand {
  837. public function getCommandId() { return 'GET'; }
  838. }
  839. class Predis_Commands_GetMultiple extends Predis_InlineCommand {
  840. public function canBeHashed() { return false; }
  841. public function getCommandId() { return 'MGET'; }
  842. }
  843. class Predis_Commands_GetSet extends Predis_BulkCommand {
  844. public function getCommandId() { return 'GETSET'; }
  845. }
  846. class Predis_Commands_Increment extends Predis_InlineCommand {
  847. public function getCommandId() { return 'INCR'; }
  848. }
  849. class Predis_Commands_IncrementBy extends Predis_InlineCommand {
  850. public function getCommandId() { return 'INCRBY'; }
  851. }
  852. class Predis_Commands_Decrement extends Predis_InlineCommand {
  853. public function getCommandId() { return 'DECR'; }
  854. }
  855. class Predis_Commands_DecrementBy extends Predis_InlineCommand {
  856. public function getCommandId() { return 'DECRBY'; }
  857. }
  858. class Predis_Commands_Exists extends Predis_InlineCommand {
  859. public function getCommandId() { return 'EXISTS'; }
  860. public function parseResponse($data) { return (bool) $data; }
  861. }
  862. class Predis_Commands_Delete extends Predis_InlineCommand {
  863. public function getCommandId() { return 'DEL'; }
  864. public function parseResponse($data) { return (bool) $data; }
  865. }
  866. class Predis_Commands_Type extends Predis_InlineCommand {
  867. public function getCommandId() { return 'TYPE'; }
  868. }
  869. /* commands operating on the key space */
  870. class Predis_Commands_Keys extends Predis_InlineCommand {
  871. public function canBeHashed() { return false; }
  872. public function getCommandId() { return 'KEYS'; }
  873. public function parseResponse($data) {
  874. // TODO: is this behaviour correct?
  875. return strlen($data) > 0 ? explode(' ', $data) : array();
  876. }
  877. }
  878. class Predis_Commands_RandomKey extends Predis_InlineCommand {
  879. public function canBeHashed() { return false; }
  880. public function getCommandId() { return 'RANDOMKEY'; }
  881. public function parseResponse($data) { return $data !== '' ? $data : null; }
  882. }
  883. class Predis_Commands_Rename extends Predis_InlineCommand {
  884. // TODO: doesn't RENAME break the hash-based client-side sharding?
  885. public function canBeHashed() { return false; }
  886. public function getCommandId() { return 'RENAME'; }
  887. }
  888. class Predis_Commands_RenamePreserve extends Predis_InlineCommand {
  889. public function canBeHashed() { return false; }
  890. public function getCommandId() { return 'RENAMENX'; }
  891. public function parseResponse($data) { return (bool) $data; }
  892. }
  893. class Predis_Commands_Expire extends Predis_InlineCommand {
  894. public function getCommandId() { return 'EXPIRE'; }
  895. public function parseResponse($data) { return (bool) $data; }
  896. }
  897. class Predis_Commands_ExpireAt extends Predis_InlineCommand {
  898. public function getCommandId() { return 'EXPIREAT'; }
  899. public function parseResponse($data) { return (bool) $data; }
  900. }
  901. class Predis_Commands_DatabaseSize extends Predis_InlineCommand {
  902. public function canBeHashed() { return false; }
  903. public function getCommandId() { return 'DBSIZE'; }
  904. }
  905. class Predis_Commands_TimeToLive extends Predis_InlineCommand {
  906. public function getCommandId() { return 'TTL'; }
  907. }
  908. /* commands operating on lists */
  909. class Predis_Commands_ListPushTail extends Predis_BulkCommand {
  910. public function getCommandId() { return 'RPUSH'; }
  911. }
  912. class Predis_Commands_ListPushHead extends Predis_BulkCommand {
  913. public function getCommandId() { return 'LPUSH'; }
  914. }
  915. class Predis_Commands_ListLength extends Predis_InlineCommand {
  916. public function getCommandId() { return 'LLEN'; }
  917. }
  918. class Predis_Commands_ListRange extends Predis_InlineCommand {
  919. public function getCommandId() { return 'LRANGE'; }
  920. }
  921. class Predis_Commands_ListTrim extends Predis_InlineCommand {
  922. public function getCommandId() { return 'LTRIM'; }
  923. }
  924. class Predis_Commands_ListIndex extends Predis_InlineCommand {
  925. public function getCommandId() { return 'LINDEX'; }
  926. }
  927. class Predis_Commands_ListSet extends Predis_BulkCommand {
  928. public function getCommandId() { return 'LSET'; }
  929. }
  930. class Predis_Commands_ListRemove extends Predis_BulkCommand {
  931. public function getCommandId() { return 'LREM'; }
  932. }
  933. class Predis_Commands_ListPopLastPushHead extends Predis_BulkCommand {
  934. public function getCommandId() { return 'RPOPLPUSH'; }
  935. }
  936. class Predis_Commands_ListPopFirst extends Predis_InlineCommand {
  937. public function getCommandId() { return 'LPOP'; }
  938. }
  939. class Predis_Commands_ListPopLast extends Predis_InlineCommand {
  940. public function getCommandId() { return 'RPOP'; }
  941. }
  942. /* commands operating on sets */
  943. class Predis_Commands_SetAdd extends Predis_BulkCommand {
  944. public function getCommandId() { return 'SADD'; }
  945. public function parseResponse($data) { return (bool) $data; }
  946. }
  947. class Predis_Commands_SetRemove extends Predis_BulkCommand {
  948. public function getCommandId() { return 'SREM'; }
  949. public function parseResponse($data) { return (bool) $data; }
  950. }
  951. class Predis_Commands_SetPop extends Predis_InlineCommand {
  952. public function getCommandId() { return 'SPOP'; }
  953. }
  954. class Predis_Commands_SetMove extends Predis_BulkCommand {
  955. public function canBeHashed() { return false; }
  956. public function getCommandId() { return 'SMOVE'; }
  957. public function parseResponse($data) { return (bool) $data; }
  958. }
  959. class Predis_Commands_SetCardinality extends Predis_InlineCommand {
  960. public function getCommandId() { return 'SCARD'; }
  961. }
  962. class Predis_Commands_SetIsMember extends Predis_BulkCommand {
  963. public function getCommandId() { return 'SISMEMBER'; }
  964. public function parseResponse($data) { return (bool) $data; }
  965. }
  966. class Predis_Commands_SetIntersection extends Predis_InlineCommand {
  967. public function getCommandId() { return 'SINTER'; }
  968. }
  969. class Predis_Commands_SetIntersectionStore extends Predis_InlineCommand {
  970. public function getCommandId() { return 'SINTERSTORE'; }
  971. }
  972. class Predis_Commands_SetUnion extends Predis_InlineCommand {
  973. public function getCommandId() { return 'SUNION'; }
  974. }
  975. class Predis_Commands_SetUnionStore extends Predis_InlineCommand {
  976. public function getCommandId() { return 'SUNIONSTORE'; }
  977. }
  978. class Predis_Commands_SetDifference extends Predis_InlineCommand {
  979. public function getCommandId() { return 'SDIFF'; }
  980. }
  981. class Predis_Commands_SetDifferenceStore extends Predis_InlineCommand {
  982. public function getCommandId() { return 'SDIFFSTORE'; }
  983. }
  984. class Predis_Commands_SetMembers extends Predis_InlineCommand {
  985. public function getCommandId() { return 'SMEMBERS'; }
  986. }
  987. class Predis_Commands_SetRandomMember extends Predis_InlineCommand {
  988. public function getCommandId() { return 'SRANDMEMBER'; }
  989. }
  990. /* commands operating on sorted sets */
  991. class Predis_Commands_ZSetAdd extends Predis_BulkCommand {
  992. public function getCommandId() { return 'ZADD'; }
  993. public function parseResponse($data) { return (bool) $data; }
  994. }
  995. class Predis_Commands_ZSetIncrementBy extends Predis_BulkCommand {
  996. public function getCommandId() { return 'ZINCRBY'; }
  997. }
  998. class Predis_Commands_ZSetRemove extends Predis_BulkCommand {
  999. public function getCommandId() { return 'ZREM'; }
  1000. public function parseResponse($data) { return (bool) $data; }
  1001. }
  1002. class Predis_Commands_ZSetRange extends Predis_InlineCommand {
  1003. public function getCommandId() { return 'ZRANGE'; }
  1004. public function parseResponse($data) {
  1005. $arguments = $this->getArguments();
  1006. if (count($arguments) === 4) {
  1007. if (strtolower($arguments[3]) === 'withscores') {
  1008. $result = array();
  1009. for ($i = 0; $i < count($data); $i++) {
  1010. $result[] = array($data[$i], $data[++$i]);
  1011. }
  1012. return $result;
  1013. }
  1014. }
  1015. return $data;
  1016. }
  1017. }
  1018. class Predis_Commands_ZSetReverseRange extends Predis_InlineCommand {
  1019. public function getCommandId() { return 'ZREVRANGE'; }
  1020. public function parseResponse($data) {
  1021. $arguments = $this->getArguments();
  1022. if (count($arguments) === 4) {
  1023. if (strtolower($arguments[3]) === 'withscores') {
  1024. $result = array();
  1025. for ($i = 0; $i < count($data); $i++) {
  1026. $result[] = array($data[$i], $data[++$i]);
  1027. }
  1028. return $result;
  1029. }
  1030. }
  1031. return $data;
  1032. }
  1033. }
  1034. class Predis_Commands_ZSetRangeByScore extends Predis_InlineCommand {
  1035. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1036. }
  1037. class Predis_Commands_ZSetCardinality extends Predis_InlineCommand {
  1038. public function getCommandId() { return 'ZCARD'; }
  1039. }
  1040. class Predis_Commands_ZSetScore extends Predis_BulkCommand {
  1041. public function getCommandId() { return 'ZSCORE'; }
  1042. }
  1043. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_InlineCommand {
  1044. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1045. }
  1046. /* multiple databases handling commands */
  1047. class Predis_Commands_SelectDatabase extends Predis_InlineCommand {
  1048. public function canBeHashed() { return false; }
  1049. public function getCommandId() { return 'SELECT'; }
  1050. }
  1051. class Predis_Commands_MoveKey extends Predis_InlineCommand {
  1052. public function canBeHashed() { return false; }
  1053. public function getCommandId() { return 'MOVE'; }
  1054. public function parseResponse($data) { return (bool) $data; }
  1055. }
  1056. class Predis_Commands_FlushDatabase extends Predis_InlineCommand {
  1057. public function canBeHashed() { return false; }
  1058. public function getCommandId() { return 'FLUSHDB'; }
  1059. }
  1060. class Predis_Commands_FlushAll extends Predis_InlineCommand {
  1061. public function canBeHashed() { return false; }
  1062. public function getCommandId() { return 'FLUSHALL'; }
  1063. }
  1064. /* sorting */
  1065. class Predis_Commands_Sort extends Predis_InlineCommand {
  1066. public function getCommandId() { return 'SORT'; }
  1067. public function filterArguments($arguments) {
  1068. if (count($arguments) === 1) {
  1069. return $arguments;
  1070. }
  1071. // TODO: add more parameters checks
  1072. $query = array($arguments[0]);
  1073. $sortParams = $arguments[1];
  1074. if (isset($sortParams['by'])) {
  1075. $query[] = 'BY ' . $sortParams['by'];
  1076. }
  1077. if (isset($sortParams['get'])) {
  1078. $query[] = 'GET ' . $sortParams['get'];
  1079. }
  1080. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1081. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1082. }
  1083. if (isset($sortParams['sort'])) {
  1084. $query[] = strtoupper($sortParams['sort']);
  1085. }
  1086. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1087. $query[] = 'ALPHA';
  1088. }
  1089. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1090. $query[] = 'STORE ' . $sortParams['store'];
  1091. }
  1092. return $query;
  1093. }
  1094. }
  1095. /* persistence control commands */
  1096. class Predis_Commands_Save extends Predis_InlineCommand {
  1097. public function canBeHashed() { return false; }
  1098. public function getCommandId() { return 'SAVE'; }
  1099. }
  1100. class Predis_Commands_BackgroundSave extends Predis_InlineCommand {
  1101. public function canBeHashed() { return false; }
  1102. public function getCommandId() { return 'BGSAVE'; }
  1103. }
  1104. class Predis_Commands_LastSave extends Predis_InlineCommand {
  1105. public function canBeHashed() { return false; }
  1106. public function getCommandId() { return 'LASTSAVE'; }
  1107. }
  1108. class Predis_Commands_Shutdown extends Predis_InlineCommand {
  1109. public function canBeHashed() { return false; }
  1110. public function getCommandId() { return 'SHUTDOWN'; }
  1111. public function closesConnection() { return true; }
  1112. }
  1113. /* remote server control commands */
  1114. class Predis_Commands_Info extends Predis_InlineCommand {
  1115. public function canBeHashed() { return false; }
  1116. public function getCommandId() { return 'INFO'; }
  1117. public function parseResponse($data) {
  1118. $info = array();
  1119. $infoLines = explode("\r\n", $data, -1);
  1120. foreach ($infoLines as $row) {
  1121. list($k, $v) = explode(':', $row);
  1122. if (!preg_match('/^db\d+$/', $k)) {
  1123. $info[$k] = $v;
  1124. }
  1125. else {
  1126. $db = array();
  1127. foreach (explode(',', $v) as $dbvar) {
  1128. list($dbvk, $dbvv) = explode('=', $dbvar);
  1129. $db[trim($dbvk)] = $dbvv;
  1130. }
  1131. $info[$k] = $db;
  1132. }
  1133. }
  1134. return $info;
  1135. }
  1136. }
  1137. class SlaveOf extends Predis_InlineCommand {
  1138. public function canBeHashed() { return false; }
  1139. public function getCommandId() { return 'SLAVEOF'; }
  1140. public function filterArguments($arguments) {
  1141. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1142. }
  1143. }
  1144. ?>