Predis.php 97 KB

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