Predis.php 77 KB

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