Predis.php 92 KB

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