Predis.php 53 KB

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