Predis.php 55 KB

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