Predis.php 81 KB

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