Predis.php 99 KB

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