Predis.php 93 KB

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