Predis.php 95 KB

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