Predis.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { } // Client-side errors
  5. class ServerException extends PredisException { } // Server-side errors
  6. class CommunicationException extends PredisException { // Communication errors
  7. private $_connection;
  8. public function __construct($message, Connection $connection, $code = null) {
  9. $this->_connection = $connection;
  10. parent::__construct($message, $code);
  11. }
  12. public function getConnection() { return $this->_connection; }
  13. public function shouldResetConnection() { return true; }
  14. }
  15. class MalformedServerResponse extends CommunicationException { // Unexpected responses
  16. public function shouldResetConnection() { return false; }
  17. }
  18. /* ------------------------------------------------------------------------- */
  19. class Client {
  20. private $_connection, $_serverProfile, $_responseReader;
  21. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  22. $this->_responseReader = new ResponseReader();
  23. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  24. $this->setupConnection($parameters);
  25. }
  26. public static function create(/* arguments */) {
  27. $argv = func_get_args();
  28. $argc = func_num_args();
  29. $serverProfile = null;
  30. $lastArg = $argv[$argc-1];
  31. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  32. $serverProfile = array_pop($argv);
  33. $argc--;
  34. }
  35. if ($argc === 0) {
  36. throw new ClientException('Missing connection parameters');
  37. }
  38. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  39. }
  40. private function setupConnection($parameters) {
  41. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  42. throw new ClientException('Invalid parameters type (array or string expected)');
  43. }
  44. if (is_array($parameters) && isset($parameters[0])) {
  45. $cluster = new ConnectionCluster();
  46. foreach ($parameters as $shardParams) {
  47. $cluster->add($this->createConnection($shardParams));
  48. }
  49. $this->setConnection($cluster);
  50. }
  51. else {
  52. $this->setConnection($this->createConnection($parameters));
  53. }
  54. }
  55. private function createConnection($parameters) {
  56. $params = new ConnectionParameters($parameters);
  57. $connection = new Connection($params, $this->_responseReader);
  58. if ($params->password !== null) {
  59. $connection->pushInitCommand($this->createCommand(
  60. 'auth', array($params->password)
  61. ));
  62. }
  63. if ($params->database !== null) {
  64. $connection->pushInitCommand($this->createCommand(
  65. 'select', array($params->database)
  66. ));
  67. }
  68. return $connection;
  69. }
  70. private function setConnection(IConnection $connection) {
  71. $this->_connection = $connection;
  72. }
  73. public function setProfile(RedisServerProfile $serverProfile) {
  74. $this->_serverProfile = $serverProfile;
  75. }
  76. public function getProfile() {
  77. return $this->_serverProfile;
  78. }
  79. public function getResponseReader() {
  80. return $this->_responseReader;
  81. }
  82. public function connect() {
  83. $this->_connection->connect();
  84. }
  85. public function disconnect() {
  86. $this->_connection->disconnect();
  87. }
  88. public function isConnected() {
  89. return $this->_connection->isConnected();
  90. }
  91. public function getConnection($id = null) {
  92. if (!isset($id)) {
  93. return $this->_connection;
  94. }
  95. else {
  96. return $this->_connection instanceof ConnectionCluster
  97. ? $this->_connection->getConnectionById($id)
  98. : $this->_connection;
  99. }
  100. }
  101. public function __call($method, $arguments) {
  102. $command = $this->_serverProfile->createCommand($method, $arguments);
  103. return $this->_connection->executeCommand($command);
  104. }
  105. public function createCommand($method, $arguments = array()) {
  106. return $this->_serverProfile->createCommand($method, $arguments);
  107. }
  108. public function executeCommand(Command $command) {
  109. return $this->_connection->executeCommand($command);
  110. }
  111. public function executeCommandOnShards(Command $command) {
  112. $replies = array();
  113. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  114. foreach($this->_connection as $connection) {
  115. $replies[] = $connection->executeCommand($command);
  116. }
  117. }
  118. else {
  119. $replies[] = $this->_connection->executeCommand($command);
  120. }
  121. return $replies;
  122. }
  123. public function rawCommand($rawCommandData, $closesConnection = false) {
  124. if ($this->_connection instanceof \Predis\ConnectionCluster) {
  125. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  126. }
  127. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  128. }
  129. public function pipeline($pipelineBlock = null) {
  130. $pipeline = new CommandPipeline($this);
  131. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  132. }
  133. public function multiExec($multiExecBlock = null) {
  134. $multiExec = new MultiExecBlock($this);
  135. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  136. }
  137. }
  138. /* ------------------------------------------------------------------------- */
  139. abstract class Command {
  140. private $_arguments, $_hash;
  141. public abstract function getCommandId();
  142. public abstract function serializeRequest($command, $arguments);
  143. public function canBeHashed() {
  144. return true;
  145. }
  146. public function getHash() {
  147. if (isset($this->_hash)) {
  148. return $this->_hash;
  149. }
  150. else {
  151. if (isset($this->_arguments[0])) {
  152. $key = $this->_arguments[0];
  153. $start = strpos($key, '{');
  154. $end = strpos($key, '}');
  155. if ($start !== false && $end !== false) {
  156. $key = substr($key, ++$start, $end - $start);
  157. }
  158. $this->_hash = crc32($key);
  159. return $this->_hash;
  160. }
  161. }
  162. return null;
  163. }
  164. public function closesConnection() {
  165. return false;
  166. }
  167. protected function filterArguments(Array $arguments) {
  168. return $arguments;
  169. }
  170. public function setArguments(/* arguments */) {
  171. $this->_arguments = $this->filterArguments(func_get_args());
  172. }
  173. public function setArgumentsArray(Array $arguments) {
  174. $this->_arguments = $this->filterArguments($arguments);
  175. }
  176. protected function getArguments() {
  177. // TODO: why getArguments is protected?
  178. return isset($this->_arguments) ? $this->_arguments : array();
  179. }
  180. public function getArgument($index = 0) {
  181. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  182. }
  183. public function parseResponse($data) {
  184. return $data;
  185. }
  186. public final function __invoke() {
  187. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  188. }
  189. }
  190. abstract class InlineCommand extends Command {
  191. public function serializeRequest($command, $arguments) {
  192. if (isset($arguments[0]) && is_array($arguments[0])) {
  193. $arguments[0] = implode($arguments[0], ' ');
  194. }
  195. return $command . ' ' . implode($arguments, ' ') . ResponseReader::NEWLINE;
  196. }
  197. }
  198. abstract class BulkCommand extends Command {
  199. public function serializeRequest($command, $arguments) {
  200. $data = array_pop($arguments);
  201. if (is_array($data)) {
  202. $data = implode($data, ' ');
  203. }
  204. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  205. ResponseReader::NEWLINE . $data . ResponseReader::NEWLINE;
  206. }
  207. }
  208. abstract class MultiBulkCommand extends Command {
  209. public function serializeRequest($command, $arguments) {
  210. $buffer = array();
  211. $cmd_args = null;
  212. if (count($arguments) === 1 && is_array($arguments[0])) {
  213. $cmd_args = array();
  214. foreach ($arguments[0] as $k => $v) {
  215. $cmd_args[] = $k;
  216. $cmd_args[] = $v;
  217. }
  218. }
  219. else {
  220. $cmd_args = $arguments;
  221. }
  222. $buffer[] = '*' . ((string) count($cmd_args) + 1) . ResponseReader::NEWLINE;
  223. $buffer[] = '$' . strlen($command) . ResponseReader::NEWLINE . $command . ResponseReader::NEWLINE;
  224. foreach ($cmd_args as $argument) {
  225. $buffer[] = '$' . strlen($argument) . ResponseReader::NEWLINE . $argument . ResponseReader::NEWLINE;
  226. }
  227. return implode('', $buffer);
  228. }
  229. }
  230. /* ------------------------------------------------------------------------- */
  231. interface IResponseHandler {
  232. function handle(Connection $connection, $payload);
  233. }
  234. class ResponseStatusHandler implements IResponseHandler {
  235. public function handle(Connection $connection, $status) {
  236. if ($status === ResponseReader::OK) {
  237. return true;
  238. }
  239. else if ($status === ResponseReader::QUEUED) {
  240. return new ResponseQueued();
  241. }
  242. return $status;
  243. }
  244. }
  245. class ResponseErrorHandler implements IResponseHandler {
  246. public function handle(Connection $connection, $errorMessage) {
  247. throw new ServerException(substr($errorMessage, 4));
  248. }
  249. }
  250. class ResponseErrorSilentHandler implements IResponseHandler {
  251. public function handle(Connection $connection, $errorMessage) {
  252. return new ResponseError(substr($errorMessage, 4));
  253. }
  254. }
  255. class ResponseBulkHandler implements IResponseHandler {
  256. public function handle(Connection $connection, $dataLength) {
  257. if (!is_numeric($dataLength)) {
  258. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  259. "Cannot parse '$dataLength' as data length", $connection
  260. ));
  261. }
  262. if ($dataLength > 0) {
  263. $value = $connection->readBytes($dataLength);
  264. if ($connection->readBytes(2) !== ResponseReader::NEWLINE) {
  265. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  266. 'Did not receive a new-line at the end of a bulk response', $connection
  267. ));
  268. }
  269. return $value;
  270. }
  271. else if ($dataLength == 0) {
  272. if ($connection->readBytes(2) !== ResponseReader::NEWLINE) {
  273. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  274. 'Did not receive a new-line at the end of a bulk response', $connection
  275. ));
  276. }
  277. return '';
  278. }
  279. return null;
  280. }
  281. }
  282. class ResponseMultiBulkHandler implements IResponseHandler {
  283. public function handle(Connection $connection, $rawLength) {
  284. if (!is_numeric($rawLength)) {
  285. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  286. "Cannot parse '$rawLength' as data length", $connection
  287. ));
  288. }
  289. $listLength = (int) $rawLength;
  290. if ($listLength === -1) {
  291. return null;
  292. }
  293. $list = array();
  294. if ($listLength > 0) {
  295. for ($i = 0; $i < $listLength; $i++) {
  296. $list[] = $connection->getResponseReader()->read($connection);
  297. }
  298. }
  299. return $list;
  300. }
  301. }
  302. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  303. public function handle(Connection $connection, $rawLength) {
  304. if (!is_numeric($rawLength)) {
  305. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  306. "Cannot parse '$rawLength' as data length", $connection
  307. ));
  308. }
  309. return new Utilities\MultiBulkResponseIterator($connection, (int)$rawLength);
  310. }
  311. }
  312. class ResponseIntegerHandler implements IResponseHandler {
  313. public function handle(Connection $connection, $number) {
  314. if (is_numeric($number)) {
  315. return (int) $number;
  316. }
  317. else {
  318. if ($number !== ResponseReader::NULL) {
  319. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  320. "Cannot parse '$number' as numeric response", $connection
  321. ));
  322. }
  323. return null;
  324. }
  325. }
  326. }
  327. class ResponseReader {
  328. const NEWLINE = "\r\n";
  329. const OK = 'OK';
  330. const ERROR = 'ERR';
  331. const QUEUED = 'QUEUED';
  332. const NULL = 'nil';
  333. const PREFIX_STATUS = '+';
  334. const PREFIX_ERROR = '-';
  335. const PREFIX_INTEGER = ':';
  336. const PREFIX_BULK = '$';
  337. const PREFIX_MULTI_BULK = '*';
  338. private $_prefixHandlers;
  339. public function __construct() {
  340. $this->initializePrefixHandlers();
  341. }
  342. private function initializePrefixHandlers() {
  343. $this->_prefixHandlers = array(
  344. self::PREFIX_STATUS => new ResponseStatusHandler(),
  345. self::PREFIX_ERROR => new ResponseErrorHandler(),
  346. self::PREFIX_INTEGER => new ResponseIntegerHandler(),
  347. self::PREFIX_BULK => new ResponseBulkHandler(),
  348. self::PREFIX_MULTI_BULK => new ResponseMultiBulkHandler(),
  349. );
  350. }
  351. private function setHandler($prefix, IResponseHandler $handler) {
  352. $this->_prefixHandlers[$prefix] = $handler;
  353. }
  354. public function setOption($option, $value) {
  355. switch ($option) {
  356. case 'iterable_multibulk_replies':
  357. case 'iterableMultiBulkReplies':
  358. $this->setHandler(self::PREFIX_MULTI_BULK, $value == true
  359. ? new ResponseMultiBulkStreamHandler()
  360. : new ResponseMultiBulkHandler()
  361. );
  362. break;
  363. case 'errorThrowException':
  364. case 'error_throw_exception':
  365. $this->setHandler(self::PREFIX_ERROR, $value == true
  366. ? new ResponseErrorHandler()
  367. : new ResponseErrorSilentHandler()
  368. );
  369. break;
  370. default:
  371. throw new \InvalidArgumentException("Unknown option: $option");
  372. }
  373. }
  374. public function getOption($option) {
  375. switch ($option) {
  376. case 'iterable_multibulk_replies':
  377. case 'iterableMultiBulkReplies':
  378. return $this->_prefixHandlers[self::PREFIX_MULTI_BULK]
  379. instanceof ResponseMultiBulkStreamHandler;
  380. case 'errorThrowException':
  381. case 'error_throw_exception':
  382. return $this->_prefixHandlers[self::PREFIX_ERROR]
  383. instanceof ResponseErrorHandler;
  384. default:
  385. throw new \InvalidArgumentException("Unknown option: $option");
  386. }
  387. }
  388. public function read(Connection $connection) {
  389. $header = $connection->readLine();
  390. if ($header === '') {
  391. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  392. 'Unexpected empty header', $connection
  393. ));
  394. }
  395. $prefix = $header[0];
  396. $payload = strlen($header) > 1 ? substr($header, 1) : '';
  397. if (!isset($this->_prefixHandlers[$prefix])) {
  398. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  399. "Unknown prefix '$prefix'", $connection
  400. ));
  401. }
  402. $handler = $this->_prefixHandlers[$prefix];
  403. return $handler->handle($connection, $payload);
  404. }
  405. }
  406. class ResponseError {
  407. private $_message;
  408. public function __construct($message) {
  409. $this->_message = $message;
  410. }
  411. public function __get($property) {
  412. if ($property == 'error') {
  413. return true;
  414. }
  415. if ($property == 'message') {
  416. return $this->_message;
  417. }
  418. }
  419. public function __isset($property) {
  420. return $property === 'error';
  421. }
  422. public function __toString() {
  423. return $this->_message;
  424. }
  425. }
  426. class ResponseQueued {
  427. public $queued = true;
  428. public function __toString() {
  429. return ResponseReader::QUEUED;
  430. }
  431. }
  432. /* ------------------------------------------------------------------------- */
  433. class CommandPipeline {
  434. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  435. public function __construct(Client $redisClient) {
  436. $this->_redisClient = $redisClient;
  437. $this->_pipelineBuffer = array();
  438. $this->_returnValues = array();
  439. }
  440. public function __call($method, $arguments) {
  441. $command = $this->_redisClient->createCommand($method, $arguments);
  442. $this->recordCommand($command);
  443. return $this;
  444. }
  445. private function recordCommand(Command $command) {
  446. $this->_pipelineBuffer[] = $command;
  447. }
  448. private function getRecordedCommands() {
  449. return $this->_pipelineBuffer;
  450. }
  451. public function flushPipeline() {
  452. $sizeofPipe = count($this->_pipelineBuffer);
  453. if ($sizeofPipe === 0) {
  454. return;
  455. }
  456. $connection = $this->_redisClient->getConnection();
  457. $commands = &$this->_pipelineBuffer;
  458. foreach ($commands as $command) {
  459. $connection->writeCommand($command);
  460. }
  461. for ($i = 0; $i < $sizeofPipe; $i++) {
  462. $response = $connection->readResponse($commands[$i]);
  463. $this->_returnValues[] = ($response instanceof \Iterator
  464. ? iterator_to_array($response)
  465. : $response
  466. );
  467. unset($commands[$i]);
  468. }
  469. $this->_pipelineBuffer = array();
  470. return $this;
  471. }
  472. private function setRunning($bool) {
  473. if ($bool == true && $this->_running == true) {
  474. throw new ClientException("This pipeline is already opened");
  475. }
  476. $this->_running = $bool;
  477. }
  478. public function execute($block = null) {
  479. if ($block && !is_callable($block)) {
  480. throw new \RuntimeException('Argument passed must be a callable object');
  481. }
  482. // TODO: do not reuse previously executed pipelines
  483. $this->setRunning(true);
  484. $pipelineBlockException = null;
  485. try {
  486. if ($block !== null) {
  487. $block($this);
  488. }
  489. $this->flushPipeline();
  490. }
  491. catch (\Exception $exception) {
  492. // TODO: client/server desync on ServerException
  493. $pipelineBlockException = $exception;
  494. }
  495. $this->setRunning(false);
  496. if ($pipelineBlockException !== null) {
  497. throw $pipelineBlockException;
  498. }
  499. return $this->_returnValues;
  500. }
  501. }
  502. class MultiExecBlock {
  503. private $_redisClient, $_commands, $_initialized, $_discarded;
  504. public function __construct(Client $redisClient) {
  505. $this->_initialized = false;
  506. $this->_discarded = false;
  507. $this->_redisClient = $redisClient;
  508. $this->_commands = array();
  509. }
  510. private function initialize() {
  511. if ($this->_initialized === false) {
  512. $this->_redisClient->multi();
  513. $this->_initialized = true;
  514. $this->_discarded = false;
  515. }
  516. }
  517. public function __call($method, $arguments) {
  518. $this->initialize();
  519. $command = $this->_redisClient->createCommand($method, $arguments);
  520. $response = $this->_redisClient->executeCommand($command);
  521. if (isset($response->queued)) {
  522. $this->_commands[] = $command;
  523. return $this;
  524. }
  525. else {
  526. $this->malformedServerResponse('The server did not respond with a QUEUED status reply');
  527. }
  528. }
  529. public function discard() {
  530. $this->_redisClient->discard();
  531. $this->_commands = array();
  532. $this->_initialized = false;
  533. $this->_discarded = true;
  534. }
  535. public function execute($block = null) {
  536. if ($block && !is_callable($block)) {
  537. throw new \RuntimeException('Argument passed must be a callable object');
  538. }
  539. $blockException = null;
  540. $returnValues = array();
  541. try {
  542. if ($block !== null) {
  543. $block($this);
  544. }
  545. if ($this->_discarded === true) {
  546. return;
  547. }
  548. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  549. ? iterator_to_array($reply)
  550. : $reply
  551. );
  552. $commands = &$this->_commands;
  553. $sizeofReplies = count($execReply);
  554. if ($sizeofReplies !== count($commands)) {
  555. $this->malformedServerResponse('Unexpected number of responses for a MultiExecBlock');
  556. }
  557. for ($i = 0; $i < $sizeofReplies; $i++) {
  558. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  559. ? iterator_to_array($execReply[$i])
  560. : $execReply[$i]
  561. );
  562. unset($commands[$i]);
  563. }
  564. }
  565. catch (\Exception $exception) {
  566. $blockException = $exception;
  567. }
  568. if ($blockException !== null) {
  569. throw $blockException;
  570. }
  571. return $returnValues;
  572. }
  573. private function malformedServerResponse($message) {
  574. // NOTE: a MULTI/EXEC block cannot be initialized on a clustered
  575. // connection, which means that Predis\Client::getConnection
  576. // will always return an instance of Predis\Connection.
  577. Utilities\Shared::onCommunicationException(new MalformedServerResponse(
  578. $message, $this->_redisClient->getConnection()
  579. ));
  580. }
  581. }
  582. /* ------------------------------------------------------------------------- */
  583. class ConnectionParameters {
  584. const DEFAULT_HOST = '127.0.0.1';
  585. const DEFAULT_PORT = 6379;
  586. const DEFAULT_TIMEOUT = 5;
  587. private $_parameters;
  588. public function __construct($parameters = null) {
  589. $parameters = $parameters ?: array();
  590. $this->_parameters = is_array($parameters)
  591. ? self::filterConnectionParams($parameters)
  592. : self::parseURI($parameters);
  593. }
  594. private static function parseURI($uri) {
  595. $parsed = @parse_url($uri);
  596. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  597. throw new ClientException("Invalid URI: $uri");
  598. }
  599. if (array_key_exists('query', $parsed)) {
  600. $details = array();
  601. foreach (explode('&', $parsed['query']) as $kv) {
  602. list($k, $v) = explode('=', $kv);
  603. switch ($k) {
  604. case 'database':
  605. $details['database'] = $v;
  606. break;
  607. case 'password':
  608. $details['password'] = $v;
  609. break;
  610. case 'connection_async':
  611. $details['connection_async'] = $v;
  612. break;
  613. case 'connection_timeout':
  614. $details['connection_timeout'] = $v;
  615. break;
  616. case 'read_write_timeout':
  617. $details['read_write_timeout'] = $v;
  618. break;
  619. case 'alias':
  620. $details['alias'] = $v;
  621. break;
  622. case 'weight':
  623. $details['weight'] = $v;
  624. break;
  625. }
  626. }
  627. $parsed = array_merge($parsed, $details);
  628. }
  629. return self::filterConnectionParams($parsed);
  630. }
  631. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  632. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  633. }
  634. private static function filterConnectionParams($parameters) {
  635. return array(
  636. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  637. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  638. 'database' => self::getParamOrDefault($parameters, 'database'),
  639. 'password' => self::getParamOrDefault($parameters, 'password'),
  640. 'connection_async' => self::getParamOrDefault($parameters, 'connection_async', false),
  641. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout', self::DEFAULT_TIMEOUT),
  642. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  643. 'alias' => self::getParamOrDefault($parameters, 'alias'),
  644. 'weight' => self::getParamOrDefault($parameters, 'weight', Utilities\HashRing::DEFAULT_WEIGHT),
  645. );
  646. }
  647. public function __get($parameter) {
  648. return $this->_parameters[$parameter];
  649. }
  650. public function __isset($parameter) {
  651. return isset($this->_parameters[$parameter]);
  652. }
  653. }
  654. interface IConnection {
  655. public function connect();
  656. public function disconnect();
  657. public function isConnected();
  658. public function writeCommand(Command $command);
  659. public function readResponse(Command $command);
  660. public function executeCommand(Command $command);
  661. }
  662. class Connection implements IConnection {
  663. private $_params, $_socket, $_initCmds, $_reader;
  664. public function __construct(ConnectionParameters $parameters, ResponseReader $reader = null) {
  665. $this->_params = $parameters;
  666. $this->_initCmds = array();
  667. $this->_reader = $reader ?: new ResponseReader();
  668. }
  669. public function __destruct() {
  670. $this->disconnect();
  671. }
  672. public function isConnected() {
  673. return is_resource($this->_socket);
  674. }
  675. public function connect() {
  676. if ($this->isConnected()) {
  677. throw new ClientException('Connection already estabilished');
  678. }
  679. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  680. $connectFlags = STREAM_CLIENT_CONNECT;
  681. if ($this->_params->connection_async) {
  682. $connectFlags |= STREAM_CLIENT_ASYNC_CONNECT;
  683. }
  684. $this->_socket = @stream_socket_client(
  685. $uri, $errno, $errstr, $this->_params->connection_timeout, $connectFlags
  686. );
  687. if (!$this->_socket) {
  688. $this->onCommunicationException(trim($errstr), $errno);
  689. }
  690. if (isset($this->_params->read_write_timeout)) {
  691. $timeoutSeconds = floor($this->_params->read_write_timeout);
  692. $timeoutUSeconds = ($this->_params->read_write_timeout - $timeoutSeconds) * 1000000;
  693. stream_set_timeout($this->_socket, $timeoutSeconds, $timeoutUSeconds);
  694. }
  695. if (count($this->_initCmds) > 0){
  696. $this->sendInitializationCommands();
  697. }
  698. }
  699. public function disconnect() {
  700. if ($this->isConnected()) {
  701. fclose($this->_socket);
  702. }
  703. }
  704. public function pushInitCommand(Command $command){
  705. $this->_initCmds[] = $command;
  706. }
  707. private function sendInitializationCommands() {
  708. foreach ($this->_initCmds as $command) {
  709. $this->writeCommand($command);
  710. }
  711. foreach ($this->_initCmds as $command) {
  712. $this->readResponse($command);
  713. }
  714. }
  715. private function onCommunicationException($message, $code = null) {
  716. Utilities\Shared::onCommunicationException(
  717. new CommunicationException($message, $this, $code)
  718. );
  719. }
  720. public function writeCommand(Command $command) {
  721. $this->writeBytes($command());
  722. }
  723. public function readResponse(Command $command) {
  724. $response = $this->_reader->read($this);
  725. $skipparse = isset($response->queued) || isset($response->error);
  726. return $skipparse ? $response : $command->parseResponse($response);
  727. }
  728. public function executeCommand(Command $command) {
  729. $this->writeCommand($command);
  730. if ($command->closesConnection()) {
  731. return $this->disconnect();
  732. }
  733. return $this->readResponse($command);
  734. }
  735. public function rawCommand($rawCommandData, $closesConnection = false) {
  736. $this->writeBytes($rawCommandData);
  737. if ($closesConnection) {
  738. $this->disconnect();
  739. return;
  740. }
  741. return $this->_reader->read($this);
  742. }
  743. public function writeBytes($value) {
  744. $socket = $this->getSocket();
  745. while (($length = strlen($value)) > 0) {
  746. $written = fwrite($socket, $value);
  747. if ($length === $written) {
  748. return true;
  749. }
  750. if ($written === false || $written === 0) {
  751. $this->onCommunicationException('Error while writing bytes to the server');
  752. }
  753. $value = substr($value, $written);
  754. }
  755. return true;
  756. }
  757. public function readBytes($length) {
  758. if ($length == 0) {
  759. throw new InvalidArgumentException('Length parameter must be greater than 0');
  760. }
  761. $socket = $this->getSocket();
  762. $value = '';
  763. do {
  764. $chunk = fread($socket, $length);
  765. if ($chunk === false || $chunk === '') {
  766. $this->onCommunicationException('Error while reading bytes from the server');
  767. }
  768. $value .= $chunk;
  769. }
  770. while (($length -= strlen($chunk)) > 0);
  771. return $value;
  772. }
  773. public function readLine() {
  774. $socket = $this->getSocket();
  775. $value = '';
  776. do {
  777. $chunk = fgets($socket);
  778. if ($chunk === false || strlen($chunk) == 0) {
  779. $this->onCommunicationException('Error while reading line from the server');
  780. }
  781. $value .= $chunk;
  782. }
  783. while (substr($value, -2) !== ResponseReader::NEWLINE);
  784. return substr($value, 0, -2);
  785. }
  786. public function getSocket() {
  787. if (!$this->isConnected()) {
  788. $this->connect();
  789. }
  790. return $this->_socket;
  791. }
  792. public function getResponseReader() {
  793. return $this->_reader;
  794. }
  795. public function getParameters() {
  796. return $this->_params;
  797. }
  798. public function __toString() {
  799. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  800. }
  801. }
  802. class ConnectionCluster implements IConnection, \IteratorAggregate {
  803. private $_pool, $_ring;
  804. public function __construct() {
  805. $this->_pool = array();
  806. $this->_ring = new Utilities\HashRing();
  807. }
  808. public function isConnected() {
  809. foreach ($this->_pool as $connection) {
  810. if ($connection->isConnected()) {
  811. return true;
  812. }
  813. }
  814. return false;
  815. }
  816. public function connect() {
  817. foreach ($this->_pool as $connection) {
  818. $connection->connect();
  819. }
  820. }
  821. public function disconnect() {
  822. foreach ($this->_pool as $connection) {
  823. $connection->disconnect();
  824. }
  825. }
  826. public function add(Connection $connection) {
  827. $parameters = $connection->getParameters();
  828. if (isset($parameters->alias)) {
  829. $this->_pool[$parameters->alias] = $connection;
  830. }
  831. else {
  832. $this->_pool[] = $connection;
  833. }
  834. $this->_ring->add($connection, $parameters->weight);
  835. }
  836. public function getConnection(Command $command) {
  837. if ($command->canBeHashed() === false) {
  838. throw new ClientException(
  839. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  840. );
  841. }
  842. return $this->_ring->get($command->getHash());
  843. }
  844. public function getConnectionById($id = null) {
  845. return $this->_pool[$id ?: 0];
  846. }
  847. public function getIterator() {
  848. return new \ArrayIterator($this->_pool);
  849. }
  850. public function writeCommand(Command $command) {
  851. $this->getConnection($command)->writeCommand($command);
  852. }
  853. public function readResponse(Command $command) {
  854. return $this->getConnection($command)->readResponse($command);
  855. }
  856. public function executeCommand(Command $command) {
  857. $connection = $this->getConnection($command);
  858. $connection->writeCommand($command);
  859. return $connection->readResponse($command);
  860. }
  861. }
  862. /* ------------------------------------------------------------------------- */
  863. abstract class RedisServerProfile {
  864. private static $_serverProfiles;
  865. private $_registeredCommands;
  866. public function __construct() {
  867. $this->_registeredCommands = $this->getSupportedCommands();
  868. }
  869. public abstract function getVersion();
  870. protected abstract function getSupportedCommands();
  871. public static function getDefault() {
  872. return self::get('default');
  873. }
  874. private static function predisServerProfiles() {
  875. return array(
  876. '1.0' => '\Predis\RedisServer_v1_0',
  877. '1.2' => '\Predis\RedisServer_v1_2',
  878. 'default' => '\Predis\RedisServer_v1_2',
  879. 'dev' => '\Predis\RedisServer_vNext',
  880. );
  881. }
  882. public static function get($version) {
  883. if (!isset(self::$_serverProfiles)) {
  884. self::$_serverProfiles = self::predisServerProfiles();
  885. }
  886. if (!isset(self::$_serverProfiles[$version])) {
  887. throw new ClientException("Unknown server profile: $version");
  888. }
  889. $profile = self::$_serverProfiles[$version];
  890. return new $profile();
  891. }
  892. public function compareWith($version, $operator = null) {
  893. // one could expect that PHP's version_compare would behave
  894. // the same way if invoked with 2 arguments or 3 arguments
  895. // with the third being NULL, but it is not like that.
  896. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  897. // we might need to revise the behavior of this method.
  898. return ($operator === null
  899. ? version_compare($this, $version)
  900. : version_compare($this, $version, $operator)
  901. );
  902. }
  903. public function supportsCommand($command) {
  904. return isset($this->_registeredCommands[$command]);
  905. }
  906. public function createCommand($method, $arguments = array()) {
  907. if (!isset($this->_registeredCommands[$method])) {
  908. throw new ClientException("'$method' is not a registered Redis command");
  909. }
  910. $commandClass = $this->_registeredCommands[$method];
  911. $command = new $commandClass();
  912. $command->setArgumentsArray($arguments);
  913. return $command;
  914. }
  915. public function registerCommands(Array $commands) {
  916. foreach ($commands as $command => $aliases) {
  917. $this->registerCommand($command, $aliases);
  918. }
  919. }
  920. public function registerCommand($command, $aliases) {
  921. $commandReflection = new \ReflectionClass($command);
  922. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  923. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  924. }
  925. if (is_array($aliases)) {
  926. foreach ($aliases as $alias) {
  927. $this->_registeredCommands[$alias] = $command;
  928. }
  929. }
  930. else {
  931. $this->_registeredCommands[$aliases] = $command;
  932. }
  933. }
  934. public function __toString() {
  935. return $this->getVersion();
  936. }
  937. }
  938. class RedisServer_v1_0 extends RedisServerProfile {
  939. public function getVersion() { return '1.0'; }
  940. public function getSupportedCommands() {
  941. return array(
  942. /* miscellaneous commands */
  943. 'ping' => '\Predis\Commands\Ping',
  944. 'echo' => '\Predis\Commands\DoEcho',
  945. 'auth' => '\Predis\Commands\Auth',
  946. /* connection handling */
  947. 'quit' => '\Predis\Commands\Quit',
  948. /* commands operating on string values */
  949. 'set' => '\Predis\Commands\Set',
  950. 'setnx' => '\Predis\Commands\SetPreserve',
  951. 'setPreserve' => '\Predis\Commands\SetPreserve',
  952. 'get' => '\Predis\Commands\Get',
  953. 'mget' => '\Predis\Commands\GetMultiple',
  954. 'getMultiple' => '\Predis\Commands\GetMultiple',
  955. 'getset' => '\Predis\Commands\GetSet',
  956. 'getSet' => '\Predis\Commands\GetSet',
  957. 'incr' => '\Predis\Commands\Increment',
  958. 'increment' => '\Predis\Commands\Increment',
  959. 'incrby' => '\Predis\Commands\IncrementBy',
  960. 'incrementBy' => '\Predis\Commands\IncrementBy',
  961. 'decr' => '\Predis\Commands\Decrement',
  962. 'decrement' => '\Predis\Commands\Decrement',
  963. 'decrby' => '\Predis\Commands\DecrementBy',
  964. 'decrementBy' => '\Predis\Commands\DecrementBy',
  965. 'exists' => '\Predis\Commands\Exists',
  966. 'del' => '\Predis\Commands\Delete',
  967. 'delete' => '\Predis\Commands\Delete',
  968. 'type' => '\Predis\Commands\Type',
  969. /* commands operating on the key space */
  970. 'keys' => '\Predis\Commands\Keys',
  971. 'randomkey' => '\Predis\Commands\RandomKey',
  972. 'randomKey' => '\Predis\Commands\RandomKey',
  973. 'rename' => '\Predis\Commands\Rename',
  974. 'renamenx' => '\Predis\Commands\RenamePreserve',
  975. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  976. 'expire' => '\Predis\Commands\Expire',
  977. 'expireat' => '\Predis\Commands\ExpireAt',
  978. 'expireAt' => '\Predis\Commands\ExpireAt',
  979. 'dbsize' => '\Predis\Commands\DatabaseSize',
  980. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  981. 'ttl' => '\Predis\Commands\TimeToLive',
  982. 'timeToLive' => '\Predis\Commands\TimeToLive',
  983. /* commands operating on lists */
  984. 'rpush' => '\Predis\Commands\ListPushTail',
  985. 'pushTail' => '\Predis\Commands\ListPushTail',
  986. 'lpush' => '\Predis\Commands\ListPushHead',
  987. 'pushHead' => '\Predis\Commands\ListPushHead',
  988. 'llen' => '\Predis\Commands\ListLength',
  989. 'listLength' => '\Predis\Commands\ListLength',
  990. 'lrange' => '\Predis\Commands\ListRange',
  991. 'listRange' => '\Predis\Commands\ListRange',
  992. 'ltrim' => '\Predis\Commands\ListTrim',
  993. 'listTrim' => '\Predis\Commands\ListTrim',
  994. 'lindex' => '\Predis\Commands\ListIndex',
  995. 'listIndex' => '\Predis\Commands\ListIndex',
  996. 'lset' => '\Predis\Commands\ListSet',
  997. 'listSet' => '\Predis\Commands\ListSet',
  998. 'lrem' => '\Predis\Commands\ListRemove',
  999. 'listRemove' => '\Predis\Commands\ListRemove',
  1000. 'lpop' => '\Predis\Commands\ListPopFirst',
  1001. 'popFirst' => '\Predis\Commands\ListPopFirst',
  1002. 'rpop' => '\Predis\Commands\ListPopLast',
  1003. 'popLast' => '\Predis\Commands\ListPopLast',
  1004. /* commands operating on sets */
  1005. 'sadd' => '\Predis\Commands\SetAdd',
  1006. 'setAdd' => '\Predis\Commands\SetAdd',
  1007. 'srem' => '\Predis\Commands\SetRemove',
  1008. 'setRemove' => '\Predis\Commands\SetRemove',
  1009. 'spop' => '\Predis\Commands\SetPop',
  1010. 'setPop' => '\Predis\Commands\SetPop',
  1011. 'smove' => '\Predis\Commands\SetMove',
  1012. 'setMove' => '\Predis\Commands\SetMove',
  1013. 'scard' => '\Predis\Commands\SetCardinality',
  1014. 'setCardinality' => '\Predis\Commands\SetCardinality',
  1015. 'sismember' => '\Predis\Commands\SetIsMember',
  1016. 'setIsMember' => '\Predis\Commands\SetIsMember',
  1017. 'sinter' => '\Predis\Commands\SetIntersection',
  1018. 'setIntersection' => '\Predis\Commands\SetIntersection',
  1019. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  1020. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  1021. 'sunion' => '\Predis\Commands\SetUnion',
  1022. 'setUnion' => '\Predis\Commands\SetUnion',
  1023. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  1024. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  1025. 'sdiff' => '\Predis\Commands\SetDifference',
  1026. 'setDifference' => '\Predis\Commands\SetDifference',
  1027. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  1028. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  1029. 'smembers' => '\Predis\Commands\SetMembers',
  1030. 'setMembers' => '\Predis\Commands\SetMembers',
  1031. 'srandmember' => '\Predis\Commands\SetRandomMember',
  1032. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  1033. /* multiple databases handling commands */
  1034. 'select' => '\Predis\Commands\SelectDatabase',
  1035. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  1036. 'move' => '\Predis\Commands\MoveKey',
  1037. 'moveKey' => '\Predis\Commands\MoveKey',
  1038. 'flushdb' => '\Predis\Commands\FlushDatabase',
  1039. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  1040. 'flushall' => '\Predis\Commands\FlushAll',
  1041. 'flushDatabases' => '\Predis\Commands\FlushAll',
  1042. /* sorting */
  1043. 'sort' => '\Predis\Commands\Sort',
  1044. /* remote server control commands */
  1045. 'info' => '\Predis\Commands\Info',
  1046. 'slaveof' => '\Predis\Commands\SlaveOf',
  1047. 'slaveOf' => '\Predis\Commands\SlaveOf',
  1048. /* persistence control commands */
  1049. 'save' => '\Predis\Commands\Save',
  1050. 'bgsave' => '\Predis\Commands\BackgroundSave',
  1051. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  1052. 'lastsave' => '\Predis\Commands\LastSave',
  1053. 'lastSave' => '\Predis\Commands\LastSave',
  1054. 'shutdown' => '\Predis\Commands\Shutdown',
  1055. );
  1056. }
  1057. }
  1058. class RedisServer_v1_2 extends RedisServer_v1_0 {
  1059. public function getVersion() { return '1.2'; }
  1060. public function getSupportedCommands() {
  1061. return array_merge(parent::getSupportedCommands(), array(
  1062. /* commands operating on string values */
  1063. 'mset' => '\Predis\Commands\SetMultiple',
  1064. 'setMultiple' => '\Predis\Commands\SetMultiple',
  1065. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  1066. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  1067. /* commands operating on lists */
  1068. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  1069. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  1070. /* commands operating on sorted sets */
  1071. 'zadd' => '\Predis\Commands\ZSetAdd',
  1072. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  1073. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  1074. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  1075. 'zrem' => '\Predis\Commands\ZSetRemove',
  1076. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  1077. 'zrange' => '\Predis\Commands\ZSetRange',
  1078. 'zsetRange' => '\Predis\Commands\ZSetRange',
  1079. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  1080. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  1081. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  1082. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  1083. 'zcard' => '\Predis\Commands\ZSetCardinality',
  1084. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  1085. 'zscore' => '\Predis\Commands\ZSetScore',
  1086. 'zsetScore' => '\Predis\Commands\ZSetScore',
  1087. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1088. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  1089. /* persistence control commands */
  1090. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1091. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  1092. ));
  1093. }
  1094. }
  1095. class RedisServer_vNext extends RedisServer_v1_2 {
  1096. public function getVersion() { return '1.3'; }
  1097. public function getSupportedCommands() {
  1098. return array_merge(parent::getSupportedCommands(), array(
  1099. /* miscellaneous commands */
  1100. 'multi' => '\Predis\Commands\Multi',
  1101. 'exec' => '\Predis\Commands\Exec',
  1102. 'discard' => '\Predis\Commands\Discard',
  1103. /* commands operating on string values */
  1104. 'append' => '\Predis\Commands\Append',
  1105. 'substr' => '\Predis\Commands\Substr',
  1106. /* commands operating on lists */
  1107. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  1108. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  1109. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  1110. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  1111. /* commands operating on sorted sets */
  1112. 'zunion' => '\Predis\Commands\ZSetUnion',
  1113. 'zsetUnion' => '\Predis\Commands\ZSetUnion',
  1114. 'zinter' => '\Predis\Commands\ZSetIntersection',
  1115. 'zsetIntersection' => '\Predis\Commands\ZSetIntersection',
  1116. 'zcount' => '\Predis\Commands\ZSetCount',
  1117. 'zsetCount' => '\Predis\Commands\ZSetCount',
  1118. 'zrank' => '\Predis\Commands\ZSetRank',
  1119. 'zsetRank' => '\Predis\Commands\ZSetRank',
  1120. 'zrevrank' => '\Predis\Commands\ZSetReverseRank',
  1121. 'zsetReverseRank' => '\Predis\Commands\ZSetReverseRank',
  1122. 'zremrangebyrank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1123. 'zsetRemoveRangeByRank' => '\Predis\Commands\ZSetRemoveRangeByRank',
  1124. /* commands operating on hashes */
  1125. 'hset' => '\Predis\Commands\HashSet',
  1126. 'hashSet' => '\Predis\Commands\HashSet',
  1127. 'hincrby' => '\Predis\Commands\HashIncrementBy',
  1128. 'hashIncrementBy' => '\Predis\Commands\HashIncrementBy',
  1129. 'hget' => '\Predis\Commands\HashGet',
  1130. 'hashGet' => '\Predis\Commands\HashGet',
  1131. 'hdel' => '\Predis\Commands\HashDelete',
  1132. 'hashDelete' => '\Predis\Commands\HashDelete',
  1133. 'hexists' => '\Predis\Commands\HashExists',
  1134. 'hashExists' => '\Predis\Commands\HashExists',
  1135. 'hlen' => '\Predis\Commands\HashLength',
  1136. 'hashLength' => '\Predis\Commands\HashLength',
  1137. 'hkeys' => '\Predis\Commands\HashKeys',
  1138. 'hashKeys' => '\Predis\Commands\HashKeys',
  1139. 'hvals' => '\Predis\Commands\HashValues',
  1140. 'hashValues' => '\Predis\Commands\HashValues',
  1141. 'hgetall' => '\Predis\Commands\HashGetAll',
  1142. 'hashKeysValues' => '\Predis\Commands\HashGetAll',
  1143. /* remote server control commands */
  1144. 'config' => '\Predis\Commands\Config',
  1145. 'configuration' => '\Predis\Commands\Config',
  1146. ));
  1147. }
  1148. }
  1149. /* ------------------------------------------------------------------------- */
  1150. namespace Predis\Utilities;
  1151. class Shared {
  1152. public static function onCommunicationException(\Predis\CommunicationException $exception) {
  1153. if ($exception->shouldResetConnection()) {
  1154. $connection = $exception->getConnection();
  1155. if ($connection->isConnected()) {
  1156. $connection->disconnect();
  1157. }
  1158. }
  1159. throw $exception;
  1160. }
  1161. }
  1162. class HashRing {
  1163. const DEFAULT_REPLICAS = 128;
  1164. const DEFAULT_WEIGHT = 100;
  1165. private $_nodes, $_ring, $_ringKeys, $_replicas;
  1166. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  1167. $this->_replicas = $replicas;
  1168. $this->_nodes = array();
  1169. }
  1170. public function add($node, $weight = self::DEFAULT_WEIGHT) {
  1171. // NOTE: in case of collisions in the hashes of the nodes, the node added
  1172. // last wins, thus the order in which nodes are added is significant.
  1173. $this->_nodes[] = array('object' => $node, 'weight' => (int) $weight);
  1174. $this->reset();
  1175. }
  1176. public function remove($node) {
  1177. // NOTE: a node is removed by resetting the ring so that it's recreated from
  1178. // scratch, in order to reassign possible hashes with collisions to the
  1179. // right node according to the order in which they were added in the
  1180. // first place.
  1181. for ($i = 0; $i < count($this->_nodes); ++$i) {
  1182. if ($this->_nodes[$i]['object'] === $node) {
  1183. array_splice($this->_nodes, $i, 1);
  1184. $this->reset();
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. private function reset() {
  1190. unset($this->_ring);
  1191. unset($this->_ringKeys);
  1192. }
  1193. private function isInitialized() {
  1194. return isset($this->_ringKeys);
  1195. }
  1196. private function computeTotalWeight() {
  1197. // TODO: array_reduce + lambda for PHP 5.3
  1198. $totalWeight = 0;
  1199. foreach ($this->_nodes as $node) {
  1200. $totalWeight += $node['weight'];
  1201. }
  1202. return $totalWeight;
  1203. }
  1204. private function initialize() {
  1205. if ($this->isInitialized()) {
  1206. return;
  1207. }
  1208. if (count($this->_nodes) === 0) {
  1209. throw new \LogicException('Cannot initialize empty hashring');
  1210. }
  1211. $this->_ring = array();
  1212. $totalWeight = $this->computeTotalWeight();
  1213. $nodesCount = count($this->_nodes);
  1214. foreach ($this->_nodes as $node) {
  1215. $nodeObject = $node['object'];
  1216. $nodeHash = (string) $nodeObject;
  1217. $weightRatio = $node['weight'] / $totalWeight;
  1218. $replicas = (int) round($weightRatio * $nodesCount * $this->_replicas);
  1219. for ($i = 0; $i < $replicas; $i++) {
  1220. $key = crc32($nodeHash . ':' . $i);
  1221. $this->_ring[$key] = $nodeObject;
  1222. }
  1223. }
  1224. ksort($this->_ring, SORT_NUMERIC);
  1225. $this->_ringKeys = array_keys($this->_ring);
  1226. }
  1227. public function get($key) {
  1228. return $this->_ring[$this->getNodeKey($key)];
  1229. }
  1230. private function getNodeKey($key) {
  1231. // NOTE: binary search for the last item in _ringkeys with a value
  1232. // less or equal to the key. If no such item exists, return the
  1233. // last item.
  1234. $this->initialize();
  1235. $ringKeys = $this->_ringKeys;
  1236. $upper = count($ringKeys) - 1;
  1237. $lower = 0;
  1238. while ($lower <= $upper) {
  1239. $index = ($lower + $upper) >> 1;
  1240. $item = $ringKeys[$index];
  1241. if ($item > $key) {
  1242. $upper = $index - 1;
  1243. }
  1244. else if ($item < $key) {
  1245. $lower = $index + 1;
  1246. }
  1247. else {
  1248. return $item;
  1249. }
  1250. }
  1251. return $ringKeys[$upper >= 0 ? $upper : count($ringKeys) - 1];
  1252. }
  1253. }
  1254. abstract class MultiBulkResponseIteratorBase implements \Iterator, \Countable {
  1255. protected $_position, $_current, $_replySize;
  1256. public function rewind() {
  1257. // NOOP
  1258. }
  1259. public function current() {
  1260. return $this->_current;
  1261. }
  1262. public function key() {
  1263. return $this->_position;
  1264. }
  1265. public function next() {
  1266. if (++$this->_position < $this->_replySize) {
  1267. $this->_current = $this->getValue();
  1268. }
  1269. return $this->_position;
  1270. }
  1271. public function valid() {
  1272. return $this->_position < $this->_replySize;
  1273. }
  1274. public function count() {
  1275. // NOTE: use count if you want to get the size of the current multi-bulk
  1276. // response without using iterator_count (which actually consumes
  1277. // our iterator to calculate the size, and we cannot perform a rewind)
  1278. return $this->_replySize;
  1279. }
  1280. protected abstract function getValue();
  1281. }
  1282. class MultiBulkResponseIterator extends MultiBulkResponseIteratorBase {
  1283. private $_connection;
  1284. public function __construct(\Predis\Connection $connection, $size) {
  1285. $this->_connection = $connection;
  1286. $this->_reader = $connection->getResponseReader();
  1287. $this->_position = 0;
  1288. $this->_current = $size > 0 ? $this->getValue() : null;
  1289. $this->_replySize = $size;
  1290. }
  1291. public function __destruct() {
  1292. // when the iterator is garbage-collected (e.g. it goes out of the
  1293. // scope of a foreach) but it has not reached its end, we must sync
  1294. // the client with the queued elements that have not been read from
  1295. // the connection with the server.
  1296. $this->sync();
  1297. }
  1298. public function sync() {
  1299. while ($this->valid()) {
  1300. $this->next();
  1301. }
  1302. }
  1303. protected function getValue() {
  1304. return $this->_reader->read($this->_connection);
  1305. }
  1306. }
  1307. class MultiBulkResponseKVIterator extends MultiBulkResponseIteratorBase {
  1308. private $_iterator;
  1309. public function __construct(MultiBulkResponseIterator $iterator) {
  1310. $virtualSize = count($iterator) / 2;
  1311. $this->_iterator = $iterator;
  1312. $this->_position = 0;
  1313. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1314. $this->_replySize = $virtualSize;
  1315. }
  1316. public function __destruct() {
  1317. $this->_iterator->sync();
  1318. }
  1319. protected function getValue() {
  1320. $k = $this->_iterator->current();
  1321. $this->_iterator->next();
  1322. $v = $this->_iterator->current();
  1323. $this->_iterator->next();
  1324. return array($k, $v);
  1325. }
  1326. }
  1327. /* ------------------------------------------------------------------------- */
  1328. namespace Predis\Commands;
  1329. /* miscellaneous commands */
  1330. class Ping extends \Predis\InlineCommand {
  1331. public function canBeHashed() { return false; }
  1332. public function getCommandId() { return 'PING'; }
  1333. public function parseResponse($data) {
  1334. return $data === 'PONG' ? true : false;
  1335. }
  1336. }
  1337. class DoEcho extends \Predis\BulkCommand {
  1338. public function canBeHashed() { return false; }
  1339. public function getCommandId() { return 'ECHO'; }
  1340. }
  1341. class Auth extends \Predis\InlineCommand {
  1342. public function canBeHashed() { return false; }
  1343. public function getCommandId() { return 'AUTH'; }
  1344. }
  1345. /* connection handling */
  1346. class Quit extends \Predis\InlineCommand {
  1347. public function canBeHashed() { return false; }
  1348. public function getCommandId() { return 'QUIT'; }
  1349. public function closesConnection() { return true; }
  1350. }
  1351. /* commands operating on string values */
  1352. class Set extends \Predis\BulkCommand {
  1353. public function getCommandId() { return 'SET'; }
  1354. }
  1355. class SetPreserve extends \Predis\BulkCommand {
  1356. public function getCommandId() { return 'SETNX'; }
  1357. public function parseResponse($data) { return (bool) $data; }
  1358. }
  1359. class SetMultiple extends \Predis\MultiBulkCommand {
  1360. public function canBeHashed() { return false; }
  1361. public function getCommandId() { return 'MSET'; }
  1362. }
  1363. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1364. public function canBeHashed() { return false; }
  1365. public function getCommandId() { return 'MSETNX'; }
  1366. public function parseResponse($data) { return (bool) $data; }
  1367. }
  1368. class Get extends \Predis\InlineCommand {
  1369. public function getCommandId() { return 'GET'; }
  1370. }
  1371. class GetMultiple extends \Predis\InlineCommand {
  1372. public function canBeHashed() { return false; }
  1373. public function getCommandId() { return 'MGET'; }
  1374. }
  1375. class GetSet extends \Predis\BulkCommand {
  1376. public function getCommandId() { return 'GETSET'; }
  1377. }
  1378. class Increment extends \Predis\InlineCommand {
  1379. public function getCommandId() { return 'INCR'; }
  1380. }
  1381. class IncrementBy extends \Predis\InlineCommand {
  1382. public function getCommandId() { return 'INCRBY'; }
  1383. }
  1384. class Decrement extends \Predis\InlineCommand {
  1385. public function getCommandId() { return 'DECR'; }
  1386. }
  1387. class DecrementBy extends \Predis\InlineCommand {
  1388. public function getCommandId() { return 'DECRBY'; }
  1389. }
  1390. class Exists extends \Predis\InlineCommand {
  1391. public function getCommandId() { return 'EXISTS'; }
  1392. public function parseResponse($data) { return (bool) $data; }
  1393. }
  1394. class Delete extends \Predis\InlineCommand {
  1395. public function getCommandId() { return 'DEL'; }
  1396. public function parseResponse($data) { return (bool) $data; }
  1397. }
  1398. class Type extends \Predis\InlineCommand {
  1399. public function getCommandId() { return 'TYPE'; }
  1400. }
  1401. class Append extends \Predis\BulkCommand {
  1402. public function getCommandId() { return 'APPEND'; }
  1403. }
  1404. class Substr extends \Predis\InlineCommand {
  1405. public function getCommandId() { return 'SUBSTR'; }
  1406. }
  1407. /* commands operating on the key space */
  1408. class Keys extends \Predis\InlineCommand {
  1409. public function canBeHashed() { return false; }
  1410. public function getCommandId() { return 'KEYS'; }
  1411. public function parseResponse($data) {
  1412. // TODO: is this behaviour correct?
  1413. if (is_array($data) || $data instanceof \Iterator) {
  1414. return $data;
  1415. }
  1416. return strlen($data) > 0 ? explode(' ', $data) : array();
  1417. }
  1418. }
  1419. class RandomKey extends \Predis\InlineCommand {
  1420. public function canBeHashed() { return false; }
  1421. public function getCommandId() { return 'RANDOMKEY'; }
  1422. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1423. }
  1424. class Rename extends \Predis\InlineCommand {
  1425. public function canBeHashed() { return false; }
  1426. public function getCommandId() { return 'RENAME'; }
  1427. }
  1428. class RenamePreserve extends \Predis\InlineCommand {
  1429. public function canBeHashed() { return false; }
  1430. public function getCommandId() { return 'RENAMENX'; }
  1431. public function parseResponse($data) { return (bool) $data; }
  1432. }
  1433. class Expire extends \Predis\InlineCommand {
  1434. public function getCommandId() { return 'EXPIRE'; }
  1435. public function parseResponse($data) { return (bool) $data; }
  1436. }
  1437. class ExpireAt extends \Predis\InlineCommand {
  1438. public function getCommandId() { return 'EXPIREAT'; }
  1439. public function parseResponse($data) { return (bool) $data; }
  1440. }
  1441. class DatabaseSize extends \Predis\InlineCommand {
  1442. public function canBeHashed() { return false; }
  1443. public function getCommandId() { return 'DBSIZE'; }
  1444. }
  1445. class TimeToLive extends \Predis\InlineCommand {
  1446. public function getCommandId() { return 'TTL'; }
  1447. }
  1448. /* commands operating on lists */
  1449. class ListPushTail extends \Predis\BulkCommand {
  1450. public function getCommandId() { return 'RPUSH'; }
  1451. }
  1452. class ListPushHead extends \Predis\BulkCommand {
  1453. public function getCommandId() { return 'LPUSH'; }
  1454. }
  1455. class ListLength extends \Predis\InlineCommand {
  1456. public function getCommandId() { return 'LLEN'; }
  1457. }
  1458. class ListRange extends \Predis\InlineCommand {
  1459. public function getCommandId() { return 'LRANGE'; }
  1460. }
  1461. class ListTrim extends \Predis\InlineCommand {
  1462. public function getCommandId() { return 'LTRIM'; }
  1463. }
  1464. class ListIndex extends \Predis\InlineCommand {
  1465. public function getCommandId() { return 'LINDEX'; }
  1466. }
  1467. class ListSet extends \Predis\BulkCommand {
  1468. public function getCommandId() { return 'LSET'; }
  1469. }
  1470. class ListRemove extends \Predis\BulkCommand {
  1471. public function getCommandId() { return 'LREM'; }
  1472. }
  1473. class ListPopLastPushHead extends \Predis\InlineCommand {
  1474. public function getCommandId() { return 'RPOPLPUSH'; }
  1475. }
  1476. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1477. public function getCommandId() { return 'RPOPLPUSH'; }
  1478. }
  1479. class ListPopFirst extends \Predis\InlineCommand {
  1480. public function getCommandId() { return 'LPOP'; }
  1481. }
  1482. class ListPopLast extends \Predis\InlineCommand {
  1483. public function getCommandId() { return 'RPOP'; }
  1484. }
  1485. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1486. public function getCommandId() { return 'BLPOP'; }
  1487. }
  1488. class ListPopLastBlocking extends \Predis\InlineCommand {
  1489. public function getCommandId() { return 'BRPOP'; }
  1490. }
  1491. /* commands operating on sets */
  1492. class SetAdd extends \Predis\BulkCommand {
  1493. public function getCommandId() { return 'SADD'; }
  1494. public function parseResponse($data) { return (bool) $data; }
  1495. }
  1496. class SetRemove extends \Predis\BulkCommand {
  1497. public function getCommandId() { return 'SREM'; }
  1498. public function parseResponse($data) { return (bool) $data; }
  1499. }
  1500. class SetPop extends \Predis\InlineCommand {
  1501. public function getCommandId() { return 'SPOP'; }
  1502. }
  1503. class SetMove extends \Predis\BulkCommand {
  1504. public function canBeHashed() { return false; }
  1505. public function getCommandId() { return 'SMOVE'; }
  1506. public function parseResponse($data) { return (bool) $data; }
  1507. }
  1508. class SetCardinality extends \Predis\InlineCommand {
  1509. public function getCommandId() { return 'SCARD'; }
  1510. }
  1511. class SetIsMember extends \Predis\BulkCommand {
  1512. public function getCommandId() { return 'SISMEMBER'; }
  1513. public function parseResponse($data) { return (bool) $data; }
  1514. }
  1515. class SetIntersection extends \Predis\InlineCommand {
  1516. public function getCommandId() { return 'SINTER'; }
  1517. }
  1518. class SetIntersectionStore extends \Predis\InlineCommand {
  1519. public function getCommandId() { return 'SINTERSTORE'; }
  1520. }
  1521. class SetUnion extends \Predis\InlineCommand {
  1522. public function getCommandId() { return 'SUNION'; }
  1523. }
  1524. class SetUnionStore extends \Predis\InlineCommand {
  1525. public function getCommandId() { return 'SUNIONSTORE'; }
  1526. }
  1527. class SetDifference extends \Predis\InlineCommand {
  1528. public function getCommandId() { return 'SDIFF'; }
  1529. }
  1530. class SetDifferenceStore extends \Predis\InlineCommand {
  1531. public function getCommandId() { return 'SDIFFSTORE'; }
  1532. }
  1533. class SetMembers extends \Predis\InlineCommand {
  1534. public function getCommandId() { return 'SMEMBERS'; }
  1535. }
  1536. class SetRandomMember extends \Predis\InlineCommand {
  1537. public function getCommandId() { return 'SRANDMEMBER'; }
  1538. }
  1539. /* commands operating on sorted sets */
  1540. class ZSetAdd extends \Predis\BulkCommand {
  1541. public function getCommandId() { return 'ZADD'; }
  1542. public function parseResponse($data) { return (bool) $data; }
  1543. }
  1544. class ZSetIncrementBy extends \Predis\BulkCommand {
  1545. public function getCommandId() { return 'ZINCRBY'; }
  1546. }
  1547. class ZSetRemove extends \Predis\BulkCommand {
  1548. public function getCommandId() { return 'ZREM'; }
  1549. public function parseResponse($data) { return (bool) $data; }
  1550. }
  1551. class ZSetUnion extends \Predis\InlineCommand {
  1552. public function getCommandId() { return 'ZUNION'; }
  1553. }
  1554. class ZSetIntersection extends \Predis\InlineCommand {
  1555. public function getCommandId() { return 'ZINTER'; }
  1556. }
  1557. class ZSetRange extends \Predis\InlineCommand {
  1558. public function getCommandId() { return 'ZRANGE'; }
  1559. public function parseResponse($data) {
  1560. $arguments = $this->getArguments();
  1561. if (count($arguments) === 4) {
  1562. if (strtolower($arguments[3]) === 'withscores') {
  1563. if ($data instanceof \Iterator) {
  1564. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1565. }
  1566. $result = array();
  1567. for ($i = 0; $i < count($data); $i++) {
  1568. $result[] = array($data[$i], $data[++$i]);
  1569. }
  1570. return $result;
  1571. }
  1572. }
  1573. return $data;
  1574. }
  1575. }
  1576. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1577. public function getCommandId() { return 'ZREVRANGE'; }
  1578. }
  1579. class ZSetRangeByScore extends \Predis\Commands\ZSetRange {
  1580. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1581. }
  1582. class ZSetCount extends \Predis\InlineCommand {
  1583. public function getCommandId() { return 'ZCOUNT'; }
  1584. }
  1585. class ZSetCardinality extends \Predis\InlineCommand {
  1586. public function getCommandId() { return 'ZCARD'; }
  1587. }
  1588. class ZSetScore extends \Predis\BulkCommand {
  1589. public function getCommandId() { return 'ZSCORE'; }
  1590. }
  1591. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1592. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1593. }
  1594. class ZSetRank extends \Predis\BulkCommand {
  1595. public function getCommandId() { return 'ZRANK'; }
  1596. }
  1597. class ZSetReverseRank extends \Predis\BulkCommand {
  1598. public function getCommandId() { return 'ZREVRANK'; }
  1599. }
  1600. class ZSetRemoveRangeByRank extends \Predis\InlineCommand {
  1601. public function getCommandId() { return 'ZREMRANGEBYRANK'; }
  1602. }
  1603. /* commands operating on hashes */
  1604. class HashSet extends \Predis\MultiBulkCommand {
  1605. public function getCommandId() { return 'HSET'; }
  1606. }
  1607. class HashIncrementBy extends \Predis\InlineCommand {
  1608. public function getCommandId() { return 'HINCRBY'; }
  1609. }
  1610. class HashGet extends \Predis\BulkCommand {
  1611. public function getCommandId() { return 'HGET'; }
  1612. }
  1613. class HashDelete extends \Predis\BulkCommand {
  1614. public function getCommandId() { return 'HDEL'; }
  1615. }
  1616. class HashExists extends \Predis\BulkCommand {
  1617. public function getCommandId() { return 'HEXISTS'; }
  1618. }
  1619. class HashLength extends \Predis\InlineCommand {
  1620. public function getCommandId() { return 'HLEN'; }
  1621. }
  1622. class HashKeys extends \Predis\InlineCommand {
  1623. public function getCommandId() { return 'HKEYS'; }
  1624. }
  1625. class HashValues extends \Predis\InlineCommand {
  1626. public function getCommandId() { return 'HVALS'; }
  1627. }
  1628. class HashGetAll extends \Predis\InlineCommand {
  1629. public function getCommandId() { return 'HGETALL'; }
  1630. }
  1631. /* multiple databases handling commands */
  1632. class SelectDatabase extends \Predis\InlineCommand {
  1633. public function canBeHashed() { return false; }
  1634. public function getCommandId() { return 'SELECT'; }
  1635. }
  1636. class MoveKey extends \Predis\InlineCommand {
  1637. public function canBeHashed() { return false; }
  1638. public function getCommandId() { return 'MOVE'; }
  1639. public function parseResponse($data) { return (bool) $data; }
  1640. }
  1641. class FlushDatabase extends \Predis\InlineCommand {
  1642. public function canBeHashed() { return false; }
  1643. public function getCommandId() { return 'FLUSHDB'; }
  1644. }
  1645. class FlushAll extends \Predis\InlineCommand {
  1646. public function canBeHashed() { return false; }
  1647. public function getCommandId() { return 'FLUSHALL'; }
  1648. }
  1649. /* sorting */
  1650. class Sort extends \Predis\InlineCommand {
  1651. public function getCommandId() { return 'SORT'; }
  1652. public function filterArguments(Array $arguments) {
  1653. if (count($arguments) === 1) {
  1654. return $arguments;
  1655. }
  1656. // TODO: add more parameters checks
  1657. $query = array($arguments[0]);
  1658. $sortParams = $arguments[1];
  1659. if (isset($sortParams['by'])) {
  1660. $query[] = 'BY ' . $sortParams['by'];
  1661. }
  1662. if (isset($sortParams['get'])) {
  1663. $getargs = $sortParams['get'];
  1664. if (is_array($getargs)) {
  1665. foreach ($getargs as $getarg) {
  1666. $query[] = 'GET ' . $getarg;
  1667. }
  1668. }
  1669. else {
  1670. $query[] = 'GET ' . $getargs;
  1671. }
  1672. }
  1673. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1674. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1675. }
  1676. if (isset($sortParams['sort'])) {
  1677. $query[] = strtoupper($sortParams['sort']);
  1678. }
  1679. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1680. $query[] = 'ALPHA';
  1681. }
  1682. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1683. $query[] = 'STORE ' . $sortParams['store'];
  1684. }
  1685. return $query;
  1686. }
  1687. }
  1688. /* persistence control commands */
  1689. class Save extends \Predis\InlineCommand {
  1690. public function canBeHashed() { return false; }
  1691. public function getCommandId() { return 'SAVE'; }
  1692. }
  1693. class BackgroundSave extends \Predis\InlineCommand {
  1694. public function canBeHashed() { return false; }
  1695. public function getCommandId() { return 'BGSAVE'; }
  1696. public function parseResponse($data) {
  1697. if ($data == 'Background saving started') {
  1698. return true;
  1699. }
  1700. return $data;
  1701. }
  1702. }
  1703. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1704. public function canBeHashed() { return false; }
  1705. public function getCommandId() { return 'BGREWRITEAOF'; }
  1706. public function parseResponse($data) {
  1707. return $data == 'Background append only file rewriting started';
  1708. }
  1709. }
  1710. class LastSave extends \Predis\InlineCommand {
  1711. public function canBeHashed() { return false; }
  1712. public function getCommandId() { return 'LASTSAVE'; }
  1713. }
  1714. class Shutdown extends \Predis\InlineCommand {
  1715. public function canBeHashed() { return false; }
  1716. public function getCommandId() { return 'SHUTDOWN'; }
  1717. public function closesConnection() { return true; }
  1718. }
  1719. /* remote server control commands */
  1720. class Info extends \Predis\InlineCommand {
  1721. public function canBeHashed() { return false; }
  1722. public function getCommandId() { return 'INFO'; }
  1723. public function parseResponse($data) {
  1724. $info = array();
  1725. $infoLines = explode("\r\n", $data, -1);
  1726. foreach ($infoLines as $row) {
  1727. list($k, $v) = explode(':', $row);
  1728. if (!preg_match('/^db\d+$/', $k)) {
  1729. $info[$k] = $v;
  1730. }
  1731. else {
  1732. $db = array();
  1733. foreach (explode(',', $v) as $dbvar) {
  1734. list($dbvk, $dbvv) = explode('=', $dbvar);
  1735. $db[trim($dbvk)] = $dbvv;
  1736. }
  1737. $info[$k] = $db;
  1738. }
  1739. }
  1740. return $info;
  1741. }
  1742. }
  1743. class SlaveOf extends \Predis\InlineCommand {
  1744. public function canBeHashed() { return false; }
  1745. public function getCommandId() { return 'SLAVEOF'; }
  1746. public function filterArguments(Array $arguments) {
  1747. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1748. }
  1749. }
  1750. class Config extends \Predis\BulkCommand {
  1751. public function canBeHashed() { return false; }
  1752. public function getCommandId() { return 'CONFIG'; }
  1753. }
  1754. class Multi extends \Predis\InlineCommand {
  1755. public function canBeHashed() { return false; }
  1756. public function getCommandId() { return 'MULTI'; }
  1757. }
  1758. class Exec extends \Predis\InlineCommand {
  1759. public function canBeHashed() { return false; }
  1760. public function getCommandId() { return 'EXEC'; }
  1761. }
  1762. class Discard extends \Predis\InlineCommand {
  1763. public function canBeHashed() { return false; }
  1764. public function getCommandId() { return 'DISCARD'; }
  1765. }
  1766. ?>