Predis.php 55 KB

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