Predis.php 53 KB

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