Predis.php 76 KB

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