Predis.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609
  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;
  400. public function __construct(Client $redisClient) {
  401. $this->_initialized = false;
  402. $this->_redisClient = $redisClient;
  403. $this->_commands = array();
  404. }
  405. private function initialize() {
  406. if ($this->_initialized === false) {
  407. $this->_redisClient->multi();
  408. $this->_initialized = true;
  409. }
  410. }
  411. public function __call($method, $arguments) {
  412. $this->initialize();
  413. $command = $this->_redisClient->createCommand($method, $arguments);
  414. $response = $this->_redisClient->executeCommand($command);
  415. if (isset($response->queued)) {
  416. $this->_commands[] = $command;
  417. return $this;
  418. }
  419. else {
  420. throw new ClientException('The server did not respond with a QUEUED status reply');
  421. }
  422. }
  423. public function execute($block = null) {
  424. if ($block && !is_callable($block)) {
  425. throw new \RuntimeException('Argument passed must be a callable object');
  426. }
  427. $blockException = null;
  428. $returnValues = array();
  429. try {
  430. if ($block !== null) {
  431. $block($this);
  432. }
  433. $execReply = $this->_redisClient->exec();
  434. $commands = &$this->_commands;
  435. $sizeofReplies = count($execReply);
  436. if ($sizeofReplies !== count($commands)) {
  437. // TODO: think of a better exception message
  438. throw new ClientException("Out-of-sync");
  439. }
  440. for ($i = 0; $i < $sizeofReplies; $i++) {
  441. $returnValues[] = $commands[$i]->parseResponse($execReply[$i]);
  442. unset($commands[$i]);
  443. }
  444. }
  445. catch (\Exception $exception) {
  446. $blockException = $exception;
  447. }
  448. if ($blockException !== null) {
  449. throw $blockException;
  450. }
  451. return $returnValues;
  452. }
  453. }
  454. /* ------------------------------------------------------------------------- */
  455. class ConnectionParameters {
  456. const DEFAULT_HOST = '127.0.0.1';
  457. const DEFAULT_PORT = 6379;
  458. const DEFAULT_TIMEOUT = 5;
  459. private $_parameters;
  460. public function __construct($parameters) {
  461. $parameters = $parameters ?: array();
  462. $this->_parameters = is_array($parameters)
  463. ? self::filterConnectionParams($parameters)
  464. : self::parseURI($parameters);
  465. }
  466. private static function parseURI($uri) {
  467. $parsed = @parse_url($uri);
  468. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  469. throw new ClientException("Invalid URI: $uri");
  470. }
  471. if (array_key_exists('query', $parsed)) {
  472. $details = array();
  473. foreach (explode('&', $parsed['query']) as $kv) {
  474. list($k, $v) = explode('=', $kv);
  475. switch ($k) {
  476. case 'database':
  477. $details['database'] = $v;
  478. break;
  479. case 'password':
  480. $details['password'] = $v;
  481. break;
  482. case 'connection_timeout':
  483. $details['connection_timeout'] = $v;
  484. break;
  485. case 'read_write_timeout':
  486. $details['read_write_timeout'] = $v;
  487. break;
  488. case 'alias':
  489. $details['alias'] = $v;
  490. break;
  491. }
  492. }
  493. $parsed = array_merge($parsed, $details);
  494. }
  495. return self::filterConnectionParams($parsed);
  496. }
  497. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  498. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  499. }
  500. private static function filterConnectionParams($parameters) {
  501. return array(
  502. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  503. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  504. 'database' => self::getParamOrDefault($parameters, 'database'),
  505. 'password' => self::getParamOrDefault($parameters, 'password'),
  506. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  507. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  508. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  509. );
  510. }
  511. public function __get($parameter) {
  512. return $this->_parameters[$parameter];
  513. }
  514. public function __isset($parameter) {
  515. return isset($this->_parameters[$parameter]);
  516. }
  517. }
  518. interface IConnection {
  519. public function connect();
  520. public function disconnect();
  521. public function isConnected();
  522. public function writeCommand(Command $command);
  523. public function readResponse(Command $command);
  524. }
  525. class Connection implements IConnection {
  526. private $_params, $_socket, $_initCmds;
  527. public function __construct(ConnectionParameters $parameters) {
  528. $this->_params = $parameters;
  529. $this->_initCmds = array();
  530. }
  531. public function __destruct() {
  532. $this->disconnect();
  533. }
  534. public function isConnected() {
  535. return is_resource($this->_socket);
  536. }
  537. public function connect() {
  538. if ($this->isConnected()) {
  539. throw new ClientException('Connection already estabilished');
  540. }
  541. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  542. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $this->_params->connection_timeout);
  543. if (!$this->_socket) {
  544. throw new ClientException(trim($errstr), $errno);
  545. }
  546. if (isset($this->_params->read_write_timeout)) {
  547. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  548. }
  549. if (count($this->_initCmds) > 0){
  550. $this->sendInitializationCommands();
  551. }
  552. }
  553. public function disconnect() {
  554. if ($this->isConnected()) {
  555. fclose($this->_socket);
  556. }
  557. }
  558. public function pushInitCommand(Command $command){
  559. $this->_initCmds[] = $command;
  560. }
  561. private function sendInitializationCommands() {
  562. foreach ($this->_initCmds as $command) {
  563. $this->writeCommand($command);
  564. }
  565. foreach ($this->_initCmds as $command) {
  566. $this->readResponse($command);
  567. }
  568. }
  569. public function writeCommand(Command $command) {
  570. $written = fwrite($this->getSocket(), $command());
  571. if ($written === false){
  572. throw new ClientException(sprintf(
  573. 'An error has occurred while writing command %s on the network stream'),
  574. $command->getCommandId()
  575. );
  576. }
  577. }
  578. public function readResponse(Command $command) {
  579. $response = Response::read($this->getSocket());
  580. return isset($response->queued) ? $response : $command->parseResponse($response);
  581. }
  582. public function rawCommand($rawCommandData, $closesConnection = false) {
  583. $socket = $this->getSocket();
  584. $written = fwrite($socket, $rawCommandData);
  585. if ($written === false){
  586. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  587. }
  588. if ($closesConnection) {
  589. return;
  590. }
  591. return Response::read($socket);
  592. }
  593. public function getSocket() {
  594. if (!$this->isConnected()) {
  595. $this->connect();
  596. }
  597. return $this->_socket;
  598. }
  599. public function getAlias() {
  600. return $this->_params->alias;
  601. }
  602. public function __toString() {
  603. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  604. }
  605. }
  606. class ConnectionCluster implements IConnection, \IteratorAggregate {
  607. // TODO: find a clean way to handle connection failures of single nodes.
  608. private $_pool, $_ring;
  609. public function __construct() {
  610. $this->_pool = array();
  611. $this->_ring = new Utilities\HashRing();
  612. }
  613. public function __destruct() {
  614. $this->disconnect();
  615. }
  616. public function isConnected() {
  617. foreach ($this->_pool as $connection) {
  618. if ($connection->isConnected()) {
  619. return true;
  620. }
  621. }
  622. return false;
  623. }
  624. public function connect() {
  625. foreach ($this->_pool as $connection) {
  626. $connection->connect();
  627. }
  628. }
  629. public function disconnect() {
  630. foreach ($this->_pool as $connection) {
  631. $connection->disconnect();
  632. }
  633. }
  634. public function add(Connection $connection) {
  635. $connectionAlias = $connection->getAlias();
  636. if (isset($connectionAlias)) {
  637. $this->_pool[$connectionAlias] = $connection;
  638. }
  639. else {
  640. $this->_pool[] = $connection;
  641. }
  642. $this->_ring->add($connection);
  643. }
  644. private function getConnection(Command $command) {
  645. if ($command->canBeHashed() === false) {
  646. throw new ClientException(
  647. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  648. );
  649. }
  650. return $this->_ring->get($command->getHash());
  651. }
  652. public function getConnectionById($id = null) {
  653. return $this->_pool[$id ?: 0];
  654. }
  655. public function getIterator() {
  656. return new \ArrayIterator($this->_pool);
  657. }
  658. public function writeCommand(Command $command) {
  659. $this->getConnection($command)->writeCommand($command);
  660. }
  661. public function readResponse(Command $command) {
  662. return $this->getConnection($command)->readResponse($command);
  663. }
  664. }
  665. /* ------------------------------------------------------------------------- */
  666. abstract class RedisServerProfile {
  667. private static $_serverProfiles;
  668. private $_registeredCommands;
  669. public function __construct() {
  670. $this->_registeredCommands = $this->getSupportedCommands();
  671. }
  672. public abstract function getVersion();
  673. protected abstract function getSupportedCommands();
  674. public static function getDefault() {
  675. return self::get('default');
  676. }
  677. private static function predisServerProfiles() {
  678. return array(
  679. '1.0' => '\Predis\RedisServer_v1_0',
  680. '1.2' => '\Predis\RedisServer_v1_2',
  681. 'default' => '\Predis\RedisServer_v1_2',
  682. 'dev' => '\Predis\RedisServer_vNext',
  683. );
  684. }
  685. public static function get($version) {
  686. if (!isset(self::$_serverProfiles)) {
  687. self::$_serverProfiles = self::predisServerProfiles();
  688. }
  689. if (!isset(self::$_serverProfiles[$version])) {
  690. throw new ClientException("Unknown server profile: $version");
  691. }
  692. $profile = self::$_serverProfiles[$version];
  693. return new $profile();
  694. }
  695. public function compareWith($version, $operator = null) {
  696. // one could expect that PHP's version_compare would behave
  697. // the same way if invoked with 2 arguments or 3 arguments
  698. // with the third being NULL, but it is not like that.
  699. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  700. // we might need to revise the behavior of this method.
  701. return ($operator === null
  702. ? version_compare($this, $version)
  703. : version_compare($this, $version, $operator)
  704. );
  705. }
  706. public function supportsCommand($command) {
  707. return isset($this->_registeredCommands[$command]);
  708. }
  709. public function createCommand($method, $arguments = array()) {
  710. if (!isset($this->_registeredCommands[$method])) {
  711. throw new ClientException("'$method' is not a registered Redis command");
  712. }
  713. $commandClass = $this->_registeredCommands[$method];
  714. $command = new $commandClass();
  715. $command->setArgumentsArray($arguments);
  716. return $command;
  717. }
  718. public function registerCommands(Array $commands) {
  719. foreach ($commands as $command => $aliases) {
  720. $this->registerCommand($command, $aliases);
  721. }
  722. }
  723. public function registerCommand($command, $aliases) {
  724. $commandReflection = new \ReflectionClass($command);
  725. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  726. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  727. }
  728. if (is_array($aliases)) {
  729. foreach ($aliases as $alias) {
  730. $this->_registeredCommands[$alias] = $command;
  731. }
  732. }
  733. else {
  734. $this->_registeredCommands[$aliases] = $command;
  735. }
  736. }
  737. public function __toString() {
  738. return $this->getVersion();
  739. }
  740. }
  741. class RedisServer_v1_0 extends RedisServerProfile {
  742. public function getVersion() { return '1.0'; }
  743. public function getSupportedCommands() {
  744. return array(
  745. /* miscellaneous commands */
  746. 'ping' => '\Predis\Commands\Ping',
  747. 'echo' => '\Predis\Commands\DoEcho',
  748. 'auth' => '\Predis\Commands\Auth',
  749. /* connection handling */
  750. 'quit' => '\Predis\Commands\Quit',
  751. /* commands operating on string values */
  752. 'set' => '\Predis\Commands\Set',
  753. 'setnx' => '\Predis\Commands\SetPreserve',
  754. 'setPreserve' => '\Predis\Commands\SetPreserve',
  755. 'get' => '\Predis\Commands\Get',
  756. 'mget' => '\Predis\Commands\GetMultiple',
  757. 'getMultiple' => '\Predis\Commands\GetMultiple',
  758. 'getset' => '\Predis\Commands\GetSet',
  759. 'getSet' => '\Predis\Commands\GetSet',
  760. 'incr' => '\Predis\Commands\Increment',
  761. 'increment' => '\Predis\Commands\Increment',
  762. 'incrby' => '\Predis\Commands\IncrementBy',
  763. 'incrementBy' => '\Predis\Commands\IncrementBy',
  764. 'decr' => '\Predis\Commands\Decrement',
  765. 'decrement' => '\Predis\Commands\Decrement',
  766. 'decrby' => '\Predis\Commands\DecrementBy',
  767. 'decrementBy' => '\Predis\Commands\DecrementBy',
  768. 'exists' => '\Predis\Commands\Exists',
  769. 'del' => '\Predis\Commands\Delete',
  770. 'delete' => '\Predis\Commands\Delete',
  771. 'type' => '\Predis\Commands\Type',
  772. /* commands operating on the key space */
  773. 'keys' => '\Predis\Commands\Keys',
  774. 'randomkey' => '\Predis\Commands\RandomKey',
  775. 'randomKey' => '\Predis\Commands\RandomKey',
  776. 'rename' => '\Predis\Commands\Rename',
  777. 'renamenx' => '\Predis\Commands\RenamePreserve',
  778. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  779. 'expire' => '\Predis\Commands\Expire',
  780. 'expireat' => '\Predis\Commands\ExpireAt',
  781. 'expireAt' => '\Predis\Commands\ExpireAt',
  782. 'dbsize' => '\Predis\Commands\DatabaseSize',
  783. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  784. 'ttl' => '\Predis\Commands\TimeToLive',
  785. 'timeToLive' => '\Predis\Commands\TimeToLive',
  786. /* commands operating on lists */
  787. 'rpush' => '\Predis\Commands\ListPushTail',
  788. 'pushTail' => '\Predis\Commands\ListPushTail',
  789. 'lpush' => '\Predis\Commands\ListPushHead',
  790. 'pushHead' => '\Predis\Commands\ListPushHead',
  791. 'llen' => '\Predis\Commands\ListLength',
  792. 'listLength' => '\Predis\Commands\ListLength',
  793. 'lrange' => '\Predis\Commands\ListRange',
  794. 'listRange' => '\Predis\Commands\ListRange',
  795. 'ltrim' => '\Predis\Commands\ListTrim',
  796. 'listTrim' => '\Predis\Commands\ListTrim',
  797. 'lindex' => '\Predis\Commands\ListIndex',
  798. 'listIndex' => '\Predis\Commands\ListIndex',
  799. 'lset' => '\Predis\Commands\ListSet',
  800. 'listSet' => '\Predis\Commands\ListSet',
  801. 'lrem' => '\Predis\Commands\ListRemove',
  802. 'listRemove' => '\Predis\Commands\ListRemove',
  803. 'lpop' => '\Predis\Commands\ListPopFirst',
  804. 'popFirst' => '\Predis\Commands\ListPopFirst',
  805. 'rpop' => '\Predis\Commands\ListPopLast',
  806. 'popLast' => '\Predis\Commands\ListPopLast',
  807. /* commands operating on sets */
  808. 'sadd' => '\Predis\Commands\SetAdd',
  809. 'setAdd' => '\Predis\Commands\SetAdd',
  810. 'srem' => '\Predis\Commands\SetRemove',
  811. 'setRemove' => '\Predis\Commands\SetRemove',
  812. 'spop' => '\Predis\Commands\SetPop',
  813. 'setPop' => '\Predis\Commands\SetPop',
  814. 'smove' => '\Predis\Commands\SetMove',
  815. 'setMove' => '\Predis\Commands\SetMove',
  816. 'scard' => '\Predis\Commands\SetCardinality',
  817. 'setCardinality' => '\Predis\Commands\SetCardinality',
  818. 'sismember' => '\Predis\Commands\SetIsMember',
  819. 'setIsMember' => '\Predis\Commands\SetIsMember',
  820. 'sinter' => '\Predis\Commands\SetIntersection',
  821. 'setIntersection' => '\Predis\Commands\SetIntersection',
  822. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  823. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  824. 'sunion' => '\Predis\Commands\SetUnion',
  825. 'setUnion' => '\Predis\Commands\SetUnion',
  826. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  827. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  828. 'sdiff' => '\Predis\Commands\SetDifference',
  829. 'setDifference' => '\Predis\Commands\SetDifference',
  830. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  831. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  832. 'smembers' => '\Predis\Commands\SetMembers',
  833. 'setMembers' => '\Predis\Commands\SetMembers',
  834. 'srandmember' => '\Predis\Commands\SetRandomMember',
  835. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  836. /* multiple databases handling commands */
  837. 'select' => '\Predis\Commands\SelectDatabase',
  838. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  839. 'move' => '\Predis\Commands\MoveKey',
  840. 'moveKey' => '\Predis\Commands\MoveKey',
  841. 'flushdb' => '\Predis\Commands\FlushDatabase',
  842. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  843. 'flushall' => '\Predis\Commands\FlushAll',
  844. 'flushDatabases' => '\Predis\Commands\FlushAll',
  845. /* sorting */
  846. 'sort' => '\Predis\Commands\Sort',
  847. /* remote server control commands */
  848. 'info' => '\Predis\Commands\Info',
  849. 'slaveof' => '\Predis\Commands\SlaveOf',
  850. 'slaveOf' => '\Predis\Commands\SlaveOf',
  851. /* persistence control commands */
  852. 'save' => '\Predis\Commands\Save',
  853. 'bgsave' => '\Predis\Commands\BackgroundSave',
  854. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  855. 'lastsave' => '\Predis\Commands\LastSave',
  856. 'lastSave' => '\Predis\Commands\LastSave',
  857. 'shutdown' => '\Predis\Commands\Shutdown',
  858. );
  859. }
  860. }
  861. class RedisServer_v1_2 extends RedisServer_v1_0 {
  862. public function getVersion() { return '1.2'; }
  863. public function getSupportedCommands() {
  864. return array_merge(parent::getSupportedCommands(), array(
  865. /* commands operating on string values */
  866. 'mset' => '\Predis\Commands\SetMultiple',
  867. 'setMultiple' => '\Predis\Commands\SetMultiple',
  868. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  869. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  870. /* commands operating on lists */
  871. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  872. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  873. /* commands operating on sorted sets */
  874. 'zadd' => '\Predis\Commands\ZSetAdd',
  875. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  876. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  877. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  878. 'zrem' => '\Predis\Commands\ZSetRemove',
  879. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  880. 'zrange' => '\Predis\Commands\ZSetRange',
  881. 'zsetRange' => '\Predis\Commands\ZSetRange',
  882. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  883. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  884. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  885. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  886. 'zcard' => '\Predis\Commands\ZSetCardinality',
  887. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  888. 'zscore' => '\Predis\Commands\ZSetScore',
  889. 'zsetScore' => '\Predis\Commands\ZSetScore',
  890. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  891. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  892. /* persistence control commands */
  893. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  894. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  895. ));
  896. }
  897. }
  898. class RedisServer_vNext extends RedisServer_v1_2 {
  899. public function getVersion() { return '1.3'; }
  900. public function getSupportedCommands() {
  901. return array_merge(parent::getSupportedCommands(), array(
  902. /* miscellaneous commands */
  903. 'multi' => '\Predis\Commands\Multi',
  904. 'exec' => '\Predis\Commands\Exec',
  905. /* commands operating on lists */
  906. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  907. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  908. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  909. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  910. ));
  911. }
  912. }
  913. /* ------------------------------------------------------------------------- */
  914. namespace Predis\Utilities;
  915. class HashRing {
  916. const DEFAULT_REPLICAS = 128;
  917. private $_ring, $_ringKeys, $_replicas;
  918. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  919. $this->_replicas = $replicas;
  920. $this->_ring = array();
  921. $this->_ringKeys = array();
  922. }
  923. public function add($node) {
  924. $nodeHash = (string) $node;
  925. $replicas = $this->_replicas;
  926. for ($i = 0; $i < $replicas; $i++) {
  927. $key = crc32($nodeHash . ':' . $i);
  928. $this->_ring[$key] = $node;
  929. }
  930. ksort($this->_ring, SORT_NUMERIC);
  931. $this->_ringKeys = array_keys($this->_ring);
  932. }
  933. public function remove($node) {
  934. $nodeHash = (string) $node;
  935. $replicas = $this->_replicas;
  936. for ($i = 0; $i < $replicas; $i++) {
  937. $key = crc32($nodeHash . ':' . $i);
  938. unset($this->_ring[$key]);
  939. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  940. return $rk !== $key;
  941. });
  942. }
  943. }
  944. public function get($key) {
  945. return $this->_ring[$this->getNodeKey($key)];
  946. }
  947. private function getNodeKey($key) {
  948. $ringKeys = $this->_ringKeys;
  949. $upper = count($ringKeys) - 1;
  950. $lower = 0;
  951. $index = 0;
  952. while ($lower <= $upper) {
  953. $index = ($lower + $upper) / 2;
  954. $item = $ringKeys[$index];
  955. if ($item > $key) {
  956. $upper = $index - 1;
  957. }
  958. else if ($item < $key) {
  959. $lower = $index + 1;
  960. }
  961. else {
  962. return $index;
  963. }
  964. }
  965. return $ringKeys[$upper];
  966. }
  967. }
  968. /* ------------------------------------------------------------------------- */
  969. namespace Predis\Commands;
  970. /* miscellaneous commands */
  971. class Ping extends \Predis\InlineCommand {
  972. public function canBeHashed() { return false; }
  973. public function getCommandId() { return 'PING'; }
  974. public function parseResponse($data) {
  975. return $data === 'PONG' ? true : false;
  976. }
  977. }
  978. class DoEcho extends \Predis\BulkCommand {
  979. public function canBeHashed() { return false; }
  980. public function getCommandId() { return 'ECHO'; }
  981. }
  982. class Auth extends \Predis\InlineCommand {
  983. public function canBeHashed() { return false; }
  984. public function getCommandId() { return 'AUTH'; }
  985. }
  986. /* connection handling */
  987. class Quit extends \Predis\InlineCommand {
  988. public function canBeHashed() { return false; }
  989. public function getCommandId() { return 'QUIT'; }
  990. public function closesConnection() { return true; }
  991. }
  992. /* commands operating on string values */
  993. class Set extends \Predis\BulkCommand {
  994. public function getCommandId() { return 'SET'; }
  995. }
  996. class SetPreserve extends \Predis\BulkCommand {
  997. public function getCommandId() { return 'SETNX'; }
  998. public function parseResponse($data) { return (bool) $data; }
  999. }
  1000. class SetMultiple extends \Predis\MultiBulkCommand {
  1001. public function canBeHashed() { return false; }
  1002. public function getCommandId() { return 'MSET'; }
  1003. }
  1004. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1005. public function canBeHashed() { return false; }
  1006. public function getCommandId() { return 'MSETNX'; }
  1007. public function parseResponse($data) { return (bool) $data; }
  1008. }
  1009. class Get extends \Predis\InlineCommand {
  1010. public function getCommandId() { return 'GET'; }
  1011. }
  1012. class GetMultiple extends \Predis\InlineCommand {
  1013. public function canBeHashed() { return false; }
  1014. public function getCommandId() { return 'MGET'; }
  1015. }
  1016. class GetSet extends \Predis\BulkCommand {
  1017. public function getCommandId() { return 'GETSET'; }
  1018. }
  1019. class Increment extends \Predis\InlineCommand {
  1020. public function getCommandId() { return 'INCR'; }
  1021. }
  1022. class IncrementBy extends \Predis\InlineCommand {
  1023. public function getCommandId() { return 'INCRBY'; }
  1024. }
  1025. class Decrement extends \Predis\InlineCommand {
  1026. public function getCommandId() { return 'DECR'; }
  1027. }
  1028. class DecrementBy extends \Predis\InlineCommand {
  1029. public function getCommandId() { return 'DECRBY'; }
  1030. }
  1031. class Exists extends \Predis\InlineCommand {
  1032. public function getCommandId() { return 'EXISTS'; }
  1033. public function parseResponse($data) { return (bool) $data; }
  1034. }
  1035. class Delete extends \Predis\InlineCommand {
  1036. public function getCommandId() { return 'DEL'; }
  1037. public function parseResponse($data) { return (bool) $data; }
  1038. }
  1039. class Type extends \Predis\InlineCommand {
  1040. public function getCommandId() { return 'TYPE'; }
  1041. }
  1042. /* commands operating on the key space */
  1043. class Keys extends \Predis\InlineCommand {
  1044. public function canBeHashed() { return false; }
  1045. public function getCommandId() { return 'KEYS'; }
  1046. public function parseResponse($data) {
  1047. // TODO: is this behaviour correct?
  1048. return strlen($data) > 0 ? explode(' ', $data) : array();
  1049. }
  1050. }
  1051. class RandomKey extends \Predis\InlineCommand {
  1052. public function canBeHashed() { return false; }
  1053. public function getCommandId() { return 'RANDOMKEY'; }
  1054. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1055. }
  1056. class Rename extends \Predis\InlineCommand {
  1057. public function canBeHashed() { return false; }
  1058. public function getCommandId() { return 'RENAME'; }
  1059. }
  1060. class RenamePreserve extends \Predis\InlineCommand {
  1061. public function canBeHashed() { return false; }
  1062. public function getCommandId() { return 'RENAMENX'; }
  1063. public function parseResponse($data) { return (bool) $data; }
  1064. }
  1065. class Expire extends \Predis\InlineCommand {
  1066. public function getCommandId() { return 'EXPIRE'; }
  1067. public function parseResponse($data) { return (bool) $data; }
  1068. }
  1069. class ExpireAt extends \Predis\InlineCommand {
  1070. public function getCommandId() { return 'EXPIREAT'; }
  1071. public function parseResponse($data) { return (bool) $data; }
  1072. }
  1073. class DatabaseSize extends \Predis\InlineCommand {
  1074. public function canBeHashed() { return false; }
  1075. public function getCommandId() { return 'DBSIZE'; }
  1076. }
  1077. class TimeToLive extends \Predis\InlineCommand {
  1078. public function getCommandId() { return 'TTL'; }
  1079. }
  1080. /* commands operating on lists */
  1081. class ListPushTail extends \Predis\BulkCommand {
  1082. public function getCommandId() { return 'RPUSH'; }
  1083. }
  1084. class ListPushHead extends \Predis\BulkCommand {
  1085. public function getCommandId() { return 'LPUSH'; }
  1086. }
  1087. class ListLength extends \Predis\InlineCommand {
  1088. public function getCommandId() { return 'LLEN'; }
  1089. }
  1090. class ListRange extends \Predis\InlineCommand {
  1091. public function getCommandId() { return 'LRANGE'; }
  1092. }
  1093. class ListTrim extends \Predis\InlineCommand {
  1094. public function getCommandId() { return 'LTRIM'; }
  1095. }
  1096. class ListIndex extends \Predis\InlineCommand {
  1097. public function getCommandId() { return 'LINDEX'; }
  1098. }
  1099. class ListSet extends \Predis\BulkCommand {
  1100. public function getCommandId() { return 'LSET'; }
  1101. }
  1102. class ListRemove extends \Predis\BulkCommand {
  1103. public function getCommandId() { return 'LREM'; }
  1104. }
  1105. class ListPopLastPushHead extends \Predis\InlineCommand {
  1106. public function getCommandId() { return 'RPOPLPUSH'; }
  1107. }
  1108. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1109. public function getCommandId() { return 'RPOPLPUSH'; }
  1110. }
  1111. class ListPopFirst extends \Predis\InlineCommand {
  1112. public function getCommandId() { return 'LPOP'; }
  1113. }
  1114. class ListPopLast extends \Predis\InlineCommand {
  1115. public function getCommandId() { return 'RPOP'; }
  1116. }
  1117. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1118. public function getCommandId() { return 'BLPOP'; }
  1119. }
  1120. class ListPopLastBlocking extends \Predis\InlineCommand {
  1121. public function getCommandId() { return 'BRPOP'; }
  1122. }
  1123. /* commands operating on sets */
  1124. class SetAdd extends \Predis\BulkCommand {
  1125. public function getCommandId() { return 'SADD'; }
  1126. public function parseResponse($data) { return (bool) $data; }
  1127. }
  1128. class SetRemove extends \Predis\BulkCommand {
  1129. public function getCommandId() { return 'SREM'; }
  1130. public function parseResponse($data) { return (bool) $data; }
  1131. }
  1132. class SetPop extends \Predis\InlineCommand {
  1133. public function getCommandId() { return 'SPOP'; }
  1134. }
  1135. class SetMove extends \Predis\BulkCommand {
  1136. public function canBeHashed() { return false; }
  1137. public function getCommandId() { return 'SMOVE'; }
  1138. public function parseResponse($data) { return (bool) $data; }
  1139. }
  1140. class SetCardinality extends \Predis\InlineCommand {
  1141. public function getCommandId() { return 'SCARD'; }
  1142. }
  1143. class SetIsMember extends \Predis\BulkCommand {
  1144. public function getCommandId() { return 'SISMEMBER'; }
  1145. public function parseResponse($data) { return (bool) $data; }
  1146. }
  1147. class SetIntersection extends \Predis\InlineCommand {
  1148. public function getCommandId() { return 'SINTER'; }
  1149. }
  1150. class SetIntersectionStore extends \Predis\InlineCommand {
  1151. public function getCommandId() { return 'SINTERSTORE'; }
  1152. }
  1153. class SetUnion extends \Predis\InlineCommand {
  1154. public function getCommandId() { return 'SUNION'; }
  1155. }
  1156. class SetUnionStore extends \Predis\InlineCommand {
  1157. public function getCommandId() { return 'SUNIONSTORE'; }
  1158. }
  1159. class SetDifference extends \Predis\InlineCommand {
  1160. public function getCommandId() { return 'SDIFF'; }
  1161. }
  1162. class SetDifferenceStore extends \Predis\InlineCommand {
  1163. public function getCommandId() { return 'SDIFFSTORE'; }
  1164. }
  1165. class SetMembers extends \Predis\InlineCommand {
  1166. public function getCommandId() { return 'SMEMBERS'; }
  1167. }
  1168. class SetRandomMember extends \Predis\InlineCommand {
  1169. public function getCommandId() { return 'SRANDMEMBER'; }
  1170. }
  1171. /* commands operating on sorted sets */
  1172. class ZSetAdd extends \Predis\BulkCommand {
  1173. public function getCommandId() { return 'ZADD'; }
  1174. public function parseResponse($data) { return (bool) $data; }
  1175. }
  1176. class ZSetIncrementBy extends \Predis\BulkCommand {
  1177. public function getCommandId() { return 'ZINCRBY'; }
  1178. }
  1179. class ZSetRemove extends \Predis\BulkCommand {
  1180. public function getCommandId() { return 'ZREM'; }
  1181. public function parseResponse($data) { return (bool) $data; }
  1182. }
  1183. class ZSetRange extends \Predis\InlineCommand {
  1184. public function getCommandId() { return 'ZRANGE'; }
  1185. public function parseResponse($data) {
  1186. $arguments = $this->getArguments();
  1187. if (count($arguments) === 4) {
  1188. if (strtolower($arguments[3]) === 'withscores') {
  1189. $result = array();
  1190. for ($i = 0; $i < count($data); $i++) {
  1191. $result[] = array($data[$i], $data[++$i]);
  1192. }
  1193. return $result;
  1194. }
  1195. }
  1196. return $data;
  1197. }
  1198. }
  1199. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1200. public function getCommandId() { return 'ZREVRANGE'; }
  1201. }
  1202. class ZSetRangeByScore extends \Predis\InlineCommand {
  1203. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1204. }
  1205. class ZSetCardinality extends \Predis\InlineCommand {
  1206. public function getCommandId() { return 'ZCARD'; }
  1207. }
  1208. class ZSetScore extends \Predis\BulkCommand {
  1209. public function getCommandId() { return 'ZSCORE'; }
  1210. }
  1211. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1212. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1213. }
  1214. /* multiple databases handling commands */
  1215. class SelectDatabase extends \Predis\InlineCommand {
  1216. public function canBeHashed() { return false; }
  1217. public function getCommandId() { return 'SELECT'; }
  1218. }
  1219. class MoveKey extends \Predis\InlineCommand {
  1220. public function canBeHashed() { return false; }
  1221. public function getCommandId() { return 'MOVE'; }
  1222. public function parseResponse($data) { return (bool) $data; }
  1223. }
  1224. class FlushDatabase extends \Predis\InlineCommand {
  1225. public function canBeHashed() { return false; }
  1226. public function getCommandId() { return 'FLUSHDB'; }
  1227. }
  1228. class FlushAll extends \Predis\InlineCommand {
  1229. public function canBeHashed() { return false; }
  1230. public function getCommandId() { return 'FLUSHALL'; }
  1231. }
  1232. /* sorting */
  1233. class Sort extends \Predis\InlineCommand {
  1234. public function getCommandId() { return 'SORT'; }
  1235. public function filterArguments(Array $arguments) {
  1236. if (count($arguments) === 1) {
  1237. return $arguments;
  1238. }
  1239. // TODO: add more parameters checks
  1240. $query = array($arguments[0]);
  1241. $sortParams = $arguments[1];
  1242. if (isset($sortParams['by'])) {
  1243. $query[] = 'BY ' . $sortParams['by'];
  1244. }
  1245. if (isset($sortParams['get'])) {
  1246. $getargs = $sortParams['get'];
  1247. if (is_array($getargs)) {
  1248. foreach ($getargs as $getarg) {
  1249. $query[] = 'GET ' . $getarg;
  1250. }
  1251. }
  1252. else {
  1253. $query[] = 'GET ' . $getargs;
  1254. }
  1255. }
  1256. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1257. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1258. }
  1259. if (isset($sortParams['sort'])) {
  1260. $query[] = strtoupper($sortParams['sort']);
  1261. }
  1262. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1263. $query[] = 'ALPHA';
  1264. }
  1265. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1266. $query[] = 'STORE ' . $sortParams['store'];
  1267. }
  1268. return $query;
  1269. }
  1270. }
  1271. /* persistence control commands */
  1272. class Save extends \Predis\InlineCommand {
  1273. public function canBeHashed() { return false; }
  1274. public function getCommandId() { return 'SAVE'; }
  1275. }
  1276. class BackgroundSave extends \Predis\InlineCommand {
  1277. public function canBeHashed() { return false; }
  1278. public function getCommandId() { return 'BGSAVE'; }
  1279. public function parseResponse($data) {
  1280. if ($data == 'Background saving started') {
  1281. return true;
  1282. }
  1283. return $data;
  1284. }
  1285. }
  1286. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1287. public function canBeHashed() { return false; }
  1288. public function getCommandId() { return 'BGREWRITEAOF'; }
  1289. public function parseResponse($data) {
  1290. return $data == 'Background append only file rewriting started';
  1291. }
  1292. }
  1293. class LastSave extends \Predis\InlineCommand {
  1294. public function canBeHashed() { return false; }
  1295. public function getCommandId() { return 'LASTSAVE'; }
  1296. }
  1297. class Shutdown extends \Predis\InlineCommand {
  1298. public function canBeHashed() { return false; }
  1299. public function getCommandId() { return 'SHUTDOWN'; }
  1300. public function closesConnection() { return true; }
  1301. }
  1302. /* remote server control commands */
  1303. class Info extends \Predis\InlineCommand {
  1304. public function canBeHashed() { return false; }
  1305. public function getCommandId() { return 'INFO'; }
  1306. public function parseResponse($data) {
  1307. $info = array();
  1308. $infoLines = explode("\r\n", $data, -1);
  1309. foreach ($infoLines as $row) {
  1310. list($k, $v) = explode(':', $row);
  1311. if (!preg_match('/^db\d+$/', $k)) {
  1312. $info[$k] = $v;
  1313. }
  1314. else {
  1315. $db = array();
  1316. foreach (explode(',', $v) as $dbvar) {
  1317. list($dbvk, $dbvv) = explode('=', $dbvar);
  1318. $db[trim($dbvk)] = $dbvv;
  1319. }
  1320. $info[$k] = $db;
  1321. }
  1322. }
  1323. return $info;
  1324. }
  1325. }
  1326. class SlaveOf extends \Predis\InlineCommand {
  1327. public function canBeHashed() { return false; }
  1328. public function getCommandId() { return 'SLAVEOF'; }
  1329. public function filterArguments(Array $arguments) {
  1330. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1331. }
  1332. }
  1333. class Multi extends \Predis\InlineCommand {
  1334. public function canBeHashed() { return false; }
  1335. public function getCommandId() { return 'MULTI'; }
  1336. }
  1337. class Exec extends \Predis\InlineCommand {
  1338. public function canBeHashed() { return false; }
  1339. public function getCommandId() { return 'EXEC'; }
  1340. }
  1341. ?>