Predis.php 55 KB

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