Predis.php 97 KB

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