Predis.php 55 KB

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