Predis.php 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. <?php
  2. namespace Predis;
  3. class PredisException extends \Exception { }
  4. class ClientException extends PredisException { }
  5. class ServerException extends PredisException { }
  6. class MalformedServerResponse extends ServerException { }
  7. /* ------------------------------------------------------------------------- */
  8. class Client {
  9. private $_connection, $_serverProfile;
  10. public function __construct($parameters = null, RedisServerProfile $serverProfile = null) {
  11. $this->setProfile($serverProfile ?: RedisServerProfile::getDefault());
  12. $this->setupConnection($parameters);
  13. }
  14. public function __destruct() {
  15. $this->_connection->disconnect();
  16. }
  17. public static function create(/* arguments */) {
  18. $argv = func_get_args();
  19. $argc = func_num_args();
  20. $serverProfile = null;
  21. $lastArg = $argv[$argc-1];
  22. if ($argc > 0 && !is_string($lastArg) && is_subclass_of($lastArg, '\Predis\RedisServerProfile')) {
  23. $serverProfile = array_pop($argv);
  24. $argc--;
  25. }
  26. if ($argc === 0) {
  27. throw new ClientException('Missing connection parameters');
  28. }
  29. return new Client($argc === 1 ? $argv[0] : $argv, $serverProfile);
  30. }
  31. private function setupConnection($parameters) {
  32. if ($parameters !== null && !(is_array($parameters) || is_string($parameters))) {
  33. throw new ClientException('Invalid parameters type (array or string expected)');
  34. }
  35. if (is_array($parameters) && isset($parameters[0])) {
  36. $cluster = new ConnectionCluster();
  37. foreach ($parameters as $shardParams) {
  38. $cluster->add($this->createConnection($shardParams));
  39. }
  40. $this->setConnection($cluster);
  41. }
  42. else {
  43. $this->setConnection($this->createConnection($parameters));
  44. }
  45. }
  46. private function createConnection($parameters) {
  47. $params = new ConnectionParameters($parameters);
  48. $connection = new Connection($params);
  49. if ($params->password !== null) {
  50. $connection->pushInitCommand($this->createCommand(
  51. 'auth', array($params->password)
  52. ));
  53. }
  54. if ($params->database !== null) {
  55. $connection->pushInitCommand($this->createCommand(
  56. 'select', array($params->database)
  57. ));
  58. }
  59. return $connection;
  60. }
  61. private function setConnection(IConnection $connection) {
  62. $this->_connection = $connection;
  63. }
  64. public function setProfile(RedisServerProfile $serverProfile) {
  65. $this->_serverProfile = $serverProfile;
  66. }
  67. public function getProfile() {
  68. return $this->_serverProfile;
  69. }
  70. public function useMultiBulkIterator($value = true) {
  71. Response::useMultiBulkIterator($value);
  72. }
  73. public function connect() {
  74. $this->_connection->connect();
  75. }
  76. public function disconnect() {
  77. $this->_connection->disconnect();
  78. }
  79. public function isConnected() {
  80. return $this->_connection->isConnected();
  81. }
  82. public function getConnection() {
  83. return $this->_connection;
  84. }
  85. public function __call($method, $arguments) {
  86. $command = $this->_serverProfile->createCommand($method, $arguments);
  87. return $this->executeCommand($command);
  88. }
  89. public function createCommand($method, $arguments = array()) {
  90. return $this->_serverProfile->createCommand($method, $arguments);
  91. }
  92. private function executeCommandInternal(IConnection $connection, Command $command) {
  93. $connection->writeCommand($command);
  94. if ($command->closesConnection()) {
  95. return $connection->disconnect();
  96. }
  97. return $connection->readResponse($command);
  98. }
  99. public function executeCommand(Command $command) {
  100. return self::executeCommandInternal($this->_connection, $command);
  101. }
  102. public function executeCommandOnShards(Command $command) {
  103. $replies = array();
  104. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  105. foreach($this->_connection as $connection) {
  106. $replies[] = self::executeCommandInternal($connection, $command);
  107. }
  108. }
  109. else {
  110. $replies[] = self::executeCommandInternal($this->_connection, $command);
  111. }
  112. return $replies;
  113. }
  114. public function rawCommand($rawCommandData, $closesConnection = false) {
  115. if (is_a($this->_connection, '\Predis\ConnectionCluster')) {
  116. throw new ClientException('Cannot send raw commands when connected to a cluster of Redis servers');
  117. }
  118. return $this->_connection->rawCommand($rawCommandData, $closesConnection);
  119. }
  120. public function pipeline($pipelineBlock = null) {
  121. $pipeline = new CommandPipeline($this);
  122. return $pipelineBlock !== null ? $pipeline->execute($pipelineBlock) : $pipeline;
  123. }
  124. public function multiExec($multiExecBlock = null) {
  125. $multiExec = new MultiExecBlock($this);
  126. return $multiExecBlock !== null ? $multiExec->execute($multiExecBlock) : $multiExec;
  127. }
  128. }
  129. /* ------------------------------------------------------------------------- */
  130. abstract class Command {
  131. private $_arguments, $_hash;
  132. public abstract function getCommandId();
  133. public abstract function serializeRequest($command, $arguments);
  134. public function canBeHashed() {
  135. return true;
  136. }
  137. public function getHash() {
  138. if (isset($this->_hash)) {
  139. return $this->_hash;
  140. }
  141. else {
  142. if (isset($this->_arguments[0])) {
  143. $key = $this->_arguments[0];
  144. $start = strpos($key, '{');
  145. $end = strpos($key, '}');
  146. if ($start !== false && $end !== false) {
  147. $key = substr($key, ++$start, $end - $start);
  148. }
  149. $this->_hash = crc32($key);
  150. return $this->_hash;
  151. }
  152. }
  153. return null;
  154. }
  155. public function closesConnection() {
  156. return false;
  157. }
  158. protected function filterArguments(Array $arguments) {
  159. return $arguments;
  160. }
  161. public function setArguments(/* arguments */) {
  162. $this->_arguments = $this->filterArguments(func_get_args());
  163. }
  164. public function setArgumentsArray(Array $arguments) {
  165. $this->_arguments = $this->filterArguments($arguments);
  166. }
  167. protected function getArguments() {
  168. return isset($this->_arguments) ? $this->_arguments : array();
  169. }
  170. public function getArgument($index = 0) {
  171. return isset($this->_arguments[$index]) ? $this->_arguments[$index] : null;
  172. }
  173. public function parseResponse($data) {
  174. return $data;
  175. }
  176. public final function __invoke() {
  177. return $this->serializeRequest($this->getCommandId(), $this->getArguments());
  178. }
  179. }
  180. abstract class InlineCommand extends Command {
  181. public function serializeRequest($command, $arguments) {
  182. if (isset($arguments[0]) && is_array($arguments[0])) {
  183. $arguments[0] = implode($arguments[0], ' ');
  184. }
  185. return $command . ' ' . implode($arguments, ' ') . Response::NEWLINE;
  186. }
  187. }
  188. abstract class BulkCommand extends Command {
  189. public function serializeRequest($command, $arguments) {
  190. $data = array_pop($arguments);
  191. if (is_array($data)) {
  192. $data = implode($data, ' ');
  193. }
  194. return $command . ' ' . implode($arguments, ' ') . ' ' . strlen($data) .
  195. Response::NEWLINE . $data . Response::NEWLINE;
  196. }
  197. }
  198. abstract class MultiBulkCommand extends Command {
  199. public function serializeRequest($command, $arguments) {
  200. $buffer = array();
  201. $cmd_args = null;
  202. if (count($arguments) === 1 && is_array($arguments[0])) {
  203. $cmd_args = array();
  204. foreach ($arguments[0] as $k => $v) {
  205. $cmd_args[] = $k;
  206. $cmd_args[] = $v;
  207. }
  208. }
  209. else {
  210. $cmd_args = $arguments;
  211. }
  212. $buffer[] = '*' . ((string) count($cmd_args) + 1) . Response::NEWLINE;
  213. $buffer[] = '$' . strlen($command) . Response::NEWLINE . $command . Response::NEWLINE;
  214. foreach ($cmd_args as $argument) {
  215. $buffer[] = '$' . strlen($argument) . Response::NEWLINE . $argument . Response::NEWLINE;
  216. }
  217. return implode('', $buffer);
  218. }
  219. }
  220. /* ------------------------------------------------------------------------- */
  221. interface IResponseHandler {
  222. function handle($socket, $prefix, $payload);
  223. }
  224. class ResponseStatusHandler implements IResponseHandler {
  225. public function handle($socket, $prefix, $status) {
  226. if ($status === Response::OK) {
  227. return true;
  228. }
  229. else if ($status === Response::QUEUED) {
  230. return new ResponseQueued();
  231. }
  232. return $status;
  233. }
  234. }
  235. class ResponseErrorHandler implements IResponseHandler {
  236. public function handle($socket, $prefix, $errorMessage) {
  237. throw new ServerException(substr($errorMessage, 4));
  238. }
  239. }
  240. class ResponseBulkHandler implements IResponseHandler {
  241. public function handle($socket, $prefix, $dataLength) {
  242. if (!is_numeric($dataLength)) {
  243. throw new ClientException("Cannot parse '$dataLength' as data length");
  244. }
  245. if ($dataLength > 0) {
  246. $value = stream_get_contents($socket, $dataLength);
  247. if ($value === false) {
  248. throw new ClientException('An error has occurred while reading from the network stream');
  249. }
  250. fread($socket, 2);
  251. return $value;
  252. }
  253. else if ($dataLength == 0) {
  254. fread($socket, 2);
  255. return '';
  256. }
  257. return null;
  258. }
  259. }
  260. class ResponseMultiBulkHandler implements IResponseHandler {
  261. public function handle($socket, $prefix, $rawLength) {
  262. if (!is_numeric($rawLength)) {
  263. throw new ClientException("Cannot parse '$rawLength' as data length");
  264. }
  265. $listLength = (int) $rawLength;
  266. if ($listLength === -1) {
  267. return null;
  268. }
  269. $list = array();
  270. if ($listLength > 0) {
  271. for ($i = 0; $i < $listLength; $i++) {
  272. $list[] = Response::read($socket);
  273. }
  274. }
  275. return $list;
  276. }
  277. }
  278. class ResponseMultiBulkStreamHandler implements IResponseHandler {
  279. public function handle($socket, $prefix, $rawLength) {
  280. if (!is_numeric($rawLength)) {
  281. throw new ClientException("Cannot parse '$rawLength' as data length");
  282. }
  283. return new Utilities\MultiBulkResponseIterator($socket, (int)$rawLength);
  284. }
  285. }
  286. class ResponseIntegerHandler implements IResponseHandler {
  287. public function handle($socket, $prefix, $number) {
  288. if (is_numeric($number)) {
  289. return (int) $number;
  290. }
  291. else {
  292. if ($number !== Response::NULL) {
  293. throw new ClientException("Cannot parse '$number' as numeric response");
  294. }
  295. return null;
  296. }
  297. }
  298. }
  299. class Response {
  300. const NEWLINE = "\r\n";
  301. const OK = 'OK';
  302. const ERROR = 'ERR';
  303. const QUEUED = 'QUEUED';
  304. const NULL = 'nil';
  305. private static $_prefixHandlers, $_useMultiBulkIterator;
  306. private static function initializePrefixHandlers() {
  307. return array(
  308. '+' => new ResponseStatusHandler(),
  309. '-' => new ResponseErrorHandler(),
  310. ':' => new ResponseIntegerHandler(),
  311. '$' => new ResponseBulkHandler(),
  312. '*' => self::$_useMultiBulkIterator
  313. ? new ResponseMultiBulkStreamHandler()
  314. : new ResponseMultiBulkHandler()
  315. );
  316. }
  317. public static function useMultiBulkIterator($value = null) {
  318. if (is_bool($value)) {
  319. self::$_useMultiBulkIterator = $value;
  320. self::$_prefixHandlers = self::initializePrefixHandlers();
  321. }
  322. else {
  323. return self::$_useMultiBulkIterator;
  324. }
  325. }
  326. public static function read($socket) {
  327. $header = fgets($socket);
  328. if ($header === false) {
  329. throw new ClientException('An error has occurred while reading from the network stream');
  330. }
  331. $prefix = $header[0];
  332. $payload = substr($header, 1, -2);
  333. if (!isset(self::$_prefixHandlers)) {
  334. self::$_prefixHandlers = self::initializePrefixHandlers();
  335. }
  336. if (!isset(self::$_prefixHandlers[$prefix])) {
  337. throw new MalformedServerResponse("Unknown prefix '$prefix'");
  338. }
  339. $handler = self::$_prefixHandlers[$prefix];
  340. return $handler->handle($socket, $prefix, $payload);
  341. }
  342. }
  343. class ResponseQueued {
  344. public $queued = true;
  345. public function __toString() {
  346. return Response::QUEUED;
  347. }
  348. }
  349. /* ------------------------------------------------------------------------- */
  350. class CommandPipeline {
  351. private $_redisClient, $_pipelineBuffer, $_returnValues, $_running;
  352. public function __construct(Client $redisClient) {
  353. $this->_redisClient = $redisClient;
  354. $this->_pipelineBuffer = array();
  355. $this->_returnValues = array();
  356. }
  357. public function __call($method, $arguments) {
  358. $command = $this->_redisClient->createCommand($method, $arguments);
  359. $this->recordCommand($command);
  360. }
  361. private function recordCommand(Command $command) {
  362. $this->_pipelineBuffer[] = $command;
  363. }
  364. private function getRecordedCommands() {
  365. return $this->_pipelineBuffer;
  366. }
  367. public function flushPipeline() {
  368. $sizeofPipe = count($this->_pipelineBuffer);
  369. if ($sizeofPipe === 0) {
  370. return;
  371. }
  372. $connection = $this->_redisClient->getConnection();
  373. $commands = &$this->_pipelineBuffer;
  374. foreach ($commands as $command) {
  375. $connection->writeCommand($command);
  376. }
  377. for ($i = 0; $i < $sizeofPipe; $i++) {
  378. $response = $connection->readResponse($commands[$i]);
  379. $this->_returnValues[] = ($response instanceof \Iterator
  380. ? iterator_to_array($response)
  381. : $response
  382. );
  383. unset($commands[$i]);
  384. }
  385. }
  386. private function setRunning($bool) {
  387. if ($bool == true && $this->_running == true) {
  388. throw new ClientException("This pipeline is already opened");
  389. }
  390. $this->_running = $bool;
  391. }
  392. public function execute($block = null) {
  393. if ($block && !is_callable($block)) {
  394. throw new \RuntimeException('Argument passed must be a callable object');
  395. }
  396. $this->setRunning(true);
  397. $pipelineBlockException = null;
  398. try {
  399. if ($block !== null) {
  400. $block($this);
  401. }
  402. $this->flushPipeline();
  403. }
  404. catch (\Exception $exception) {
  405. $pipelineBlockException = $exception;
  406. }
  407. $this->setRunning(false);
  408. if ($pipelineBlockException !== null) {
  409. throw $pipelineBlockException;
  410. }
  411. return $this->_returnValues;
  412. }
  413. }
  414. class MultiExecBlock {
  415. private $_redisClient, $_commands, $_initialized;
  416. public function __construct(Client $redisClient) {
  417. $this->_initialized = false;
  418. $this->_redisClient = $redisClient;
  419. $this->_commands = array();
  420. }
  421. private function initialize() {
  422. if ($this->_initialized === false) {
  423. $this->_redisClient->multi();
  424. $this->_initialized = true;
  425. }
  426. }
  427. public function __call($method, $arguments) {
  428. $this->initialize();
  429. $command = $this->_redisClient->createCommand($method, $arguments);
  430. $response = $this->_redisClient->executeCommand($command);
  431. if (isset($response->queued)) {
  432. $this->_commands[] = $command;
  433. return $response;
  434. }
  435. else {
  436. throw new ClientException('The server did not respond with a QUEUED status reply');
  437. }
  438. }
  439. public function execute($block = null) {
  440. if ($block && !is_callable($block)) {
  441. throw new \RuntimeException('Argument passed must be a callable object');
  442. }
  443. $blockException = null;
  444. $returnValues = array();
  445. try {
  446. if ($block !== null) {
  447. $block($this);
  448. }
  449. $execReply = (($reply = $this->_redisClient->exec()) instanceof \Iterator
  450. ? iterator_to_array($reply)
  451. : $reply
  452. );
  453. $commands = &$this->_commands;
  454. $sizeofReplies = count($execReply);
  455. if ($sizeofReplies !== count($commands)) {
  456. // TODO: think of a better exception message
  457. throw new ClientException("Out-of-sync");
  458. }
  459. for ($i = 0; $i < $sizeofReplies; $i++) {
  460. $returnValues[] = $commands[$i]->parseResponse($execReply[$i] instanceof \Iterator
  461. ? iterator_to_array($execReply[$i])
  462. : $execReply[$i]
  463. );
  464. unset($commands[$i]);
  465. }
  466. }
  467. catch (\Exception $exception) {
  468. $blockException = $exception;
  469. }
  470. if ($blockException !== null) {
  471. throw $blockException;
  472. }
  473. return $returnValues;
  474. }
  475. }
  476. /* ------------------------------------------------------------------------- */
  477. class ConnectionParameters {
  478. const DEFAULT_HOST = '127.0.0.1';
  479. const DEFAULT_PORT = 6379;
  480. private $_parameters;
  481. public function __construct($parameters) {
  482. $parameters = $parameters ?: array();
  483. $this->_parameters = is_array($parameters)
  484. ? self::filterConnectionParams($parameters)
  485. : self::parseURI($parameters);
  486. }
  487. private static function parseURI($uri) {
  488. $parsed = @parse_url($uri);
  489. if ($parsed == false || $parsed['scheme'] != 'redis' || $parsed['host'] == null) {
  490. throw new ClientException("Invalid URI: $uri");
  491. }
  492. if (array_key_exists('query', $parsed)) {
  493. $details = array();
  494. foreach (explode('&', $parsed['query']) as $kv) {
  495. list($k, $v) = explode('=', $kv);
  496. switch ($k) {
  497. case 'database':
  498. $details['database'] = $v;
  499. break;
  500. case 'password':
  501. $details['password'] = $v;
  502. break;
  503. case 'connection_timeout':
  504. $details['connection_timeout'] = $v;
  505. break;
  506. case 'read_write_timeout':
  507. $details['read_write_timeout'] = $v;
  508. break;
  509. }
  510. }
  511. $parsed = array_merge($parsed, $details);
  512. }
  513. return self::filterConnectionParams($parsed);
  514. }
  515. private static function getParamOrDefault(Array $parameters, $param, $default = null) {
  516. return array_key_exists($param, $parameters) ? $parameters[$param] : $default;
  517. }
  518. private static function filterConnectionParams($parameters) {
  519. return array(
  520. 'host' => self::getParamOrDefault($parameters, 'host', self::DEFAULT_HOST),
  521. 'port' => (int) self::getParamOrDefault($parameters, 'port', self::DEFAULT_PORT),
  522. 'database' => self::getParamOrDefault($parameters, 'database'),
  523. 'password' => self::getParamOrDefault($parameters, 'password'),
  524. 'connection_timeout' => self::getParamOrDefault($parameters, 'connection_timeout'),
  525. 'read_write_timeout' => self::getParamOrDefault($parameters, 'read_write_timeout'),
  526. );
  527. }
  528. public function __get($parameter) {
  529. return $this->_parameters[$parameter];
  530. }
  531. public function __isset($parameter) {
  532. return isset($this->_parameters[$parameter]);
  533. }
  534. }
  535. interface IConnection {
  536. public function connect();
  537. public function disconnect();
  538. public function isConnected();
  539. public function writeCommand(Command $command);
  540. public function readResponse(Command $command);
  541. }
  542. class Connection implements IConnection {
  543. const CONNECTION_TIMEOUT = 2;
  544. private $_params, $_socket, $_initCmds;
  545. public function __construct(ConnectionParameters $parameters) {
  546. $this->_params = $parameters;
  547. $this->_initCmds = array();
  548. }
  549. public function __destruct() {
  550. $this->disconnect();
  551. }
  552. public function isConnected() {
  553. return is_resource($this->_socket);
  554. }
  555. public function connect() {
  556. if ($this->isConnected()) {
  557. throw new ClientException('Connection already estabilished');
  558. }
  559. $uri = sprintf('tcp://%s:%d/', $this->_params->host, $this->_params->port);
  560. $connectionTimeout = $this->_params->connection_timeout ?: self::CONNECTION_TIMEOUT;
  561. $this->_socket = @stream_socket_client($uri, $errno, $errstr, $connectionTimeout);
  562. if (!$this->_socket) {
  563. throw new ClientException(trim($errstr), $errno);
  564. }
  565. if (isset($this->_params->read_write_timeout)) {
  566. stream_set_timeout($this->_socket, $this->_params->read_write_timeout);
  567. }
  568. if (count($this->_initCmds) > 0){
  569. $this->sendInitializationCommands();
  570. }
  571. }
  572. public function disconnect() {
  573. if ($this->isConnected()) {
  574. fclose($this->_socket);
  575. }
  576. }
  577. public function pushInitCommand(Command $command){
  578. $this->_initCmds[] = $command;
  579. }
  580. private function sendInitializationCommands() {
  581. foreach ($this->_initCmds as $command) {
  582. $this->writeCommand($command);
  583. }
  584. foreach ($this->_initCmds as $command) {
  585. $this->readResponse($command);
  586. }
  587. }
  588. public function writeCommand(Command $command) {
  589. $written = fwrite($this->getSocket(), $command());
  590. if ($written === false){
  591. throw new ClientException(sprintf(
  592. 'An error has occurred while writing command %s on the network stream'),
  593. $command->getCommandId()
  594. );
  595. }
  596. }
  597. public function readResponse(Command $command) {
  598. $response = Response::read($this->getSocket());
  599. return isset($response->queued) ? $response : $command->parseResponse($response);
  600. }
  601. public function rawCommand($rawCommandData, $closesConnection = false) {
  602. $socket = $this->getSocket();
  603. $written = fwrite($socket, $rawCommandData);
  604. if ($written === false){
  605. throw new ClientException('An error has occurred while writing a raw command on the network stream');
  606. }
  607. if ($closesConnection) {
  608. return;
  609. }
  610. return Response::read($socket);
  611. }
  612. public function getSocket() {
  613. if (!$this->isConnected()) {
  614. $this->connect();
  615. }
  616. return $this->_socket;
  617. }
  618. public function __toString() {
  619. return sprintf('%s:%d', $this->_params->host, $this->_params->port);
  620. }
  621. }
  622. class ConnectionCluster implements IConnection, \IteratorAggregate {
  623. // TODO: find a clean way to handle connection failures of single nodes.
  624. private $_pool, $_ring;
  625. public function __construct() {
  626. $this->_pool = array();
  627. $this->_ring = new Utilities\HashRing();
  628. }
  629. public function __destruct() {
  630. $this->disconnect();
  631. }
  632. public function isConnected() {
  633. foreach ($this->_pool as $connection) {
  634. if ($connection->isConnected()) {
  635. return true;
  636. }
  637. }
  638. return false;
  639. }
  640. public function connect() {
  641. foreach ($this->_pool as $connection) {
  642. $connection->connect();
  643. }
  644. }
  645. public function disconnect() {
  646. foreach ($this->_pool as $connection) {
  647. $connection->disconnect();
  648. }
  649. }
  650. public function add(Connection $connection) {
  651. $this->_pool[] = $connection;
  652. $this->_ring->add($connection);
  653. }
  654. private function getConnection(Command $command) {
  655. if ($command->canBeHashed() === false) {
  656. throw new ClientException(
  657. sprintf("Cannot send '%s' commands to a cluster of connections.", $command->getCommandId())
  658. );
  659. }
  660. return $this->_ring->get($command->getHash());
  661. }
  662. public function getConnectionById($id = null) {
  663. return $this->_pool[$id ?: 0];
  664. }
  665. public function getIterator() {
  666. return new \ArrayIterator($this->_pool);
  667. }
  668. public function writeCommand(Command $command) {
  669. $this->getConnection($command)->writeCommand($command);
  670. }
  671. public function readResponse(Command $command) {
  672. return $this->getConnection($command)->readResponse($command);
  673. }
  674. }
  675. /* ------------------------------------------------------------------------- */
  676. abstract class RedisServerProfile {
  677. private static $_serverProfiles;
  678. private $_registeredCommands;
  679. public function __construct() {
  680. $this->_registeredCommands = $this->getSupportedCommands();
  681. }
  682. public abstract function getVersion();
  683. protected abstract function getSupportedCommands();
  684. public static function getDefault() {
  685. return self::get('default');
  686. }
  687. private static function predisServerProfiles() {
  688. return array(
  689. '1.0' => '\Predis\RedisServer_v1_0',
  690. '1.2' => '\Predis\RedisServer_v1_2',
  691. 'default' => '\Predis\RedisServer_v1_2',
  692. 'dev' => '\Predis\RedisServer_vNext',
  693. );
  694. }
  695. public static function get($version) {
  696. if (!isset(self::$_serverProfiles)) {
  697. self::$_serverProfiles = self::predisServerProfiles();
  698. }
  699. if (!isset(self::$_serverProfiles[$version])) {
  700. throw new ClientException("Unknown server profile: $version");
  701. }
  702. $profile = self::$_serverProfiles[$version];
  703. return new $profile();
  704. }
  705. public function compareWith($version, $operator = null) {
  706. // one could expect that PHP's version_compare would behave
  707. // the same way if invoked with 2 arguments or 3 arguments
  708. // with the third being NULL, but it is not like that.
  709. // TODO: since version_compare considers 1 < 1.0 < 1.0.0,
  710. // we might need to revise the behavior of this method.
  711. return ($operator === null
  712. ? version_compare($this, $version)
  713. : version_compare($this, $version, $operator)
  714. );
  715. }
  716. public function supportsCommand($command) {
  717. return isset($this->_registeredCommands[$command]);
  718. }
  719. public function createCommand($method, $arguments = array()) {
  720. if (!isset($this->_registeredCommands[$method])) {
  721. throw new ClientException("'$method' is not a registered Redis command");
  722. }
  723. $commandClass = $this->_registeredCommands[$method];
  724. $command = new $commandClass();
  725. $command->setArgumentsArray($arguments);
  726. return $command;
  727. }
  728. public function registerCommands(Array $commands) {
  729. foreach ($commands as $command => $aliases) {
  730. $this->registerCommand($command, $aliases);
  731. }
  732. }
  733. public function registerCommand($command, $aliases) {
  734. $commandReflection = new \ReflectionClass($command);
  735. if (!$commandReflection->isSubclassOf('\Predis\Command')) {
  736. throw new ClientException("Cannot register '$command' as it is not a valid Redis command");
  737. }
  738. if (is_array($aliases)) {
  739. foreach ($aliases as $alias) {
  740. $this->_registeredCommands[$alias] = $command;
  741. }
  742. }
  743. else {
  744. $this->_registeredCommands[$aliases] = $command;
  745. }
  746. }
  747. public function __toString() {
  748. return $this->getVersion();
  749. }
  750. }
  751. class RedisServer_v1_0 extends RedisServerProfile {
  752. public function getVersion() { return '1.0'; }
  753. public function getSupportedCommands() {
  754. return array(
  755. /* miscellaneous commands */
  756. 'ping' => '\Predis\Commands\Ping',
  757. 'echo' => '\Predis\Commands\DoEcho',
  758. 'auth' => '\Predis\Commands\Auth',
  759. /* connection handling */
  760. 'quit' => '\Predis\Commands\Quit',
  761. /* commands operating on string values */
  762. 'set' => '\Predis\Commands\Set',
  763. 'setnx' => '\Predis\Commands\SetPreserve',
  764. 'setPreserve' => '\Predis\Commands\SetPreserve',
  765. 'get' => '\Predis\Commands\Get',
  766. 'mget' => '\Predis\Commands\GetMultiple',
  767. 'getMultiple' => '\Predis\Commands\GetMultiple',
  768. 'getset' => '\Predis\Commands\GetSet',
  769. 'getSet' => '\Predis\Commands\GetSet',
  770. 'incr' => '\Predis\Commands\Increment',
  771. 'increment' => '\Predis\Commands\Increment',
  772. 'incrby' => '\Predis\Commands\IncrementBy',
  773. 'incrementBy' => '\Predis\Commands\IncrementBy',
  774. 'decr' => '\Predis\Commands\Decrement',
  775. 'decrement' => '\Predis\Commands\Decrement',
  776. 'decrby' => '\Predis\Commands\DecrementBy',
  777. 'decrementBy' => '\Predis\Commands\DecrementBy',
  778. 'exists' => '\Predis\Commands\Exists',
  779. 'del' => '\Predis\Commands\Delete',
  780. 'delete' => '\Predis\Commands\Delete',
  781. 'type' => '\Predis\Commands\Type',
  782. /* commands operating on the key space */
  783. 'keys' => '\Predis\Commands\Keys',
  784. 'randomkey' => '\Predis\Commands\RandomKey',
  785. 'randomKey' => '\Predis\Commands\RandomKey',
  786. 'rename' => '\Predis\Commands\Rename',
  787. 'renamenx' => '\Predis\Commands\RenamePreserve',
  788. 'renamePreserve' => '\Predis\Commands\RenamePreserve',
  789. 'expire' => '\Predis\Commands\Expire',
  790. 'expireat' => '\Predis\Commands\ExpireAt',
  791. 'expireAt' => '\Predis\Commands\ExpireAt',
  792. 'dbsize' => '\Predis\Commands\DatabaseSize',
  793. 'databaseSize' => '\Predis\Commands\DatabaseSize',
  794. 'ttl' => '\Predis\Commands\TimeToLive',
  795. 'timeToLive' => '\Predis\Commands\TimeToLive',
  796. /* commands operating on lists */
  797. 'rpush' => '\Predis\Commands\ListPushTail',
  798. 'pushTail' => '\Predis\Commands\ListPushTail',
  799. 'lpush' => '\Predis\Commands\ListPushHead',
  800. 'pushHead' => '\Predis\Commands\ListPushHead',
  801. 'llen' => '\Predis\Commands\ListLength',
  802. 'listLength' => '\Predis\Commands\ListLength',
  803. 'lrange' => '\Predis\Commands\ListRange',
  804. 'listRange' => '\Predis\Commands\ListRange',
  805. 'ltrim' => '\Predis\Commands\ListTrim',
  806. 'listTrim' => '\Predis\Commands\ListTrim',
  807. 'lindex' => '\Predis\Commands\ListIndex',
  808. 'listIndex' => '\Predis\Commands\ListIndex',
  809. 'lset' => '\Predis\Commands\ListSet',
  810. 'listSet' => '\Predis\Commands\ListSet',
  811. 'lrem' => '\Predis\Commands\ListRemove',
  812. 'listRemove' => '\Predis\Commands\ListRemove',
  813. 'lpop' => '\Predis\Commands\ListPopFirst',
  814. 'popFirst' => '\Predis\Commands\ListPopFirst',
  815. 'rpop' => '\Predis\Commands\ListPopLast',
  816. 'popLast' => '\Predis\Commands\ListPopLast',
  817. /* commands operating on sets */
  818. 'sadd' => '\Predis\Commands\SetAdd',
  819. 'setAdd' => '\Predis\Commands\SetAdd',
  820. 'srem' => '\Predis\Commands\SetRemove',
  821. 'setRemove' => '\Predis\Commands\SetRemove',
  822. 'spop' => '\Predis\Commands\SetPop',
  823. 'setPop' => '\Predis\Commands\SetPop',
  824. 'smove' => '\Predis\Commands\SetMove',
  825. 'setMove' => '\Predis\Commands\SetMove',
  826. 'scard' => '\Predis\Commands\SetCardinality',
  827. 'setCardinality' => '\Predis\Commands\SetCardinality',
  828. 'sismember' => '\Predis\Commands\SetIsMember',
  829. 'setIsMember' => '\Predis\Commands\SetIsMember',
  830. 'sinter' => '\Predis\Commands\SetIntersection',
  831. 'setIntersection' => '\Predis\Commands\SetIntersection',
  832. 'sinterstore' => '\Predis\Commands\SetIntersectionStore',
  833. 'setIntersectionStore' => '\Predis\Commands\SetIntersectionStore',
  834. 'sunion' => '\Predis\Commands\SetUnion',
  835. 'setUnion' => '\Predis\Commands\SetUnion',
  836. 'sunionstore' => '\Predis\Commands\SetUnionStore',
  837. 'setUnionStore' => '\Predis\Commands\SetUnionStore',
  838. 'sdiff' => '\Predis\Commands\SetDifference',
  839. 'setDifference' => '\Predis\Commands\SetDifference',
  840. 'sdiffstore' => '\Predis\Commands\SetDifferenceStore',
  841. 'setDifferenceStore' => '\Predis\Commands\SetDifferenceStore',
  842. 'smembers' => '\Predis\Commands\SetMembers',
  843. 'setMembers' => '\Predis\Commands\SetMembers',
  844. 'srandmember' => '\Predis\Commands\SetRandomMember',
  845. 'setRandomMember' => '\Predis\Commands\SetRandomMember',
  846. /* multiple databases handling commands */
  847. 'select' => '\Predis\Commands\SelectDatabase',
  848. 'selectDatabase' => '\Predis\Commands\SelectDatabase',
  849. 'move' => '\Predis\Commands\MoveKey',
  850. 'moveKey' => '\Predis\Commands\MoveKey',
  851. 'flushdb' => '\Predis\Commands\FlushDatabase',
  852. 'flushDatabase' => '\Predis\Commands\FlushDatabase',
  853. 'flushall' => '\Predis\Commands\FlushAll',
  854. 'flushDatabases' => '\Predis\Commands\FlushAll',
  855. /* sorting */
  856. 'sort' => '\Predis\Commands\Sort',
  857. /* remote server control commands */
  858. 'info' => '\Predis\Commands\Info',
  859. 'slaveof' => '\Predis\Commands\SlaveOf',
  860. 'slaveOf' => '\Predis\Commands\SlaveOf',
  861. /* persistence control commands */
  862. 'save' => '\Predis\Commands\Save',
  863. 'bgsave' => '\Predis\Commands\BackgroundSave',
  864. 'backgroundSave' => '\Predis\Commands\BackgroundSave',
  865. 'lastsave' => '\Predis\Commands\LastSave',
  866. 'lastSave' => '\Predis\Commands\LastSave',
  867. 'shutdown' => '\Predis\Commands\Shutdown',
  868. );
  869. }
  870. }
  871. class RedisServer_v1_2 extends RedisServer_v1_0 {
  872. public function getVersion() { return '1.2'; }
  873. public function getSupportedCommands() {
  874. return array_merge(parent::getSupportedCommands(), array(
  875. /* commands operating on string values */
  876. 'mset' => '\Predis\Commands\SetMultiple',
  877. 'setMultiple' => '\Predis\Commands\SetMultiple',
  878. 'msetnx' => '\Predis\Commands\SetMultiplePreserve',
  879. 'setMultiplePreserve' => '\Predis\Commands\SetMultiplePreserve',
  880. /* commands operating on lists */
  881. 'rpoplpush' => '\Predis\Commands\ListPushTailPopFirst',
  882. 'listPopLastPushHead' => '\Predis\Commands\ListPopLastPushHead',
  883. /* commands operating on sorted sets */
  884. 'zadd' => '\Predis\Commands\ZSetAdd',
  885. 'zsetAdd' => '\Predis\Commands\ZSetAdd',
  886. 'zincrby' => '\Predis\Commands\ZSetIncrementBy',
  887. 'zsetIncrementBy' => '\Predis\Commands\ZSetIncrementBy',
  888. 'zrem' => '\Predis\Commands\ZSetRemove',
  889. 'zsetRemove' => '\Predis\Commands\ZSetRemove',
  890. 'zrange' => '\Predis\Commands\ZSetRange',
  891. 'zsetRange' => '\Predis\Commands\ZSetRange',
  892. 'zrevrange' => '\Predis\Commands\ZSetReverseRange',
  893. 'zsetReverseRange' => '\Predis\Commands\ZSetReverseRange',
  894. 'zrangebyscore' => '\Predis\Commands\ZSetRangeByScore',
  895. 'zsetRangeByScore' => '\Predis\Commands\ZSetRangeByScore',
  896. 'zcard' => '\Predis\Commands\ZSetCardinality',
  897. 'zsetCardinality' => '\Predis\Commands\ZSetCardinality',
  898. 'zscore' => '\Predis\Commands\ZSetScore',
  899. 'zsetScore' => '\Predis\Commands\ZSetScore',
  900. 'zremrangebyscore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  901. 'zsetRemoveRangeByScore' => '\Predis\Commands\ZSetRemoveRangeByScore',
  902. /* persistence control commands */
  903. 'bgrewriteaof' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  904. 'backgroundRewriteAppendOnlyFile' => '\Predis\Commands\BackgroundRewriteAppendOnlyFile',
  905. ));
  906. }
  907. }
  908. class RedisServer_vNext extends RedisServer_v1_2 {
  909. public function getVersion() { return '1.3'; }
  910. public function getSupportedCommands() {
  911. return array_merge(parent::getSupportedCommands(), array(
  912. /* miscellaneous commands */
  913. 'multi' => '\Predis\Commands\Multi',
  914. 'exec' => '\Predis\Commands\Exec',
  915. /* commands operating on lists */
  916. 'blpop' => '\Predis\Commands\ListPopFirstBlocking',
  917. 'popFirstBlocking' => '\Predis\Commands\ListPopFirstBlocking',
  918. 'brpop' => '\Predis\Commands\ListPopLastBlocking',
  919. 'popLastBlocking' => '\Predis\Commands\ListPopLastBlocking',
  920. ));
  921. }
  922. }
  923. /* ------------------------------------------------------------------------- */
  924. namespace Predis\Utilities;
  925. class HashRing {
  926. const DEFAULT_REPLICAS = 128;
  927. private $_ring, $_ringKeys, $_replicas;
  928. public function __construct($replicas = self::DEFAULT_REPLICAS) {
  929. $this->_replicas = $replicas;
  930. $this->_ring = array();
  931. $this->_ringKeys = array();
  932. }
  933. public function add($node) {
  934. $nodeHash = (string) $node;
  935. $replicas = $this->_replicas;
  936. for ($i = 0; $i < $replicas; $i++) {
  937. $key = crc32($nodeHash . ':' . $i);
  938. $this->_ring[$key] = $node;
  939. }
  940. ksort($this->_ring, SORT_NUMERIC);
  941. $this->_ringKeys = array_keys($this->_ring);
  942. }
  943. public function remove($node) {
  944. $nodeHash = (string) $node;
  945. $replicas = $this->_replicas;
  946. for ($i = 0; $i < $replicas; $i++) {
  947. $key = crc32($nodeHash . ':' . $i);
  948. unset($this->_ring[$key]);
  949. $this->_ringKeys = array_filter($this->_ringKeys, function($rk) use($key) {
  950. return $rk !== $key;
  951. });
  952. }
  953. }
  954. public function get($key) {
  955. return $this->_ring[$this->getNodeKey($key)];
  956. }
  957. private function getNodeKey($key) {
  958. $ringKeys = $this->_ringKeys;
  959. $upper = count($ringKeys) - 1;
  960. $lower = 0;
  961. $index = 0;
  962. while ($lower <= $upper) {
  963. $index = ($lower + $upper) / 2;
  964. $item = $ringKeys[$index];
  965. if ($item > $key) {
  966. $upper = $index - 1;
  967. }
  968. else if ($item < $key) {
  969. $lower = $index + 1;
  970. }
  971. else {
  972. return $index;
  973. }
  974. }
  975. return $ringKeys[$upper];
  976. }
  977. }
  978. class MultiBulkResponseIterator implements \Iterator, \Countable {
  979. private $_connection, $_position, $_current, $_replySize;
  980. public function __construct($socket, $size) {
  981. $this->_connection = $socket;
  982. $this->_position = 0;
  983. $this->_current = $size > 0 ? $this->getValue() : null;
  984. $this->_replySize = $size;
  985. }
  986. public function __destruct() {
  987. // when the iterator is garbage-collected (e.g. it goes out of the
  988. // scope of a foreach) but it has not reached its end, we must sync
  989. // the client with the queued elements that have not been read from
  990. // the connection with the server.
  991. $this->sync();
  992. }
  993. public function sync() {
  994. while ($this->valid()) {
  995. $this->next();
  996. }
  997. }
  998. public function rewind() {
  999. // NOOP
  1000. }
  1001. public function current() {
  1002. return $this->_current;
  1003. }
  1004. public function key() {
  1005. return $this->_position;
  1006. }
  1007. public function next() {
  1008. if (++$this->_position < $this->_replySize) {
  1009. $this->_current = $this->getValue();
  1010. }
  1011. return $this->_position;
  1012. }
  1013. public function valid() {
  1014. return $this->_position < $this->_replySize;
  1015. }
  1016. public function count() {
  1017. // NOTE: use count if you want to get the size of the current multi-bulk
  1018. // response without using iterator_count (which actually consumes
  1019. // our iterator to calculate the size, and we cannot perform a rewind)
  1020. return $this->_replySize;
  1021. }
  1022. private function getValue() {
  1023. return \Predis\Response::read($this->_connection);
  1024. }
  1025. }
  1026. class MultiBulkResponseKVIterator implements \Iterator, \Countable {
  1027. private $_iterator, $_position, $_current, $_replySize;
  1028. public function __construct(MultiBulkResponseIterator $iterator) {
  1029. $virtualSize = count($iterator) / 2;
  1030. $this->_iterator = $iterator;
  1031. $this->_position = 0;
  1032. $this->_current = $virtualSize > 0 ? $this->getValue() : null;
  1033. $this->_replySize = $virtualSize;
  1034. }
  1035. public function __destruct() {
  1036. $this->_iterator->sync();
  1037. }
  1038. public function rewind() {
  1039. // NOOP
  1040. }
  1041. public function current() {
  1042. return $this->_current;
  1043. }
  1044. public function key() {
  1045. return $this->_position;
  1046. }
  1047. public function next() {
  1048. if (++$this->_position < $this->_replySize) {
  1049. $this->_current = $this->getValue();
  1050. }
  1051. return $this->_position;
  1052. }
  1053. public function valid() {
  1054. return $this->_position < $this->_replySize;
  1055. }
  1056. public function count() {
  1057. return $this->_replySize;
  1058. }
  1059. private function getValue() {
  1060. $k = $this->_iterator->current();
  1061. $this->_iterator->next();
  1062. $v = $this->_iterator->current();
  1063. $this->_iterator->next();
  1064. return array($k, $v);
  1065. }
  1066. }
  1067. /* ------------------------------------------------------------------------- */
  1068. namespace Predis\Commands;
  1069. /* miscellaneous commands */
  1070. class Ping extends \Predis\InlineCommand {
  1071. public function canBeHashed() { return false; }
  1072. public function getCommandId() { return 'PING'; }
  1073. public function parseResponse($data) {
  1074. return $data === 'PONG' ? true : false;
  1075. }
  1076. }
  1077. class DoEcho extends \Predis\BulkCommand {
  1078. public function canBeHashed() { return false; }
  1079. public function getCommandId() { return 'ECHO'; }
  1080. }
  1081. class Auth extends \Predis\InlineCommand {
  1082. public function canBeHashed() { return false; }
  1083. public function getCommandId() { return 'AUTH'; }
  1084. }
  1085. /* connection handling */
  1086. class Quit extends \Predis\InlineCommand {
  1087. public function canBeHashed() { return false; }
  1088. public function getCommandId() { return 'QUIT'; }
  1089. public function closesConnection() { return true; }
  1090. }
  1091. /* commands operating on string values */
  1092. class Set extends \Predis\BulkCommand {
  1093. public function getCommandId() { return 'SET'; }
  1094. }
  1095. class SetPreserve extends \Predis\BulkCommand {
  1096. public function getCommandId() { return 'SETNX'; }
  1097. public function parseResponse($data) { return (bool) $data; }
  1098. }
  1099. class SetMultiple extends \Predis\MultiBulkCommand {
  1100. public function canBeHashed() { return false; }
  1101. public function getCommandId() { return 'MSET'; }
  1102. }
  1103. class SetMultiplePreserve extends \Predis\MultiBulkCommand {
  1104. public function canBeHashed() { return false; }
  1105. public function getCommandId() { return 'MSETNX'; }
  1106. public function parseResponse($data) { return (bool) $data; }
  1107. }
  1108. class Get extends \Predis\InlineCommand {
  1109. public function getCommandId() { return 'GET'; }
  1110. }
  1111. class GetMultiple extends \Predis\InlineCommand {
  1112. public function canBeHashed() { return false; }
  1113. public function getCommandId() { return 'MGET'; }
  1114. }
  1115. class GetSet extends \Predis\BulkCommand {
  1116. public function getCommandId() { return 'GETSET'; }
  1117. }
  1118. class Increment extends \Predis\InlineCommand {
  1119. public function getCommandId() { return 'INCR'; }
  1120. }
  1121. class IncrementBy extends \Predis\InlineCommand {
  1122. public function getCommandId() { return 'INCRBY'; }
  1123. }
  1124. class Decrement extends \Predis\InlineCommand {
  1125. public function getCommandId() { return 'DECR'; }
  1126. }
  1127. class DecrementBy extends \Predis\InlineCommand {
  1128. public function getCommandId() { return 'DECRBY'; }
  1129. }
  1130. class Exists extends \Predis\InlineCommand {
  1131. public function getCommandId() { return 'EXISTS'; }
  1132. public function parseResponse($data) { return (bool) $data; }
  1133. }
  1134. class Delete extends \Predis\InlineCommand {
  1135. public function getCommandId() { return 'DEL'; }
  1136. public function parseResponse($data) { return (bool) $data; }
  1137. }
  1138. class Type extends \Predis\InlineCommand {
  1139. public function getCommandId() { return 'TYPE'; }
  1140. }
  1141. /* commands operating on the key space */
  1142. class Keys extends \Predis\InlineCommand {
  1143. public function canBeHashed() { return false; }
  1144. public function getCommandId() { return 'KEYS'; }
  1145. public function parseResponse($data) {
  1146. // TODO: is this behaviour correct?
  1147. return strlen($data) > 0 ? explode(' ', $data) : array();
  1148. }
  1149. }
  1150. class RandomKey extends \Predis\InlineCommand {
  1151. public function canBeHashed() { return false; }
  1152. public function getCommandId() { return 'RANDOMKEY'; }
  1153. public function parseResponse($data) { return $data !== '' ? $data : null; }
  1154. }
  1155. class Rename extends \Predis\InlineCommand {
  1156. public function canBeHashed() { return false; }
  1157. public function getCommandId() { return 'RENAME'; }
  1158. }
  1159. class RenamePreserve extends \Predis\InlineCommand {
  1160. public function canBeHashed() { return false; }
  1161. public function getCommandId() { return 'RENAMENX'; }
  1162. public function parseResponse($data) { return (bool) $data; }
  1163. }
  1164. class Expire extends \Predis\InlineCommand {
  1165. public function getCommandId() { return 'EXPIRE'; }
  1166. public function parseResponse($data) { return (bool) $data; }
  1167. }
  1168. class ExpireAt extends \Predis\InlineCommand {
  1169. public function getCommandId() { return 'EXPIREAT'; }
  1170. public function parseResponse($data) { return (bool) $data; }
  1171. }
  1172. class DatabaseSize extends \Predis\InlineCommand {
  1173. public function canBeHashed() { return false; }
  1174. public function getCommandId() { return 'DBSIZE'; }
  1175. }
  1176. class TimeToLive extends \Predis\InlineCommand {
  1177. public function getCommandId() { return 'TTL'; }
  1178. }
  1179. /* commands operating on lists */
  1180. class ListPushTail extends \Predis\BulkCommand {
  1181. public function getCommandId() { return 'RPUSH'; }
  1182. }
  1183. class ListPushHead extends \Predis\BulkCommand {
  1184. public function getCommandId() { return 'LPUSH'; }
  1185. }
  1186. class ListLength extends \Predis\InlineCommand {
  1187. public function getCommandId() { return 'LLEN'; }
  1188. }
  1189. class ListRange extends \Predis\InlineCommand {
  1190. public function getCommandId() { return 'LRANGE'; }
  1191. }
  1192. class ListTrim extends \Predis\InlineCommand {
  1193. public function getCommandId() { return 'LTRIM'; }
  1194. }
  1195. class ListIndex extends \Predis\InlineCommand {
  1196. public function getCommandId() { return 'LINDEX'; }
  1197. }
  1198. class ListSet extends \Predis\BulkCommand {
  1199. public function getCommandId() { return 'LSET'; }
  1200. }
  1201. class ListRemove extends \Predis\BulkCommand {
  1202. public function getCommandId() { return 'LREM'; }
  1203. }
  1204. class ListPopLastPushHead extends \Predis\InlineCommand {
  1205. public function getCommandId() { return 'RPOPLPUSH'; }
  1206. }
  1207. class ListPopLastPushHeadBulk extends \Predis\BulkCommand {
  1208. public function getCommandId() { return 'RPOPLPUSH'; }
  1209. }
  1210. class ListPopFirst extends \Predis\InlineCommand {
  1211. public function getCommandId() { return 'LPOP'; }
  1212. }
  1213. class ListPopLast extends \Predis\InlineCommand {
  1214. public function getCommandId() { return 'RPOP'; }
  1215. }
  1216. class ListPopFirstBlocking extends \Predis\InlineCommand {
  1217. public function getCommandId() { return 'BLPOP'; }
  1218. }
  1219. class ListPopLastBlocking extends \Predis\InlineCommand {
  1220. public function getCommandId() { return 'BRPOP'; }
  1221. }
  1222. /* commands operating on sets */
  1223. class SetAdd extends \Predis\BulkCommand {
  1224. public function getCommandId() { return 'SADD'; }
  1225. public function parseResponse($data) { return (bool) $data; }
  1226. }
  1227. class SetRemove extends \Predis\BulkCommand {
  1228. public function getCommandId() { return 'SREM'; }
  1229. public function parseResponse($data) { return (bool) $data; }
  1230. }
  1231. class SetPop extends \Predis\InlineCommand {
  1232. public function getCommandId() { return 'SPOP'; }
  1233. }
  1234. class SetMove extends \Predis\BulkCommand {
  1235. public function canBeHashed() { return false; }
  1236. public function getCommandId() { return 'SMOVE'; }
  1237. public function parseResponse($data) { return (bool) $data; }
  1238. }
  1239. class SetCardinality extends \Predis\InlineCommand {
  1240. public function getCommandId() { return 'SCARD'; }
  1241. }
  1242. class SetIsMember extends \Predis\BulkCommand {
  1243. public function getCommandId() { return 'SISMEMBER'; }
  1244. public function parseResponse($data) { return (bool) $data; }
  1245. }
  1246. class SetIntersection extends \Predis\InlineCommand {
  1247. public function getCommandId() { return 'SINTER'; }
  1248. }
  1249. class SetIntersectionStore extends \Predis\InlineCommand {
  1250. public function getCommandId() { return 'SINTERSTORE'; }
  1251. }
  1252. class SetUnion extends \Predis\InlineCommand {
  1253. public function getCommandId() { return 'SUNION'; }
  1254. }
  1255. class SetUnionStore extends \Predis\InlineCommand {
  1256. public function getCommandId() { return 'SUNIONSTORE'; }
  1257. }
  1258. class SetDifference extends \Predis\InlineCommand {
  1259. public function getCommandId() { return 'SDIFF'; }
  1260. }
  1261. class SetDifferenceStore extends \Predis\InlineCommand {
  1262. public function getCommandId() { return 'SDIFFSTORE'; }
  1263. }
  1264. class SetMembers extends \Predis\InlineCommand {
  1265. public function getCommandId() { return 'SMEMBERS'; }
  1266. }
  1267. class SetRandomMember extends \Predis\InlineCommand {
  1268. public function getCommandId() { return 'SRANDMEMBER'; }
  1269. }
  1270. /* commands operating on sorted sets */
  1271. class ZSetAdd extends \Predis\BulkCommand {
  1272. public function getCommandId() { return 'ZADD'; }
  1273. public function parseResponse($data) { return (bool) $data; }
  1274. }
  1275. class ZSetIncrementBy extends \Predis\BulkCommand {
  1276. public function getCommandId() { return 'ZINCRBY'; }
  1277. }
  1278. class ZSetRemove extends \Predis\BulkCommand {
  1279. public function getCommandId() { return 'ZREM'; }
  1280. public function parseResponse($data) { return (bool) $data; }
  1281. }
  1282. class ZSetRange extends \Predis\InlineCommand {
  1283. public function getCommandId() { return 'ZRANGE'; }
  1284. public function parseResponse($data) {
  1285. $arguments = $this->getArguments();
  1286. if (count($arguments) === 4) {
  1287. if (strtolower($arguments[3]) === 'withscores') {
  1288. if ($data instanceof \Iterator) {
  1289. return new \Predis\Utilities\MultiBulkResponseKVIterator($data);
  1290. }
  1291. $result = array();
  1292. for ($i = 0; $i < count($data); $i++) {
  1293. $result[] = array($data[$i], $data[++$i]);
  1294. }
  1295. return $result;
  1296. }
  1297. }
  1298. return $data;
  1299. }
  1300. }
  1301. class ZSetReverseRange extends \Predis\Commands\ZSetRange {
  1302. public function getCommandId() { return 'ZREVRANGE'; }
  1303. }
  1304. class ZSetRangeByScore extends \Predis\InlineCommand {
  1305. public function getCommandId() { return 'ZRANGEBYSCORE'; }
  1306. }
  1307. class ZSetCardinality extends \Predis\InlineCommand {
  1308. public function getCommandId() { return 'ZCARD'; }
  1309. }
  1310. class ZSetScore extends \Predis\BulkCommand {
  1311. public function getCommandId() { return 'ZSCORE'; }
  1312. }
  1313. class ZSetRemoveRangeByScore extends \Predis\InlineCommand {
  1314. public function getCommandId() { return 'ZREMRANGEBYSCORE'; }
  1315. }
  1316. /* multiple databases handling commands */
  1317. class SelectDatabase extends \Predis\InlineCommand {
  1318. public function canBeHashed() { return false; }
  1319. public function getCommandId() { return 'SELECT'; }
  1320. }
  1321. class MoveKey extends \Predis\InlineCommand {
  1322. public function canBeHashed() { return false; }
  1323. public function getCommandId() { return 'MOVE'; }
  1324. public function parseResponse($data) { return (bool) $data; }
  1325. }
  1326. class FlushDatabase extends \Predis\InlineCommand {
  1327. public function canBeHashed() { return false; }
  1328. public function getCommandId() { return 'FLUSHDB'; }
  1329. }
  1330. class FlushAll extends \Predis\InlineCommand {
  1331. public function canBeHashed() { return false; }
  1332. public function getCommandId() { return 'FLUSHALL'; }
  1333. }
  1334. /* sorting */
  1335. class Sort extends \Predis\InlineCommand {
  1336. public function getCommandId() { return 'SORT'; }
  1337. public function filterArguments(Array $arguments) {
  1338. if (count($arguments) === 1) {
  1339. return $arguments;
  1340. }
  1341. // TODO: add more parameters checks
  1342. $query = array($arguments[0]);
  1343. $sortParams = $arguments[1];
  1344. if (isset($sortParams['by'])) {
  1345. $query[] = 'BY ' . $sortParams['by'];
  1346. }
  1347. if (isset($sortParams['get'])) {
  1348. $getargs = $sortParams['get'];
  1349. if (is_array($getargs)) {
  1350. foreach ($getargs as $getarg) {
  1351. $query[] = 'GET ' . $getarg;
  1352. }
  1353. }
  1354. else {
  1355. $query[] = 'GET ' . $getargs;
  1356. }
  1357. }
  1358. if (isset($sortParams['limit']) && is_array($sortParams['limit'])) {
  1359. $query[] = 'LIMIT ' . $sortParams['limit'][0] . ' ' . $sortParams['limit'][1];
  1360. }
  1361. if (isset($sortParams['sort'])) {
  1362. $query[] = strtoupper($sortParams['sort']);
  1363. }
  1364. if (isset($sortParams['alpha']) && $sortParams['alpha'] == true) {
  1365. $query[] = 'ALPHA';
  1366. }
  1367. if (isset($sortParams['store']) && $sortParams['store'] == true) {
  1368. $query[] = 'STORE ' . $sortParams['store'];
  1369. }
  1370. return $query;
  1371. }
  1372. }
  1373. /* persistence control commands */
  1374. class Save extends \Predis\InlineCommand {
  1375. public function canBeHashed() { return false; }
  1376. public function getCommandId() { return 'SAVE'; }
  1377. }
  1378. class BackgroundSave extends \Predis\InlineCommand {
  1379. public function canBeHashed() { return false; }
  1380. public function getCommandId() { return 'BGSAVE'; }
  1381. public function parseResponse($data) {
  1382. if ($data == 'Background saving started') {
  1383. return true;
  1384. }
  1385. return $data;
  1386. }
  1387. }
  1388. class BackgroundRewriteAppendOnlyFile extends \Predis\InlineCommand {
  1389. public function canBeHashed() { return false; }
  1390. public function getCommandId() { return 'BGREWRITEAOF'; }
  1391. public function parseResponse($data) {
  1392. return $data == 'Background append only file rewriting started';
  1393. }
  1394. }
  1395. class LastSave extends \Predis\InlineCommand {
  1396. public function canBeHashed() { return false; }
  1397. public function getCommandId() { return 'LASTSAVE'; }
  1398. }
  1399. class Shutdown extends \Predis\InlineCommand {
  1400. public function canBeHashed() { return false; }
  1401. public function getCommandId() { return 'SHUTDOWN'; }
  1402. public function closesConnection() { return true; }
  1403. }
  1404. /* remote server control commands */
  1405. class Info extends \Predis\InlineCommand {
  1406. public function canBeHashed() { return false; }
  1407. public function getCommandId() { return 'INFO'; }
  1408. public function parseResponse($data) {
  1409. $info = array();
  1410. $infoLines = explode("\r\n", $data, -1);
  1411. foreach ($infoLines as $row) {
  1412. list($k, $v) = explode(':', $row);
  1413. if (!preg_match('/^db\d+$/', $k)) {
  1414. $info[$k] = $v;
  1415. }
  1416. else {
  1417. $db = array();
  1418. foreach (explode(',', $v) as $dbvar) {
  1419. list($dbvk, $dbvv) = explode('=', $dbvar);
  1420. $db[trim($dbvk)] = $dbvv;
  1421. }
  1422. $info[$k] = $db;
  1423. }
  1424. }
  1425. return $info;
  1426. }
  1427. }
  1428. class SlaveOf extends \Predis\InlineCommand {
  1429. public function canBeHashed() { return false; }
  1430. public function getCommandId() { return 'SLAVEOF'; }
  1431. public function filterArguments(Array $arguments) {
  1432. return count($arguments) === 0 ? array('NO ONE') : $arguments;
  1433. }
  1434. }
  1435. class Multi extends \Predis\InlineCommand {
  1436. public function canBeHashed() { return false; }
  1437. public function getCommandId() { return 'MULTI'; }
  1438. }
  1439. class Exec extends \Predis\InlineCommand {
  1440. public function canBeHashed() { return false; }
  1441. public function getCommandId() { return 'EXEC'; }
  1442. }
  1443. ?>