Predis.php 60 KB

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