Predis.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. <?php
  2. class PredisException extends Exception { }
  3. class Predis_ClientException extends PredisException { }
  4. class Predis_ServerException extends PredisException { }
  5. class Predis_MalformedServerResponse extends Predis_ServerException { }
  6. /* ------------------------------------------------------------------------- */
  7. class Predis_Client {
  8. // TODO: command arguments should be sanitized or checked for bad arguments
  9. // (e.g. CRLF in keys for inline commands)
  10. private $_connection, $_registeredCommands;
  11. public function __construct($host = Predis_Connection::DEFAULT_HOST, $port = Predis_Connection::DEFAULT_PORT) {
  12. $this->_registeredCommands = self::initializeDefaultCommands();
  13. $this->setConnection($this->createConnection(
  14. func_num_args() === 1 && is_array($host) || @stripos('redis://') === 0
  15. ? $host
  16. : array('host' => $host, 'port' => $port)
  17. ));
  18. }
  19. public function __destruct() {
  20. $this->_connection->disconnect();
  21. }
  22. public static function create(/* arguments */) {
  23. $argv = func_get_args();
  24. $argc = func_num_args();
  25. if ($argc == 1) {
  26. return new Predis_Client($argv[0]);
  27. }
  28. else if ($argc > 1) {
  29. $client = new Predis_Client();
  30. $cluster = new Predis_ConnectionCluster();
  31. foreach ($argv as $parameters) {
  32. // TODO: this is a bit dirty...
  33. $cluster->add($client->createConnection($parameters));
  34. }
  35. $client->setConnection($cluster);
  36. return $client;
  37. }
  38. else {
  39. return new Predis_Client();
  40. }
  41. }
  42. private function createConnection($parameters) {
  43. $params = new Predis_ConnectionParameters($parameters);
  44. $connection = new Predis_Connection($params);
  45. if ($params->password !== null) {
  46. $connection->pushInitCommand($this->createCommandInstance(
  47. 'auth', array($params->password)
  48. ));
  49. }
  50. if ($params->database !== null) {
  51. $connection->pushInitCommand($this->createCommandInstance(
  52. 'select', array($params->database)
  53. ));
  54. }
  55. return $connection;
  56. }
  57. private function setConnection(Predis_IConnection $connection) {
  58. $this->_connection = $connection;
  59. }
  60. public function connect() {
  61. $this->_connection->connect();
  62. }
  63. public function disconnect() {
  64. $this->_connection->disconnect();
  65. }
  66. public function isConnected() {
  67. return $this->_connection->isConnected();
  68. }
  69. public function getConnection() {
  70. return $this->_connection;
  71. }
  72. public function __call($method, $arguments) {
  73. $command = $this->createCommandInstance($method, $arguments);
  74. return $this->executeCommand($command);
  75. }
  76. public function createCommandInstance($method, $arguments) {
  77. $commandClass = $this->_registeredCommands[$method];
  78. if ($commandClass === null) {
  79. throw new Predis_ClientException("'$method' is not a registered Redis command");
  80. }
  81. $command = new $commandClass();
  82. $command->setArgumentsArray($arguments);
  83. return $command;
  84. }
  85. public function executeCommand(Predis_Command $command) {
  86. $this->_connection->writeCommand($command);
  87. if ($command->closesConnection()) {
  88. return $this->_connection->disconnect();
  89. }
  90. return $this->_connection->readResponse($command);
  91. }
  92. public function rawCommand($rawCommandData, $closesConnection = false) {
  93. // TODO: rather than check the type of a connection instance, we should
  94. // check if it does respond to the rawCommand method.
  95. if (is_a($this->_connection, 'Predis_ConnectionCluster')) {
  96. throw new Predis_ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  97. }
  98. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  99. }
  100. public function pipeline() {
  101. return new Predis_CommandPipeline($this);
  102. }
  103. public function registerCommands(Array $commands) {
  104. foreach ($commands as $command => $aliases) {
  105. $this->registerCommand($command, $aliases);
  106. }
  107. }
  108. public function registerCommand($command, $aliases) {
  109. $commandReflection = new ReflectionClass($command);
  110. if (!$commandReflection->isSubclassOf('Predis_Command')) {
  111. throw new Predis_ClientException("Cannot register '$command' as it is not a valid Redis command");
  112. }
  113. if (is_array($aliases)) {
  114. foreach ($aliases as $alias) {
  115. $this->_registeredCommands[$alias] = $command;
  116. }
  117. }
  118. else {
  119. $this->_registeredCommands[$aliases] = $command;
  120. }
  121. }
  122. private static function initializeDefaultCommands() {
  123. // NOTE: we don't use Predis_Client::registerCommands for performance reasons.
  124. return array(
  125. /* miscellaneous commands */
  126. 'ping' => 'Predis_Commands_Ping',
  127. 'echo' => 'Predis_Commands_DoEcho',
  128. 'auth' => 'Predis_Commands_Auth',
  129. /* connection handling */
  130. 'quit' => 'Predis_Commands_Quit',
  131. /* commands operating on string values */
  132. 'set' => 'Predis_Commands_Set',
  133. 'setnx' => 'Predis_Commands_SetPreserve',
  134. 'setPreserve' => 'Predis_Commands_SetPreserve',
  135. 'mset' => 'Predis_Commands_SetMultiple',
  136. 'setMultiple' => 'Predis_Commands_SetMultiple',
  137. 'msetnx' => 'Predis_Commands_SetMultiplePreserve',
  138. 'setMultiplePreserve' => 'Predis_Commands_SetMultiplePreserve',
  139. 'get' => 'Predis_Commands_Get',
  140. 'mget' => 'Predis_Commands_GetMultiple',
  141. 'getMultiple' => 'Predis_Commands_GetMultiple',
  142. 'getset' => 'Predis_Commands_GetSet',
  143. 'getSet' => 'Predis_Commands_GetSet',
  144. 'incr' => 'Predis_Commands_Increment',
  145. 'increment' => 'Predis_Commands_Increment',
  146. 'incrby' => 'Predis_Commands_IncrementBy',
  147. 'incrementBy' => 'Predis_Commands_IncrementBy',
  148. 'decr' => 'Predis_Commands_Decrement',
  149. 'decrement' => 'Predis_Commands_Decrement',
  150. 'decrby' => 'Predis_Commands_DecrementBy',
  151. 'decrementBy' => 'Predis_Commands_DecrementBy',
  152. 'exists' => 'Predis_Commands_Exists',
  153. 'del' => 'Predis_Commands_Delete',
  154. 'delete' => 'Predis_Commands_Delete',
  155. 'type' => 'Predis_Commands_Type',
  156. /* commands operating on the key space */
  157. 'keys' => 'Predis_Commands_Keys',
  158. 'randomkey' => 'Predis_Commands_RandomKey',
  159. 'randomKey' => 'Predis_Commands_RandomKey',
  160. 'rename' => 'Predis_Commands_Rename',
  161. 'renamenx' => 'Predis_Commands_RenamePreserve',
  162. 'renamePreserve' => 'Predis_Commands_RenamePreserve',
  163. 'expire' => 'Predis_Commands_Expire',
  164. 'expireat' => 'Predis_Commands_ExpireAt',
  165. 'expireAt' => 'Predis_Commands_ExpireAt',
  166. 'dbsize' => 'Predis_Commands_DatabaseSize',
  167. 'databaseSize' => 'Predis_Commands_DatabaseSize',
  168. 'ttl' => 'Predis_Commands_TimeToLive',
  169. 'timeToLive' => 'Predis_Commands_TimeToLive',
  170. /* commands operating on lists */
  171. 'rpush' => 'Predis_Commands_ListPushTail',
  172. 'pushTail' => 'Predis_Commands_ListPushTail',
  173. 'lpush' => 'Predis_Commands_ListPushHead',
  174. 'pushHead' => 'Predis_Commands_ListPushHead',
  175. 'llen' => 'Predis_Commands_ListLength',
  176. 'listLength' => 'Predis_Commands_ListLength',
  177. 'lrange' => 'Predis_Commands_ListRange',
  178. 'listRange' => 'Predis_Commands_ListRange',
  179. 'ltrim' => 'Predis_Commands_ListTrim',
  180. 'listTrim' => 'Predis_Commands_ListTrim',
  181. 'lindex' => 'Predis_Commands_ListIndex',
  182. 'listIndex' => 'Predis_Commands_ListIndex',
  183. 'lset' => 'Predis_Commands_ListSet',
  184. 'listSet' => 'Predis_Commands_ListSet',
  185. 'lrem' => 'Predis_Commands_ListRemove',
  186. 'listRemove' => 'Predis_Commands_ListRemove',
  187. 'lpop' => 'Predis_Commands_ListPopFirst',
  188. 'popFirst' => 'Predis_Commands_ListPopFirst',
  189. 'rpop' => 'Predis_Commands_ListPopLast',
  190. 'popLast' => 'Predis_Commands_ListPopLast',
  191. 'rpoplpush' => 'Predis_Commands_ListPushTailPopFirst',
  192. 'listPopLastPushHead' => 'Predis_Commands_ListPopLastPushHead',
  193. /* commands operating on sets */
  194. 'sadd' => 'Predis_Commands_SetAdd',
  195. 'setAdd' => 'Predis_Commands_SetAdd',
  196. 'srem' => 'Predis_Commands_SetRemove',
  197. 'setRemove' => 'Predis_Commands_SetRemove',
  198. 'spop' => 'Predis_Commands_SetPop',
  199. 'setPop' => 'Predis_Commands_SetPop',
  200. 'smove' => 'Predis_Commands_SetMove',
  201. 'setMove' => 'Predis_Commands_SetMove',
  202. 'scard' => 'Predis_Commands_SetCardinality',
  203. 'setCardinality' => 'Predis_Commands_SetCardinality',
  204. 'sismember' => 'Predis_Commands_SetIsMember',
  205. 'setIsMember' => 'Predis_Commands_SetIsMember',
  206. 'sinter' => 'Predis_Commands_SetIntersection',
  207. 'setIntersection' => 'Predis_Commands_SetIntersection',
  208. 'sinterstore' => 'Predis_Commands_SetIntersectionStore',
  209. 'setIntersectionStore' => 'Predis_Commands_SetIntersectionStore',
  210. 'sunion' => 'Predis_Commands_SetUnion',
  211. 'setUnion' => 'Predis_Commands_SetUnion',
  212. 'sunionstore' => 'Predis_Commands_SetUnionStore',
  213. 'setUnionStore' => 'Predis_Commands_SetUnionStore',
  214. 'sdiff' => 'Predis_Commands_SetDifference',
  215. 'setDifference' => 'Predis_Commands_SetDifference',
  216. 'sdiffstore' => 'Predis_Commands_SetDifferenceStore',
  217. 'setDifferenceStore' => 'Predis_Commands_SetDifferenceStore',
  218. 'smembers' => 'Predis_Commands_SetMembers',
  219. 'setMembers' => 'Predis_Commands_SetMembers',
  220. 'srandmember' => 'Predis_Commands_SetRandomMember',
  221. 'setRandomMember' => 'Predis_Commands_SetRandomMember',
  222. /* commands operating on sorted sets */
  223. 'zadd' => 'Predis_Commands_ZSetAdd',
  224. 'zsetAdd' => 'Predis_Commands_ZSetAdd',
  225. 'zrem' => 'Predis_Commands_ZSetRemove',
  226. 'zsetRemove' => 'Predis_Commands_ZSetRemove',
  227. 'zrange' => 'Predis_Commands_ZSetRange',
  228. 'zsetRange' => 'Predis_Commands_ZSetRange',
  229. 'zrevrange' => 'Predis_Commands_ZSetReverseRange',
  230. 'zsetReverseRange' => 'Predis_Commands_ZSetReverseRange',
  231. 'zrangebyscore' => 'Predis_Commands_ZSetRangeByScore',
  232. 'zsetRangeByScore' => 'Predis_Commands_ZSetRangeByScore',
  233. 'zcard' => 'Predis_Commands_ZSetCardinality',
  234. 'zsetCardinality' => 'Predis_Commands_ZSetCardinality',
  235. 'zscore' => 'Predis_Commands_ZSetScore',
  236. 'zsetScore' => 'Predis_Commands_ZSetScore',
  237. 'zremrangebyscore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  238. 'zsetRemoveRangeByScore' => 'Predis_Commands_ZSetRemoveRangeByScore',
  239. /* multiple databases handling commands */
  240. 'select' => 'Predis_Commands_SelectDatabase',
  241. 'selectDatabase' => 'Predis_Commands_SelectDatabase',
  242. 'move' => 'Predis_Commands_MoveKey',
  243. 'moveKey' => 'Predis_Commands_MoveKey',
  244. 'flushdb' => 'Predis_Commands_FlushDatabase',
  245. 'flushDatabase' => 'Predis_Commands_FlushDatabase',
  246. 'flushall' => 'Predis_Commands_FlushAll',
  247. 'flushDatabases' => 'Predis_Commands_FlushAll',
  248. /* sorting */
  249. 'sort' => 'Predis_Commands_Sort',
  250. /* remote server control commands */
  251. 'info' => 'Predis_Commands_Info',
  252. 'slaveof' => 'Predis_Commands_SlaveOf',
  253. 'slaveOf' => 'Predis_Commands_SlaveOf',
  254. /* persistence control commands */
  255. 'save' => 'Predis_Commands_Save',
  256. 'bgsave' => 'Predis_Commands_BackgroundSave',
  257. 'backgroundSave' => 'Predis_Commands_BackgroundSave',
  258. 'lastsave' => 'Predis_Commands_LastSave',
  259. 'lastSave' => 'Predis_Commands_LastSave',
  260. 'shutdown' => 'Predis_Commands_Shutdown'
  261. );
  262. }
  263. }
  264. /* ------------------------------------------------------------------------- */
  265. abstract class Predis_Command {
  266. private $_arguments;
  267. public abstract function getCommandId();
  268. public abstract function serializeRequest($command, $arguments);
  269. public function canBeHashed() {
  270. return true;
  271. }
  272. public function closesConnection() {
  273. return false;
  274. }
  275. protected function filterArguments(Array $arguments) {
  276. return $arguments;
  277. }
  278. public function setArguments(/* arguments */) {
  279. $this->_arguments = $this->filterArguments(func_get_args());
  280. }
  281. public function setArgumentsArray(Array $arguments) {
  282. $this->_arguments = $this->filterArguments($arguments);
  283. }
  284. protected function getArguments() {
  285. return $this->_arguments !== null ? $this->_arguments : array();
  286. }
  287. public function getArgument($index = 0) {
  288. return $this->_arguments !== null ? $this->_arguments[$index] : null;
  289. }
  290. public function parseResponse($data) {
  291. return $data;
  292. }
  293. public final function invoke() {
  294. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  295. }
  296. }
  297. abstract class Predis_InlineCommand extends Predis_Command {
  298. public function serializeRequest($command, $arguments) {
  299. if (isset($arguments[0]) && is_array($arguments[0])) {
  300. $arguments[0] = implode($arguments[0], ' ');
  301. }
  302. return $command . ' ' . implode($arguments, ' ') . Predis_Response::NEWLINE;
  303. }
  304. }
  305. abstract class Predis_BulkCommand extends Predis_Command {
  306. public function serializeRequest($command, $arguments) {
  307. $data = array_pop($arguments);
  308. if (is_array($data)) {
  309. $data = implode($data, ' ');
  310. }
  311. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  312. Predis_Response::NEWLINE . $data . Predis_Response::NEWLINE;
  313. }
  314. }
  315. abstract class Predis_MultiBulkCommand extends Predis_Command {
  316. public function serializeRequest($command, $arguments) {
  317. $buffer = array();
  318. $cmd_args = null;
  319. if (count($arguments) === 1 && is_array($arguments[0])) {
  320. $cmd_args = array();
  321. foreach ($arguments[0] as $k => $v) {
  322. $cmd_args[] = $k;
  323. $cmd_args[] = $v;
  324. }
  325. }
  326. else {
  327. $cmd_args = $arguments;
  328. }
  329. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Predis_Response::NEWLINE;
  330. $buffer[] = '$' . strlen($command) . Predis_Response::NEWLINE . $command . Predis_Response::NEWLINE;
  331. foreach ($cmd_args as $argument) {
  332. $buffer[] = '$' . strlen($argument) . Predis_Response::NEWLINE . $argument . Predis_Response::NEWLINE;
  333. }
  334. return implode('', $buffer);
  335. }
  336. }
  337. /* ------------------------------------------------------------------------- */
  338. class Predis_Response {
  339. const NEWLINE = "\r\n";
  340. const OK = 'OK';
  341. const ERROR = 'ERR';
  342. const NULL = 'nil';
  343. private static $_prefixHandlers;
  344. private static function initializePrefixHandlers() {
  345. return array(
  346. // status
  347. '+' => array('Predis_Response', 'handleStatus'),
  348. // error
  349. '-' => array('Predis_Response', 'handleError'),
  350. // bulk
  351. '$' => array('Predis_Response', 'handleBulk'),
  352. // multibulk
  353. '*' => array('Predis_Response', 'handleMultiBulk'),
  354. // integer
  355. ':' => array('Predis_Response', 'handleInteger')
  356. );
  357. }
  358. public static function getPrefixHandler($prefix) {
  359. if (self::$_prefixHandlers == null) {
  360. self::$_prefixHandlers = self::initializePrefixHandlers();
  361. }
  362. $handler = self::$_prefixHandlers[$prefix];
  363. if ($handler === null) {
  364. throw new Predis_MalformedServerResponse("Unknown prefix '$prefix'");
  365. }
  366. return $handler;
  367. }
  368. public static function handleStatus($socket) {
  369. $status = rtrim(fgets($socket), Predis_Response::NEWLINE);
  370. return $status === Predis_Response::OK ? true : $status;
  371. }
  372. public static function handleError($socket) {
  373. $errorMessage = rtrim(fgets($socket), Predis_Response::NEWLINE);
  374. throw new Predis_ServerException(substr($errorMessage, 4));
  375. }
  376. public static function handleBulk($socket) {
  377. $dataLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  378. if (!is_numeric($dataLength)) {
  379. throw new Predis_ClientException("Cannot parse '$dataLength' as data length");
  380. }
  381. if ($dataLength > 0) {
  382. $value = stream_get_contents($socket, $dataLength);
  383. fread($socket, 2);
  384. return $value;
  385. }
  386. else if ($dataLength == 0) {
  387. // TODO: I just have a doubt here...
  388. fread($socket, 2);
  389. }
  390. return null;
  391. }
  392. public static function handleMultiBulk($socket) {
  393. $rawLength = rtrim(fgets($socket), Predis_Response::NEWLINE);
  394. if (!is_numeric($rawLength)) {
  395. throw new Predis_ClientException("Cannot parse '$rawLength' as data length");
  396. }
  397. $listLength = (int) $rawLength;
  398. if ($listLength === -1) {
  399. return null;
  400. }
  401. $list = array();
  402. if ($listLength > 0) {
  403. for ($i = 0; $i < $listLength; $i++) {
  404. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  405. $list[] = call_user_func($handler, $socket);
  406. }
  407. }
  408. return $list;
  409. }
  410. public static function handleInteger($socket) {
  411. $number = rtrim(fgets($socket), Predis_Response::NEWLINE);
  412. if (is_numeric($number)) {
  413. return (int) $number;
  414. }
  415. else {
  416. if ($number !== Predis_Response::NULL) {
  417. throw new Predis_ClientException("Cannot parse '$number' as numeric response");
  418. }
  419. return null;
  420. }
  421. }
  422. }
  423. class Predis_CommandPipeline {
  424. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  425. public function __construct(Predis_Client $redisClient) {
  426. $this->_redisClient = $redisClient;
  427. $this->_pipelineBuffer = array();
  428. $this->_returnValues = array();
  429. }
  430. public function __call($method, $arguments) {
  431. $command = $this->_redisClient->createCommandInstance($method, $arguments);
  432. $this->recordCommand($command);
  433. }
  434. private function recordCommand(Predis_Command $command) {
  435. $this->_pipelineBuffer[] = $command;
  436. }
  437. private function getRecordedCommands() {
  438. return $this->_pipelineBuffer;
  439. }
  440. public function flushPipeline() {
  441. if (count($this->_pipelineBuffer) === 0) {
  442. return;
  443. }
  444. $connection = $this->_redisClient->getConnection();
  445. $commands = &$this->getRecordedCommands();
  446. foreach ($commands as $command) {
  447. $connection->writeCommand($command);
  448. }
  449. foreach ($commands as $command) {
  450. $this->_returnValues[] = $connection->readResponse($command);
  451. }
  452. $this->_pipelineBuffer = array();
  453. }
  454. private function setRunning($bool) {
  455. // TODO: I am honest when I say that I don't like this approach.
  456. if ($bool == true && $this->_running == true) {
  457. throw new Predis_ClientException("This pipeline is already opened");
  458. }
  459. $this->_running = $bool;
  460. }
  461. public function execute() {
  462. $this->setRunning(true);
  463. $pipelineBlockException = null;
  464. try {
  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 Predis_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 Predis_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', Predis_Connection::DEFAULT_HOST),
  513. 'port' => (int) self::getParamOrDefault($parameters, 'port', Predis_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 Predis_IConnection {
  523. public function connect();
  524. public function disconnect();
  525. public function isConnected();
  526. public function writeCommand(Predis_Command $command);
  527. public function readResponse(Predis_Command $command);
  528. }
  529. class Predis_Connection implements Predis_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(Predis_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 Predis_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 Predis_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(Predis_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(Predis_Command $command) {
  576. fwrite($this->getSocket(), $command->invoke());
  577. }
  578. public function readResponse(Predis_Command $command) {
  579. $socket = $this->getSocket();
  580. $handler = Predis_Response::getPrefixHandler(fgetc($socket));
  581. $response = $command->parseResponse(call_user_func($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 = Predis_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 Predis_ConnectionCluster implements Predis_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(Predis_Connection $connection) {
  635. $this->_pool[] = $connection;
  636. $this->_ring->add($connection);
  637. }
  638. private function getConnectionFromRing(Predis_Command $command) {
  639. return $this->_ring->get($this->computeHash($command));
  640. }
  641. private function computeHash(Predis_Command $command) {
  642. return crc32($command->getArgument(0));
  643. }
  644. private function getConnection(Predis_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(Predis_Command $command) {
  653. $this->getConnection($command)->writeCommand($command);
  654. }
  655. public function readResponse(Predis_Command $command) {
  656. return $this->getConnection($command)->readResponse($command);
  657. }
  658. }
  659. /* ------------------------------------------------------------------------- */
  660. class Utilities_HashRing {
  661. const DEFAULT_REPLICAS = 128;
  662. private $_ring, $_ringKeys, $_replicas;
  663. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  664. $this->_replicas = $replicas;
  665. $this->_ring = array();
  666. $this->_ringKeys = array();
  667. }
  668. public function add($node) {
  669. $nodeHash = (string) $node;
  670. for ($i = 0; $i < $this->_replicas; $i++) {
  671. $key = crc32($nodeHash . ':' . $i);
  672. $this->_ring[$key] = $node;
  673. }
  674. ksort($this->_ring, SORT_NUMERIC);
  675. $this->_ringKeys = array_keys($this->_ring);
  676. }
  677. public function remove($node) {
  678. $nodeHash = (string) $node;
  679. for ($i = 0; $i < $this->_replicas; $i++) {
  680. $key = crc32($nodeHash . ':' . $i);
  681. unset($this->_ring[$key]);
  682. $newRing = array();
  683. foreach ($this->_ringKeys as $rk) {
  684. if ($rk !== $key) {
  685. $newRing[] = $rk;
  686. }
  687. }
  688. $this->_ringKeys = $newRing;
  689. }
  690. }
  691. public function get($key) {
  692. return $this->_ring[$this->getNodeKey($key)];
  693. }
  694. private function getNodeKey($key) {
  695. $upper = count($this->_ringKeys) - 1;
  696. $lower = 0;
  697. $index = 0;
  698. while ($lower <= $upper) {
  699. $index = ($lower + $upper) / 2;
  700. $item = $this->_ringKeys[$index];
  701. if ($item === $key) {
  702. return $index;
  703. }
  704. else if ($item > $key) {
  705. $upper = $index - 1;
  706. }
  707. else {
  708. $lower = $index + 1;
  709. }
  710. }
  711. return $this->_ringKeys[$upper];
  712. }
  713. }
  714. /* ------------------------------------------------------------------------- */
  715. /* miscellaneous commands */
  716. class Predis_Commands_Ping extends Predis_InlineCommand {
  717. public function canBeHashed() { return false; }
  718. public function getCommandId() { return 'PING'; }
  719. public function parseResponse($data) {
  720. return $data === 'PONG' ? true : false;
  721. }
  722. }
  723. class Predis_Commands_DoEcho extends Predis_BulkCommand {
  724. public function canBeHashed() { return false; }
  725. public function getCommandId() { return 'ECHO'; }
  726. }
  727. class Predis_Commands_Auth extends Predis_InlineCommand {
  728. public function canBeHashed() { return false; }
  729. public function getCommandId() { return 'AUTH'; }
  730. }
  731. /* connection handling */
  732. class Predis_Commands_Quit extends Predis_InlineCommand {
  733. public function canBeHashed() { return false; }
  734. public function getCommandId() { return 'QUIT'; }
  735. public function closesConnection() { return true; }
  736. }
  737. /* commands operating on string values */
  738. class Predis_Commands_Set extends Predis_BulkCommand {
  739. public function getCommandId() { return 'SET'; }
  740. }
  741. class Predis_Commands_SetPreserve extends Predis_BulkCommand {
  742. public function getCommandId() { return 'SETNX'; }
  743. public function parseResponse($data) { return (bool) $data; }
  744. }
  745. class Predis_Commands_SetMultiple extends Predis_MultiBulkCommand {
  746. public function canBeHashed() { return false; }
  747. public function getCommandId() { return 'MSET'; }
  748. }
  749. class Predis_Commands_SetMultiplePreserve extends Predis_MultiBulkCommand {
  750. public function canBeHashed() { return false; }
  751. public function getCommandId() { return 'MSETNX'; }
  752. public function parseResponse($data) { return (bool) $data; }
  753. }
  754. class Predis_Commands_Get extends Predis_InlineCommand {
  755. public function getCommandId() { return 'GET'; }
  756. }
  757. class Predis_Commands_GetMultiple extends Predis_InlineCommand {
  758. public function canBeHashed() { return false; }
  759. public function getCommandId() { return 'MGET'; }
  760. }
  761. class Predis_Commands_GetSet extends Predis_BulkCommand {
  762. public function getCommandId() { return 'GETSET'; }
  763. }
  764. class Predis_Commands_Increment extends Predis_InlineCommand {
  765. public function getCommandId() { return 'INCR'; }
  766. }
  767. class Predis_Commands_IncrementBy extends Predis_InlineCommand {
  768. public function getCommandId() { return 'INCRBY'; }
  769. }
  770. class Predis_Commands_Decrement extends Predis_InlineCommand {
  771. public function getCommandId() { return 'DECR'; }
  772. }
  773. class Predis_Commands_DecrementBy extends Predis_InlineCommand {
  774. public function getCommandId() { return 'DECRBY'; }
  775. }
  776. class Predis_Commands_Exists extends Predis_InlineCommand {
  777. public function getCommandId() { return 'EXISTS'; }
  778. public function parseResponse($data) { return (bool) $data; }
  779. }
  780. class Predis_Commands_Delete extends Predis_InlineCommand {
  781. public function getCommandId() { return 'DEL'; }
  782. public function parseResponse($data) { return (bool) $data; }
  783. }
  784. class Predis_Commands_Type extends Predis_InlineCommand {
  785. public function getCommandId() { return 'TYPE'; }
  786. }
  787. /* commands operating on the key space */
  788. class Predis_Commands_Keys extends Predis_InlineCommand {
  789. public function canBeHashed() { return false; }
  790. public function getCommandId() { return 'KEYS'; }
  791. public function parseResponse($data) {
  792. // TODO: is this behaviour correct?
  793. return strlen($data) > 0 ? explode(' ', $data) : array();
  794. }
  795. }
  796. class Predis_Commands_RandomKey extends Predis_InlineCommand {
  797. public function canBeHashed() { return false; }
  798. public function getCommandId() { return 'RANDOMKEY'; }
  799. public function parseResponse($data) { return $data !== '' ? $data : null; }
  800. }
  801. class Predis_Commands_Rename extends Predis_InlineCommand {
  802. // TODO: doesn't RENAME break the hash-based client-side sharding?
  803. public function canBeHashed() { return false; }
  804. public function getCommandId() { return 'RENAME'; }
  805. }
  806. class Predis_Commands_RenamePreserve extends Predis_InlineCommand {
  807. public function canBeHashed() { return false; }
  808. public function getCommandId() { return 'RENAMENX'; }
  809. public function parseResponse($data) { return (bool) $data; }
  810. }
  811. class Predis_Commands_Expire extends Predis_InlineCommand {
  812. public function getCommandId() { return 'EXPIRE'; }
  813. public function parseResponse($data) { return (bool) $data; }
  814. }
  815. class Predis_Commands_ExpireAt extends Predis_InlineCommand {
  816. public function getCommandId() { return 'EXPIREAT'; }
  817. public function parseResponse($data) { return (bool) $data; }
  818. }
  819. class Predis_Commands_DatabaseSize extends Predis_InlineCommand {
  820. public function canBeHashed() { return false; }
  821. public function getCommandId() { return 'DBSIZE'; }
  822. }
  823. class Predis_Commands_TimeToLive extends Predis_InlineCommand {
  824. public function getCommandId() { return 'TTL'; }
  825. }
  826. /* commands operating on lists */
  827. class Predis_Commands_ListPushTail extends Predis_BulkCommand {
  828. public function getCommandId() { return 'RPUSH'; }
  829. }
  830. class Predis_Commands_ListPushHead extends Predis_BulkCommand {
  831. public function getCommandId() { return 'LPUSH'; }
  832. }
  833. class Predis_Commands_ListLength extends Predis_InlineCommand {
  834. public function getCommandId() { return 'LLEN'; }
  835. }
  836. class Predis_Commands_ListRange extends Predis_InlineCommand {
  837. public function getCommandId() { return 'LRANGE'; }
  838. }
  839. class Predis_Commands_ListTrim extends Predis_InlineCommand {
  840. public function getCommandId() { return 'LTRIM'; }
  841. }
  842. class Predis_Commands_ListIndex extends Predis_InlineCommand {
  843. public function getCommandId() { return 'LINDEX'; }
  844. }
  845. class Predis_Commands_ListSet extends Predis_BulkCommand {
  846. public function getCommandId() { return 'LSET'; }
  847. }
  848. class Predis_Commands_ListRemove extends Predis_BulkCommand {
  849. public function getCommandId() { return 'LREM'; }
  850. }
  851. class Predis_Commands_ListPopLastPushHead extends Predis_BulkCommand {
  852. public function getCommandId() { return 'RPOPLPUSH'; }
  853. }
  854. class Predis_Commands_ListPopFirst extends Predis_InlineCommand {
  855. public function getCommandId() { return 'LPOP'; }
  856. }
  857. class Predis_Commands_ListPopLast extends Predis_InlineCommand {
  858. public function getCommandId() { return 'RPOP'; }
  859. }
  860. /* commands operating on sets */
  861. class Predis_Commands_SetAdd extends Predis_BulkCommand {
  862. public function getCommandId() { return 'SADD'; }
  863. public function parseResponse($data) { return (bool) $data; }
  864. }
  865. class Predis_Commands_SetRemove extends Predis_BulkCommand {
  866. public function getCommandId() { return 'SREM'; }
  867. public function parseResponse($data) { return (bool) $data; }
  868. }
  869. class Predis_Commands_SetPop extends Predis_InlineCommand {
  870. public function getCommandId() { return 'SPOP'; }
  871. }
  872. class Predis_Commands_SetMove extends Predis_BulkCommand {
  873. public function canBeHashed() { return false; }
  874. public function getCommandId() { return 'SMOVE'; }
  875. public function parseResponse($data) { return (bool) $data; }
  876. }
  877. class Predis_Commands_SetCardinality extends Predis_InlineCommand {
  878. public function getCommandId() { return 'SCARD'; }
  879. }
  880. class Predis_Commands_SetIsMember extends Predis_BulkCommand {
  881. public function getCommandId() { return 'SISMEMBER'; }
  882. public function parseResponse($data) { return (bool) $data; }
  883. }
  884. class Predis_Commands_SetIntersection extends Predis_InlineCommand {
  885. public function getCommandId() { return 'SINTER'; }
  886. }
  887. class Predis_Commands_SetIntersectionStore extends Predis_InlineCommand {
  888. public function getCommandId() { return 'SINTERSTORE'; }
  889. }
  890. class Predis_Commands_SetUnion extends Predis_InlineCommand {
  891. public function getCommandId() { return 'SUNION'; }
  892. }
  893. class Predis_Commands_SetUnionStore extends Predis_InlineCommand {
  894. public function getCommandId() { return 'SUNIONSTORE'; }
  895. }
  896. class Predis_Commands_SetDifference extends Predis_InlineCommand {
  897. public function getCommandId() { return 'SDIFF'; }
  898. }
  899. class Predis_Commands_SetDifferenceStore extends Predis_InlineCommand {
  900. public function getCommandId() { return 'SDIFFSTORE'; }
  901. }
  902. class Predis_Commands_SetMembers extends Predis_InlineCommand {
  903. public function getCommandId() { return 'SMEMBERS'; }
  904. }
  905. class Predis_Commands_SetRandomMember extends Predis_InlineCommand {
  906. public function getCommandId() { return 'SRANDMEMBER'; }
  907. }
  908. /* commands operating on sorted sets */
  909. class Predis_Commands_ZSetAdd extends Predis_BulkCommand {
  910. public function getCommandId() { return 'ZADD'; }
  911. public function parseResponse($data) { return (bool) $data; }
  912. }
  913. class Predis_Commands_ZSetRemove extends Predis_BulkCommand {
  914. public function getCommandId() { return 'ZREM'; }
  915. public function parseResponse($data) { return (bool) $data; }
  916. }
  917. class Predis_Commands_ZSetRange extends Predis_InlineCommand {
  918. public function getCommandId() { return 'ZRANGE'; }
  919. }
  920. class Predis_Commands_ZSetReverseRange extends Predis_InlineCommand {
  921. public function getCommandId() { return 'ZREVRANGE'; }
  922. }
  923. class Predis_Commands_ZSetRangeByScore extends Predis_InlineCommand {
  924. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  925. }
  926. class Predis_Commands_ZSetCardinality extends Predis_InlineCommand {
  927. public function getCommandId() { return 'ZCARD'; }
  928. }
  929. class Predis_Commands_ZSetScore extends Predis_BulkCommand {
  930. public function getCommandId() { return 'ZSCORE'; }
  931. }
  932. class Predis_Commands_ZSetRemoveRangeByScore extends Predis_InlineCommand {
  933. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  934. }
  935. /* multiple databases handling commands */
  936. class Predis_Commands_SelectDatabase extends Predis_InlineCommand {
  937. public function canBeHashed() { return false; }
  938. public function getCommandId() { return 'SELECT'; }
  939. }
  940. class Predis_Commands_MoveKey extends Predis_InlineCommand {
  941. public function canBeHashed() { return false; }
  942. public function getCommandId() { return 'MOVE'; }
  943. public function parseResponse($data) { return (bool) $data; }
  944. }
  945. class Predis_Commands_FlushDatabase extends Predis_InlineCommand {
  946. public function canBeHashed() { return false; }
  947. public function getCommandId() { return 'FLUSHDB'; }
  948. }
  949. class Predis_Commands_FlushAll extends Predis_InlineCommand {
  950. public function canBeHashed() { return false; }
  951. public function getCommandId() { return 'FLUSHALL'; }
  952. }
  953. /* sorting */
  954. class Predis_Commands_Sort extends Predis_InlineCommand {
  955. public function getCommandId() { return 'SORT'; }
  956. public function filterArguments($arguments) {
  957. if (count($arguments) === 1) {
  958. return $arguments;
  959. }
  960. // TODO: add more parameters checks
  961. $query = array($arguments[0]);
  962. $sortParams = $arguments[1];
  963. if (isset($sortParams['by'])) {
  964. $query[] = 'BY ' . $sortParams['by'];
  965. }
  966. if (isset($sortParams['get'])) {
  967. $query[] = 'GET ' . $sortParams['get'];
  968. }
  969. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  970. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  971. }
  972. if (isset($sortParams['sort'])) {
  973. $query[] = strtoupper($sortParams['sort']);
  974. }
  975. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  976. $query[] = 'ALPHA';
  977. }
  978. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  979. $query[] = 'STORE ' . $sortParams['store'];
  980. }
  981. return $query;
  982. }
  983. }
  984. /* persistence control commands */
  985. class Predis_Commands_Save extends Predis_InlineCommand {
  986. public function canBeHashed() { return false; }
  987. public function getCommandId() { return 'SAVE'; }
  988. }
  989. class Predis_Commands_BackgroundSave extends Predis_InlineCommand {
  990. public function canBeHashed() { return false; }
  991. public function getCommandId() { return 'BGSAVE'; }
  992. }
  993. class Predis_Commands_LastSave extends Predis_InlineCommand {
  994. public function canBeHashed() { return false; }
  995. public function getCommandId() { return 'LASTSAVE'; }
  996. }
  997. class Predis_Commands_Shutdown extends Predis_InlineCommand {
  998. public function canBeHashed() { return false; }
  999. public function getCommandId() { return 'SHUTDOWN'; }
  1000. public function closesConnection() { return true; }
  1001. }
  1002. /* remote server control commands */
  1003. class Predis_Commands_Info extends Predis_InlineCommand {
  1004. public function canBeHashed() { return false; }
  1005. public function getCommandId() { return 'INFO'; }
  1006. public function parseResponse($data) {
  1007. $info = array();
  1008. $infoLines = explode("\r\n", $data, -1);
  1009. foreach ($infoLines as $row) {
  1010. list($k, $v) = explode(':', $row);
  1011. if (!preg_match('/^db\d+$/', $k)) {
  1012. $info[$k] = $v;
  1013. }
  1014. else {
  1015. $db = array();
  1016. foreach (explode(',', $v) as $dbvar) {
  1017. list($dbvk, $dbvv) = explode('=', $dbvar);
  1018. $db[trim($dbvk)] = $dbvv;
  1019. }
  1020. $info[$k] = $db;
  1021. }
  1022. }
  1023. return $info;
  1024. }
  1025. }
  1026. class SlaveOf extends Predis_InlineCommand {
  1027. public function canBeHashed() { return false; }
  1028. public function getCommandId() { return 'SLAVEOF'; }
  1029. public function filterArguments($arguments) {
  1030. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1031. }
  1032. }
  1033. ?>