Predis.php 72 KB

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