Predis.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. /* ------------------------------------------------------------------------- */
  697. namespace Predis\Utilities;
  698. class HashRing {
  699. const DEFAULT_REPLICAS = 128;
  700. private $_ring, $_ringKeys, $_replicas;
  701. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  702. $this->_replicas = $replicas;
  703. $this->_ring = array();
  704. $this->_ringKeys = array();
  705. }
  706. public function add($node) {
  707. $nodeHash = (string) $node;
  708. for ($i = 0; $i < $this->_replicas; $i++) {
  709. $key = crc32($nodeHash . ':' . $i);
  710. $this->_ring[$key] = $node;
  711. }
  712. ksort($this->_ring, SORT_NUMERIC);
  713. $this->_ringKeys = array_keys($this->_ring);
  714. }
  715. public function remove($node) {
  716. $nodeHash = (string) $node;
  717. for ($i = 0; $i < $this->_replicas; $i++) {
  718. $key = crc32($nodeHash . ':' . $i);
  719. unset($this->_ring[$key]);
  720. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  721. return $rk !== $key;
  722. });
  723. }
  724. }
  725. public function get($key) {
  726. return $this->_ring[$this->getNodeKey($key)];
  727. }
  728. private function getNodeKey($key) {
  729. $upper = count($this->_ringKeys) - 1;
  730. $lower = 0;
  731. $index = 0;
  732. while ($lower <= $upper) {
  733. $index = ($lower + $upper) / 2;
  734. $item = $this->_ringKeys[$index];
  735. if ($item === $key) {
  736. return $index;
  737. }
  738. else if ($item > $key) {
  739. $upper = $index - 1;
  740. }
  741. else {
  742. $lower = $index + 1;
  743. }
  744. }
  745. return $this->_ringKeys[$upper];
  746. }
  747. }
  748. /* ------------------------------------------------------------------------- */
  749. namespace Predis\Commands;
  750. /* miscellaneous commands */
  751. class Ping extends \Predis\InlineCommand {
  752. public function canBeHashed() { return false; }
  753. public function getCommandId() { return 'PING'; }
  754. public function parseResponse($data) {
  755. return $data === 'PONG' ? true : false;
  756. }
  757. }
  758. class DoEcho extends \Predis\BulkCommand {
  759. public function canBeHashed() { return false; }
  760. public function getCommandId() { return 'ECHO'; }
  761. }
  762. class Auth extends \Predis\InlineCommand {
  763. public function canBeHashed() { return false; }
  764. public function getCommandId() { return 'AUTH'; }
  765. }
  766. /* connection handling */
  767. class Quit extends \Predis\InlineCommand {
  768. public function canBeHashed() { return false; }
  769. public function getCommandId() { return 'QUIT'; }
  770. public function closesConnection() { return true; }
  771. }
  772. /* commands operating on string values */
  773. class Set extends \Predis\BulkCommand {
  774. public function getCommandId() { return 'SET'; }
  775. }
  776. class SetPreserve extends \Predis\BulkCommand {
  777. public function getCommandId() { return 'SETNX'; }
  778. public function parseResponse($data) { return (bool) $data; }
  779. }
  780. class SetMultiple extends \Predis\MultiBulkCommand {
  781. public function canBeHashed() { return false; }
  782. public function getCommandId() { return 'MSET'; }
  783. }
  784. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  785. public function canBeHashed() { return false; }
  786. public function getCommandId() { return 'MSETNX'; }
  787. public function parseResponse($data) { return (bool) $data; }
  788. }
  789. class Get extends \Predis\InlineCommand {
  790. public function getCommandId() { return 'GET'; }
  791. }
  792. class GetMultiple extends \Predis\InlineCommand {
  793. public function canBeHashed() { return false; }
  794. public function getCommandId() { return 'MGET'; }
  795. }
  796. class GetSet extends \Predis\BulkCommand {
  797. public function getCommandId() { return 'GETSET'; }
  798. }
  799. class Increment extends \Predis\InlineCommand {
  800. public function getCommandId() { return 'INCR'; }
  801. }
  802. class IncrementBy extends \Predis\InlineCommand {
  803. public function getCommandId() { return 'INCRBY'; }
  804. }
  805. class Decrement extends \Predis\InlineCommand {
  806. public function getCommandId() { return 'DECR'; }
  807. }
  808. class DecrementBy extends \Predis\InlineCommand {
  809. public function getCommandId() { return 'DECRBY'; }
  810. }
  811. class Exists extends \Predis\InlineCommand {
  812. public function getCommandId() { return 'EXISTS'; }
  813. public function parseResponse($data) { return (bool) $data; }
  814. }
  815. class Delete extends \Predis\InlineCommand {
  816. public function getCommandId() { return 'DEL'; }
  817. public function parseResponse($data) { return (bool) $data; }
  818. }
  819. class Type extends \Predis\InlineCommand {
  820. public function getCommandId() { return 'TYPE'; }
  821. }
  822. /* commands operating on the key space */
  823. class Keys extends \Predis\InlineCommand {
  824. public function canBeHashed() { return false; }
  825. public function getCommandId() { return 'KEYS'; }
  826. public function parseResponse($data) {
  827. // TODO: is this behaviour correct?
  828. return strlen($data) > 0 ? explode(' ', $data) : array();
  829. }
  830. }
  831. class RandomKey extends \Predis\InlineCommand {
  832. public function canBeHashed() { return false; }
  833. public function getCommandId() { return 'RANDOMKEY'; }
  834. public function parseResponse($data) { return $data !== '' ? $data : null; }
  835. }
  836. class Rename extends \Predis\InlineCommand {
  837. // TODO: doesn't RENAME break the hash-based client-side sharding?
  838. public function canBeHashed() { return false; }
  839. public function getCommandId() { return 'RENAME'; }
  840. }
  841. class RenamePreserve extends \Predis\InlineCommand {
  842. public function canBeHashed() { return false; }
  843. public function getCommandId() { return 'RENAMENX'; }
  844. public function parseResponse($data) { return (bool) $data; }
  845. }
  846. class Expire extends \Predis\InlineCommand {
  847. public function getCommandId() { return 'EXPIRE'; }
  848. public function parseResponse($data) { return (bool) $data; }
  849. }
  850. class ExpireAt extends \Predis\InlineCommand {
  851. public function getCommandId() { return 'EXPIREAT'; }
  852. public function parseResponse($data) { return (bool) $data; }
  853. }
  854. class DatabaseSize extends \Predis\InlineCommand {
  855. public function canBeHashed() { return false; }
  856. public function getCommandId() { return 'DBSIZE'; }
  857. }
  858. class TimeToLive extends \Predis\InlineCommand {
  859. public function getCommandId() { return 'TTL'; }
  860. }
  861. /* commands operating on lists */
  862. class ListPushTail extends \Predis\BulkCommand {
  863. public function getCommandId() { return 'RPUSH'; }
  864. }
  865. class ListPushHead extends \Predis\BulkCommand {
  866. public function getCommandId() { return 'LPUSH'; }
  867. }
  868. class ListLength extends \Predis\InlineCommand {
  869. public function getCommandId() { return 'LLEN'; }
  870. }
  871. class ListRange extends \Predis\InlineCommand {
  872. public function getCommandId() { return 'LRANGE'; }
  873. }
  874. class ListTrim extends \Predis\InlineCommand {
  875. public function getCommandId() { return 'LTRIM'; }
  876. }
  877. class ListIndex extends \Predis\InlineCommand {
  878. public function getCommandId() { return 'LINDEX'; }
  879. }
  880. class ListSet extends \Predis\BulkCommand {
  881. public function getCommandId() { return 'LSET'; }
  882. }
  883. class ListRemove extends \Predis\BulkCommand {
  884. public function getCommandId() { return 'LREM'; }
  885. }
  886. class ListPopLastPushHead extends \Predis\BulkCommand {
  887. public function getCommandId() { return 'RPOPLPUSH'; }
  888. }
  889. class ListPopFirst extends \Predis\InlineCommand {
  890. public function getCommandId() { return 'LPOP'; }
  891. }
  892. class ListPopLast extends \Predis\InlineCommand {
  893. public function getCommandId() { return 'RPOP'; }
  894. }
  895. /* commands operating on sets */
  896. class SetAdd extends \Predis\BulkCommand {
  897. public function getCommandId() { return 'SADD'; }
  898. public function parseResponse($data) { return (bool) $data; }
  899. }
  900. class SetRemove extends \Predis\BulkCommand {
  901. public function getCommandId() { return 'SREM'; }
  902. public function parseResponse($data) { return (bool) $data; }
  903. }
  904. class SetPop extends \Predis\InlineCommand {
  905. public function getCommandId() { return 'SPOP'; }
  906. }
  907. class SetMove extends \Predis\BulkCommand {
  908. public function canBeHashed() { return false; }
  909. public function getCommandId() { return 'SMOVE'; }
  910. public function parseResponse($data) { return (bool) $data; }
  911. }
  912. class SetCardinality extends \Predis\InlineCommand {
  913. public function getCommandId() { return 'SCARD'; }
  914. }
  915. class SetIsMember extends \Predis\BulkCommand {
  916. public function getCommandId() { return 'SISMEMBER'; }
  917. public function parseResponse($data) { return (bool) $data; }
  918. }
  919. class SetIntersection extends \Predis\InlineCommand {
  920. public function getCommandId() { return 'SINTER'; }
  921. }
  922. class SetIntersectionStore extends \Predis\InlineCommand {
  923. public function getCommandId() { return 'SINTERSTORE'; }
  924. }
  925. class SetUnion extends \Predis\InlineCommand {
  926. public function getCommandId() { return 'SUNION'; }
  927. }
  928. class SetUnionStore extends \Predis\InlineCommand {
  929. public function getCommandId() { return 'SUNIONSTORE'; }
  930. }
  931. class SetDifference extends \Predis\InlineCommand {
  932. public function getCommandId() { return 'SDIFF'; }
  933. }
  934. class SetDifferenceStore extends \Predis\InlineCommand {
  935. public function getCommandId() { return 'SDIFFSTORE'; }
  936. }
  937. class SetMembers extends \Predis\InlineCommand {
  938. public function getCommandId() { return 'SMEMBERS'; }
  939. }
  940. class SetRandomMember extends \Predis\InlineCommand {
  941. public function getCommandId() { return 'SRANDMEMBER'; }
  942. }
  943. /* commands operating on sorted sets */
  944. class ZSetAdd extends \Predis\BulkCommand {
  945. public function getCommandId() { return 'ZADD'; }
  946. public function parseResponse($data) { return (bool) $data; }
  947. }
  948. class ZSetRemove extends \Predis\BulkCommand {
  949. public function getCommandId() { return 'ZREM'; }
  950. public function parseResponse($data) { return (bool) $data; }
  951. }
  952. class ZSetRange extends \Predis\InlineCommand {
  953. public function getCommandId() { return 'ZRANGE'; }
  954. }
  955. class ZSetReverseRange extends \Predis\InlineCommand {
  956. public function getCommandId() { return 'ZREVRANGE'; }
  957. }
  958. class ZSetRangeByScore extends \Predis\InlineCommand {
  959. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  960. }
  961. class ZSetCardinality extends \Predis\InlineCommand {
  962. public function getCommandId() { return 'ZCARD'; }
  963. }
  964. class ZSetScore extends \Predis\BulkCommand {
  965. public function getCommandId() { return 'ZSCORE'; }
  966. }
  967. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  968. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  969. }
  970. /* multiple databases handling commands */
  971. class SelectDatabase extends \Predis\InlineCommand {
  972. public function canBeHashed() { return false; }
  973. public function getCommandId() { return 'SELECT'; }
  974. }
  975. class MoveKey extends \Predis\InlineCommand {
  976. public function canBeHashed() { return false; }
  977. public function getCommandId() { return 'MOVE'; }
  978. public function parseResponse($data) { return (bool) $data; }
  979. }
  980. class FlushDatabase extends \Predis\InlineCommand {
  981. public function canBeHashed() { return false; }
  982. public function getCommandId() { return 'FLUSHDB'; }
  983. }
  984. class FlushAll extends \Predis\InlineCommand {
  985. public function canBeHashed() { return false; }
  986. public function getCommandId() { return 'FLUSHALL'; }
  987. }
  988. /* sorting */
  989. class Sort extends \Predis\InlineCommand {
  990. public function getCommandId() { return 'SORT'; }
  991. public function filterArguments($arguments) {
  992. if (count($arguments) === 1) {
  993. return $arguments;
  994. }
  995. // TODO: add more parameters checks
  996. $query = array($arguments[0]);
  997. $sortParams = $arguments[1];
  998. if (isset($sortParams['by'])) {
  999. $query[] = 'BY ' . $sortParams['by'];
  1000. }
  1001. if (isset($sortParams['get'])) {
  1002. $query[] = 'GET ' . $sortParams['get'];
  1003. }
  1004. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1005. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1006. }
  1007. if (isset($sortParams['sort'])) {
  1008. $query[] = strtoupper($sortParams['sort']);
  1009. }
  1010. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1011. $query[] = 'ALPHA';
  1012. }
  1013. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1014. $query[] = 'STORE ' . $sortParams['store'];
  1015. }
  1016. return $query;
  1017. }
  1018. }
  1019. /* persistence control commands */
  1020. class Save extends \Predis\InlineCommand {
  1021. public function canBeHashed() { return false; }
  1022. public function getCommandId() { return 'SAVE'; }
  1023. }
  1024. class BackgroundSave extends \Predis\InlineCommand {
  1025. public function canBeHashed() { return false; }
  1026. public function getCommandId() { return 'BGSAVE'; }
  1027. }
  1028. class LastSave extends \Predis\InlineCommand {
  1029. public function canBeHashed() { return false; }
  1030. public function getCommandId() { return 'LASTSAVE'; }
  1031. }
  1032. class Shutdown extends \Predis\InlineCommand {
  1033. public function canBeHashed() { return false; }
  1034. public function getCommandId() { return 'SHUTDOWN'; }
  1035. public function closesConnection() { return true; }
  1036. }
  1037. /* remote server control commands */
  1038. class Info extends \Predis\InlineCommand {
  1039. public function canBeHashed() { return false; }
  1040. public function getCommandId() { return 'INFO'; }
  1041. public function parseResponse($data) {
  1042. $info = array();
  1043. $infoLines = explode("\r\n", $data, -1);
  1044. foreach ($infoLines as $row) {
  1045. list($k, $v) = explode(':', $row);
  1046. if (!preg_match('/^db\d+$/', $k)) {
  1047. $info[$k] = $v;
  1048. }
  1049. else {
  1050. $db = array();
  1051. foreach (explode(',', $v) as $dbvar) {
  1052. list($dbvk, $dbvv) = explode('=', $dbvar);
  1053. $db[trim($dbvk)] = $dbvv;
  1054. }
  1055. $info[$k] = $db;
  1056. }
  1057. }
  1058. return $info;
  1059. }
  1060. }
  1061. class SlaveOf extends \Predis\InlineCommand {
  1062. public function canBeHashed() { return false; }
  1063. public function getCommandId() { return 'SLAVEOF'; }
  1064. public function filterArguments($arguments) {
  1065. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1066. }
  1067. }
  1068. ?>