Predis.php 42 KB

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