Predis.php 54 KB

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