forked from jdp/redisent
-
Notifications
You must be signed in to change notification settings - Fork 145
/
Client.php
executable file
·1686 lines (1576 loc) · 61.1 KB
/
Client.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Credis_Client (a fork of Redisent)
*
* Most commands are compatible with phpredis library:
* - use "pipeline()" to start a pipeline of commands instead of multi(Redis::PIPELINE)
* - any arrays passed as arguments will be flattened automatically
* - setOption and getOption are not supported in standalone mode
* - order of arguments follows redis-cli instead of phpredis where they differ (lrem)
*
* - Uses phpredis library if extension is installed for better performance.
* - Establishes connection lazily.
* - Supports tcp and unix sockets.
* - Reconnects automatically unless a watch or transaction is in progress.
* - Can set automatic retry connection attempts for iffy Redis connections.
*
* @author Colin Mollenhour <[email protected]>
* @copyright 2011 Colin Mollenhour <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @package Credis_Client
*/
/**
* Credis-specific errors, wraps native Redis errors
*/
class CredisException extends Exception
{
const CODE_TIMED_OUT = 1;
const CODE_DISCONNECTED = 2;
public function __construct($message, $code = 0, $exception = null)
{
if ($exception && get_class($exception) == 'RedisException' && strpos($message, 'read error on connection') === 0) {
$code = CredisException::CODE_DISCONNECTED;
}
parent::__construct($message, $code, $exception);
}
}
/**
* Credis_Client, a lightweight Redis PHP standalone client and phpredis wrapper
*
* Server/Connection:
* @method Credis_Client pipeline()
* @method Credis_Client multi()
* @method Credis_Client|bool watch(string ...$keys)
* @method Credis_Client|bool unwatch()
* @method array exec()
* @method bool discard()
* @method Credis_Client|bool flushAll()
* @method Credis_Client|bool flushDb()
* @method array|Credis_Client info(string $section = null)
* @method bool|array|Credis_Client config(string $setGet, string $key, string $value = null)
* @method array|Credis_Client role()
* @method array|Credis_Client time()
* @method int|Credis_Client dbsize()
*
* Keys:
* @method int|Credis_Client del(string|array ...$keys)
* @method int|Credis_Client exists(string $key)
* @method int|Credis_Client expire(string $key, int $seconds)
* @method int|Credis_Client expireAt(string $key, int $timestamp)
* @method array|Credis_Client keys(string $key)
* @method int|Credis_Client persist(string $key)
* @method bool|Credis_Client rename(string $key, string $newKey)
* @method bool|Credis_Client renameNx(string $key, string $newKey)
* @method array|Credis_Client sort(string $key, string $arg1, string $valueN = null)
* @method int|Credis_Client ttl(string $key)
* @method string|Credis_Client type(string $key)
* @method string|Credis_Client unlink(string|array ...$keys)
*
* Scalars:
* @method int|Credis_Client append(string $key, string $value)
* @method int|Credis_Client decr(string $key)
* @method int|Credis_Client decrBy(string $key, int $decrement)
* @method false|string|Credis_Client get(string $key)
* @method int|Credis_Client getBit(string $key, int $offset)
* @method string|Credis_Client getRange(string $key, int $start, int $end)
* @method string|Credis_Client getSet(string $key, string $value)
* @method int|Credis_Client incr(string $key)
* @method int|Credis_Client incrBy(string $key, int $decrement)
* @method false|array|Credis_Client mGet(array $keys)
* @method bool|Credis_Client mSet(array $keysValues)
* @method int|Credis_Client mSetNx(array $keysValues)
* @method bool|Credis_Client set(string $key, string $value, int | array $options = null)
* @method int|Credis_Client setBit(string $key, int $offset, int $value)
* @method bool|Credis_Client setEx(string $key, int $seconds, string $value)
* @method int|Credis_Client setNx(string $key, string $value)
* @method int |Credis_Client setRange(string $key, int $offset, int $value)
* @method int|Credis_Client strLen(string $key)
*
* Sets:
* @method int|Credis_Client sAdd(string $key, mixed $value, string $valueN = null)
* @method int|Credis_Client sRem(string $key, mixed $value, string $valueN = null)
* @method array|Credis_Client sMembers(string $key)
* @method array|Credis_Client sUnion(mixed $keyOrArray, string $valueN = null)
* @method array|Credis_Client sInter(mixed $keyOrArray, string $valueN = null)
* @method array |Credis_Client sDiff(mixed $keyOrArray, string $valueN = null)
* @method string|Credis_Client sPop(string $key)
* @method int|Credis_Client sCard(string $key)
* @method int|Credis_Client sIsMember(string $key, string $member)
* @method int|Credis_Client sMove(string $source, string $dest, string $member)
* @method string|array|Credis_Client sRandMember(string $key, int $count = null)
* @method int|Credis_Client sUnionStore(string $dest, string $key1, string $key2 = null)
* @method int|Credis_Client sInterStore(string $dest, string $key1, string $key2 = null)
* @method int|Credis_Client sDiffStore(string $dest, string $key1, string $key2 = null)
*
* Hashes:
* @method bool|int|Credis_Client hSet(string $key, string $field, string $value)
* @method bool|Credis_Client hSetNx(string $key, string $field, string $value)
* @method bool|string|Credis_Client hGet(string $key, string $field)
* @method bool|int|Credis_Client hLen(string $key)
* @method bool|Credis_Client hDel(string $key, string $field)
* @method array|Credis_Client hKeys(string $key)
* @method array|Credis_Client hVals(string $key)
* @method array|Credis_Client hGetAll(string $key)
* @method bool|Credis_Client hExists(string $key, string $field)
* @method int|Credis_Client hIncrBy(string $key, string $field, int $value)
* @method float|Credis_Client hIncrByFloat(string $key, string $member, float $value)
* @method bool|Credis_Client hMSet(string $key, array $keysValues)
* @method array|Credis_Client hMGet(string $key, array $fields)
*
* Lists:
* @method array|null|Credis_Client blPop(string $keyN, int $timeout)
* @method array|null|Credis_Client brPop(string $keyN, int $timeout)
* @method array|null |Credis_Client brPoplPush(string $source, string $destination, int $timeout)
* @method string|null|Credis_Client lIndex(string $key, int $index)
* @method int|Credis_Client lInsert(string $key, string $beforeAfter, string $pivot, string $value)
* @method int|Credis_Client lLen(string $key)
* @method string|null|Credis_Client lPop(string $key)
* @method int|Credis_Client lPush(string $key, mixed $value, mixed $valueN = null)
* @method int|Credis_Client lPushX(string $key, mixed $value)
* @method array|Credis_Client lRange(string $key, int $start, int $stop)
* @method int|Credis_Client lRem(string $key, int $count, mixed $value)
* @method bool|Credis_Client lSet(string $key, int $index, mixed $value)
* @method bool|Credis_Client lTrim(string $key, int $start, int $stop)
* @method string|null|Credis_Client rPop(string $key)
* @method string|null|Credis_Client rPoplPush(string $source, string $destination)
* @method int|Credis_Client rPush(string $key, mixed $value, mixed $valueN = null)
* @method int |Credis_Client rPushX(string $key, mixed $value)
*
* Sorted Sets:
* @method int|Credis_Client zAdd(string $key, double $score, string $value)
* @method int|Credis_Client zCard(string $key)
* @method int|Credis_Client zSize(string $key)
* @method int|Credis_Client zCount(string $key, mixed $start, mixed $stop)
* @method int|Credis_Client zIncrBy(string $key, double $value, string $member)
* @method array|Credis_Client zRangeByScore(string $key, mixed $start, mixed $stop, array $args = null)
* @method array|Credis_Client zRevRangeByScore(string $key, mixed $start, mixed $stop, array $args = null)
* @method int|Credis_Client zRemRangeByScore(string $key, mixed $start, mixed $stop)
* @method array|Credis_Client zRange(string $key, mixed $start, mixed $stop, array $args = null)
* @method array|Credis_Client zRevRange(string $key, mixed $start, mixed $stop, array $args = null)
* @method int|Credis_Client zRank(string $key, string $member)
* @method int|Credis_Client zRevRank(string $key, string $member)
* @method int|Credis_Client zRem(string $key, string $member)
* @method int|Credis_Client zDelete(string $key, string $member)
* TODO
*
* Pub/Sub
* @method int |Credis_Client publish(string $channel, string $message)
* @method int|array|Credis_Client pubsub(string $subCommand, $arg = null)
*
* Scripting:
* @method string|int|Credis_Client script(string $command, string $arg1 = null)
* @method string|int|array|bool|Credis_Client eval(string $script, array|string $keys = null, array|string $args = null)
* @method string|int|array|bool|Credis_Client evalSha(string $script, array|string $keys = null, array|string $args = null)
*/
class Credis_Client
{
const TYPE_STRING = 'string';
const TYPE_LIST = 'list';
const TYPE_SET = 'set';
const TYPE_ZSET = 'zset';
const TYPE_HASH = 'hash';
const TYPE_NONE = 'none';
/**
* Socket connection to the Redis server or Redis library instance
* @var resource|Redis
*/
protected $redis;
protected $redisMulti;
/**
* Host of the Redis server
* @var string
*/
protected $host;
/**
* Scheme of the Redis server (tcp, tls, tlsv1.2, unix)
* @var string|null
*/
protected $scheme;
/**
* SSL Meta information
* @var array|null
*/
protected $sslMeta;
/**
* Port on which the Redis server is running
* @var int|null
*/
protected $port;
/**
* Timeout for connecting to Redis server
* @var float|null
*/
protected $timeout;
/**
* Timeout for reading response from Redis server
* @var float|null
*/
protected $readTimeout;
/**
* Unique identifier for persistent connections
* @var string
*/
protected $persistent;
/**
* @var bool
*/
protected $closeOnDestruct = true;
/**
* @var bool
*/
protected $connected = false;
/**
* @var bool
*/
protected $standalone;
/**
* @var int
*/
protected $maxConnectRetries = 0;
/**
* @var int
*/
protected $connectFailures = 0;
/**
* @var bool
*/
protected $usePipeline = false;
/**
* @var array
*/
protected $commandNames;
/**
* @var string
*/
protected $commands;
/**
* @var bool
*/
protected $isMulti = false;
/**
* @var bool
*/
protected $isWatching = false;
/**
* @var string|null
*/
protected $authUsername;
/**
* @var string|null
*/
protected $authPassword;
/**
* @var int
*/
protected $selectedDb = 0;
/**
* Aliases for backwards compatibility with phpredis
* @var array
*/
protected $wrapperMethods = array('delete' => 'del', 'getkeys' => 'keys', 'sremove' => 'srem');
/**
* @var array<string,string>|callable|null
*/
protected $renamedCommands;
/**
* @var int
*/
protected $requests = 0;
/**
* @var bool
*/
protected $subscribed = false;
/** @var bool */
protected $oldPhpRedis = false;
/** @var array */
protected $tlsOptions = [];
/**
* @var bool
*/
protected $isTls = false;
/**
* Gets Useful Meta debug information about the SSL
*
* @return array|null
*/
public function getSslMeta()
{
return $this->sslMeta;
}
/**
* Creates a connection to the Redis server on host {@link $host} and port {@link $port}.
* $host may also be a path to a unix socket or a string in the form of tcp://[hostname]:[port] or unix://[path]
*
* @param string $host The hostname of the Redis server
* @param int|null $port The port number of the Redis server
* @param float|null $timeout Timeout period in seconds
* @param string $persistent Flag to establish persistent connection
* @param int $db The selected database of the Redis server
* @param string|null $password The authentication password of the Redis server
* @param string|null $username The authentication username of the Redis server
* @param array|null $tlsOptions The TLS/SSL context options. See https://www.php.net/manual/en/context.ssl.php for details
* @throws CredisException
*/
public function __construct($host = '127.0.0.1', $port = 6379, $timeout = null, $persistent = '', $db = 0, $password = null, $username = null, $tlsOptions = null)
{
$this->host = (string)$host;
if ($port !== null) {
$this->port = (int)$port;
}
$this->scheme = null;
$this->timeout = $timeout;
$this->persistent = (string)$persistent;
$this->standalone = !extension_loaded('redis');
$this->authPassword = $password;
$this->authUsername = $username;
$this->selectedDb = (int)$db;
$this->convertHost();
if (is_array($tlsOptions) && count($tlsOptions) !== 0) {
$this->setTlsOptions($tlsOptions);
}
// PHP Redis extension support TLS/ACL AUTH since 5.3.0
$this->oldPhpRedis = (bool)version_compare(phpversion('redis'), '5.3.0', '<');
if ((
$this->isTls
|| $this->authUsername !== null
)
&& !$this->standalone && $this->oldPhpRedis) {
$this->standalone = true;
}
}
public function __destruct()
{
if ($this->closeOnDestruct) {
$this->close();
}
}
/**
* @return bool
*/
public function isSubscribed()
{
return $this->subscribed;
}
/**
* Return the host of the Redis instance
* @return string
*/
public function getHost()
{
return $this->host;
}
/**
* Return the port of the Redis instance
* @return int|null
*/
public function getPort()
{
return $this->port;
}
/**
* @return bool
*/
public function isTls()
{
return $this->isTls;
}
/**
* Return the selected database
* @return int
*/
public function getSelectedDb()
{
return $this->selectedDb;
}
/**
* @return string
*/
public function getPersistence()
{
return $this->persistent;
}
/**
* @return Credis_Client
* @throws CredisException
*/
public function forceStandalone()
{
if ($this->standalone) {
return $this;
}
if ($this->connected) {
throw new CredisException('Cannot force Credis_Client to use standalone PHP driver after a connection has already been established.');
}
$this->standalone = true;
return $this;
}
/**
* @param int $retries
* @return Credis_Client
*/
public function setMaxConnectRetries($retries)
{
$this->maxConnectRetries = $retries;
return $this;
}
/**
* @param bool $flag
* @return Credis_Client
*/
public function setCloseOnDestruct($flag)
{
$this->closeOnDestruct = $flag;
return $this;
}
/**
* @throws CredisException
*/
public function setTlsOptions(array $tlsOptions)
{
if ($this->connected) {
throw new CredisException('Cannot change TLS options after a connection has already been established.');
}
$this->tlsOptions = $tlsOptions;
}
/**
* @throws CredisException
*/
protected function convertHost()
{
if (preg_match('#^(tcp|tls|ssl|tlsv\d(?:\.\d)?|unix)://(.+)$#', $this->host, $matches)) {
$this->isTls = strpos($matches[1], 'tls') === 0 || strpos($matches[1], 'ssl') === 0;
if ($this->isTls || $matches[1] === 'tcp') {
$this->scheme = $matches[1];
if (!preg_match('#^([^:]+)(:([0-9]+))?(/(.+))?$#', $matches[2], $matches)) {
throw new CredisException('Invalid host format; expected ' . $this->scheme . '://host[:port][/persistence_identifier]');
}
$this->host = $matches[1];
$this->port = (int)(isset($matches[3]) ? $matches[3] : $this->port);
$this->persistent = isset($matches[5]) ? $matches[5] : $this->persistent;
} else {
$this->host = $matches[2];
$this->port = null;
$this->scheme = 'unix';
if (substr($this->host, 0, 1) != '/') {
throw new CredisException('Invalid unix socket format; expected unix:///path/to/redis.sock');
}
}
}
if ($this->port !== null && substr($this->host, 0, 1) == '/') {
$this->port = null;
$this->scheme = 'unix';
}
if (!$this->scheme) {
$this->scheme = 'tcp';
}
}
/**
* @return Credis_Client
* @throws CredisException
*/
public function connect()
{
if ($this->connected) {
return $this;
}
$this->close(true);
$tlsOptions = $this->isTls ? $this->tlsOptions : [];
if ($this->standalone) {
$flags = STREAM_CLIENT_CONNECT;
$remote_socket = $this->port === null
? $this->scheme . '://' . $this->host
: $this->scheme . '://' . $this->host . ':' . $this->port;
if ($this->persistent && $this->port !== null) {
// Persistent connections to UNIX sockets are not supported
$remote_socket .= '/' . $this->persistent;
$flags = $flags | STREAM_CLIENT_PERSISTENT;
}
if ($this->isTls) {
$tlsOptions = array_merge($tlsOptions, [
'capture_peer_cert' => true,
'capture_peer_cert_chain' => true,
'capture_session_meta' => true,
]);
}
// passing $context as null errors before php 8.0
$context = stream_context_create(['ssl' => $tlsOptions]);
$result = $this->redis = @stream_socket_client($remote_socket, $errno, $errstr, $this->timeout !== null ? $this->timeout : 2.5, $flags, $context);
if ($result && $this->isTls) {
$this->sslMeta = stream_context_get_options($context);
}
} else {
if (!$this->redis) {
$this->redis = new Redis();
}
$socketTimeout = $this->timeout ?: 0.0;
try {
if ($this->oldPhpRedis) {
$result = $this->persistent
? $this->redis->pconnect($this->host, (int)$this->port, $socketTimeout, $this->persistent)
: $this->redis->connect($this->host, (int)$this->port, $socketTimeout);
} else {
// 7th argument is non-documented TLS options. But it only exists on the newer versions of phpredis
if ($tlsOptions) {
$context = ['stream' => $tlsOptions];
} else {
$context = [];
}
/** @noinspection PhpMethodParametersCountMismatchInspection */
$result = $this->persistent
? $this->redis->pconnect($this->scheme . '://' . $this->host, (int)$this->port, $socketTimeout, $this->persistent, 0, 0.0, $context)
: $this->redis->connect($this->scheme . '://' . $this->host, (int)$this->port, $socketTimeout, null, 0, 0.0, $context);
}
} catch (Exception $e) {
// Some applications will capture the php error that phpredis can sometimes generate and throw it as an Exception
$result = false;
$errno = 1;
$errstr = $e->getMessage();
}
}
// Use recursion for connection retries
if (!$result) {
$this->connectFailures++;
if ($this->connectFailures <= $this->maxConnectRetries) {
return $this->connect();
}
$failures = $this->connectFailures;
$this->connectFailures = 0;
throw new CredisException(sprintf(
"Connection to Redis%s %s://%s failed after %s failures.%s",
$this->standalone ? ' standalone' : '',
$this->scheme,
$this->host . ($this->port ? ':' . $this->port : ''),
$failures,
(isset($errno) && isset($errstr) ? "Last Error : ({$errno}) {$errstr}" : "")
));
}
$this->connectFailures = 0;
$this->connected = true;
// Set read timeout
if ($this->readTimeout) {
$this->setReadTimeout($this->readTimeout);
}
if ($this->authPassword) {
$this->auth($this->authPassword, $this->authUsername);
}
if ($this->selectedDb !== 0) {
$this->select($this->selectedDb);
}
return $this;
}
/**
* @return bool
*/
public function isConnected()
{
return $this->connected;
}
/**
* Set the read timeout for the connection. Use 0 to disable timeouts entirely (or use a very long timeout
* if not supported).
*
* @param float $timeout 0 (or -1) for no timeout, otherwise number of seconds
* @return Credis_Client
* @throws CredisException
*/
public function setReadTimeout($timeout)
{
if ($timeout < -1) {
throw new CredisException('Timeout values less than -1 are not accepted.');
}
$this->readTimeout = $timeout;
if ($this->isConnected()) {
if ($this->standalone) {
$timeout = $timeout <= 0 ? 315360000 : $timeout; // Ten-year timeout
stream_set_blocking($this->redis, true);
stream_set_timeout($this->redis, (int)floor($timeout), ($timeout - floor($timeout)) * 1000000);
} elseif (defined('Redis::OPT_READ_TIMEOUT')) {
// supported in phpredis 2.2.3
// a timeout value of -1 means reads will not time out
$timeout = $timeout == 0 ? -1 : $timeout;
try {
$this->redis->setOption(Redis::OPT_READ_TIMEOUT, $timeout);
} catch (RedisException $e) {
throw new CredisException($e->getMessage(), $e->getCode(), $e);
}
}
}
return $this;
}
/**
* @return bool
*/
public function close($force = false)
{
$result = true;
if ($this->redis && ($force || $this->connected && !$this->persistent)) {
try {
if (is_callable(array($this->redis, 'close'))) {
$this->redis->close();
} else {
@fclose($this->redis);
$this->redis = null;
}
} catch (Exception $e) {
// Ignore exceptions on close
$result = false;
}
$this->connected = $this->usePipeline = $this->isMulti = $this->isWatching = false;
}
return $result;
}
/**
* Enabled command renaming and provide mapping method. Supported methods are:
*
* 1. renameCommand('foo') // Salted md5 hash for all commands -> md5('foo'.$command)
* 2. renameCommand(function($command){ return 'my'.$command; }); // Callable
* 3. renameCommand('get', 'foo') // Single command -> alias
* 4. renameCommand(['get' => 'foo', 'set' => 'bar']) // Full map of [command -> alias]
*
* @param string|callable|array $command
* @param string|null $alias
* @return $this
* @throws CredisException
*/
public function renameCommand($command, $alias = null)
{
if (!$this->standalone) {
$this->forceStandalone();
}
if ($alias === null) {
$this->renamedCommands = $command;
} else {
if (!$this->renamedCommands) {
$this->renamedCommands = array();
}
$this->renamedCommands[$command] = $alias;
}
return $this;
}
/**
* @param $command
* @return string
*/
public function getRenamedCommand($command)
{
static $map;
// Command renaming not enabled
if ($this->renamedCommands === null) {
return $command;
}
// Initialize command map
if ($map === null) {
if (is_array($this->renamedCommands)) {
$map = $this->renamedCommands;
} else {
$map = array();
}
}
// Generate and return cached result
if (!isset($map[$command])) {
// String means all commands are hashed with salted md5
if (is_string($this->renamedCommands)) {
$map[$command] = md5($this->renamedCommands . $command);
} // Would already be set in $map if it was intended to be renamed
elseif (is_array($this->renamedCommands)) {
return $command;
} // User-supplied function
elseif (is_callable($this->renamedCommands)) {
$map[$command] = call_user_func($this->renamedCommands, $command);
}
}
return $map[$command];
}
/**
* @param string $password
* @param string|null $username
* @return bool
* @throws CredisException
*/
public function auth($password, $username = null)
{
if ($username !== null) {
$response = $this->__call('auth', array($username, $password));
$this->authUsername = $username;
} else {
$response = $this->__call('auth', array($password));
}
$this->authPassword = $password;
return $response;
}
/**
* @param int $index
* @return bool
* @throws CredisException
*/
public function select($index)
{
$response = $this->__call('select', array($index));
$this->selectedDb = (int)$index;
return $response;
}
/**
* @param string $caller
* @return void
* @throws CredisException
*/
protected function assertNotPipelineOrMulti($caller)
{
if ($this->standalone && ($this->isMulti || $this->usePipeline) ||
// phpredis triggers a php fatal error, so do the check before
!$this->standalone && ($this->redis->getMode() === Redis::MULTI || $this->redis->getMode() === Redis::PIPELINE)) {
throw new CredisException('multi()/pipeline() mode can not be used with '.$caller);
}
}
/**
* @param string|array ...$args
* @return array
* @throws CredisException
*/
public function pUnsubscribe(...$args)
{
list($command, $channel, $subscribedChannels) = $this->__call('punsubscribe', $args);
$this->subscribed = $subscribedChannels > 0;
return array($command, $channel, $subscribedChannels);
}
/**
* @param ?int $Iterator
* @param string $pattern
* @param int $count
* @return bool|array
* @throws CredisException
*/
public function scan(&$Iterator, $pattern = null, $count = null)
{
$this->assertNotPipelineOrMulti(__METHOD__);
return $this->__call('scan', array(&$Iterator, $pattern, $count));
}
/**
* @param ?int $Iterator
* @param string $field
* @param string $pattern
* @param int $count
* @return bool|array
* @throws CredisException
*/
public function hscan(&$Iterator, $field, $pattern = null, $count = null)
{
$this->assertNotPipelineOrMulti(__METHOD__);
return $this->__call('hscan', array($field, &$Iterator, $pattern, $count));
}
/**
* @param ?int $Iterator
* @param string $field
* @param string $pattern
* @param ?int $count
* @return bool|array
* @throws CredisException
*/
public function sscan(&$Iterator, $field, $pattern = null, $count = null)
{
$this->assertNotPipelineOrMulti(__METHOD__);
return $this->__call('sscan', array($field, &$Iterator, $pattern, $count));
}
/**
* @param ?int $Iterator
* @param string $field
* @param string $pattern
* @param ?int $count
* @return bool|array
* @throws CredisException
*/
public function zscan(&$Iterator, $field, $pattern = null, $count = null)
{
$this->assertNotPipelineOrMulti(__METHOD__);
return $this->__call('zscan', array($field, &$Iterator, $pattern, $count));
}
/**
* @param string|array $patterns
* @param $callback
* @return $this|array|bool|Credis_Client|mixed|null|string
* @throws CredisException
*/
public function pSubscribe($patterns, $callback)
{
if (!$this->standalone) {
return $this->__call('pSubscribe', array((array)$patterns, $callback));
}
// Standalone mode: use infinite loop to subscribe until timeout
$patternCount = is_array($patterns) ? count($patterns) : 1;
while ($patternCount--) {
if (isset($status)) {
list($command, $pattern, $status) = $this->read_reply();
} else {
list($command, $pattern, $status) = $this->__call('psubscribe', array($patterns));
}
$this->subscribed = $status > 0;
if (!$status) {
throw new CredisException('Invalid pSubscribe response.');
}
}
while ($this->subscribed) {
list($type, $pattern, $channel, $message) = $this->read_reply();
if ($type != 'pmessage') {
throw new CredisException('Received non-pmessage reply.');
}
$callback($this, $pattern, $channel, $message);
}
return null;
}
/**
* @param string|array ...$args
* @return array
* @throws CredisException
*/
public function unsubscribe(...$args)
{
list($command, $channel, $subscribedChannels) = $this->__call('unsubscribe', $args);
$this->subscribed = $subscribedChannels > 0;
return array($command, $channel, $subscribedChannels);
}
/**
* @param string|array $channels
* @param $callback
* @return $this|array|bool|Credis_Client|mixed|null|string
* @throws CredisException
*/
public function subscribe($channels, $callback)
{
if (!$this->standalone) {
return $this->__call('subscribe', array((array)$channels, $callback));
}
// Standalone mode: use infinite loop to subscribe until timeout
$channelCount = is_array($channels) ? count($channels) : 1;
while ($channelCount--) {
if (isset($status)) {
list($command, $channel, $status) = $this->read_reply();
} else {
list($command, $channel, $status) = $this->__call('subscribe', array($channels));
}
$this->subscribed = $status > 0;
if (!$status) {
throw new CredisException('Invalid subscribe response.');
}
}
while ($this->subscribed) {
list($type, $channel, $message) = $this->read_reply();
if ($type != 'message') {
throw new CredisException('Received non-message reply.');
}
$callback($this, $channel, $message);
}
return null;
}
/**
* @param string|null $name
* @return string|Credis_Client
* @throws CredisException
*/
public function ping($name = null)
{
return $this->__call('ping', $name ? array($name) : array());
}
/**
* @param string $command
* @param array $args
*
* @return array|Credis_Client
* @throws CredisException
*/
public function rawCommand($command, array $args)
{
if ($this->standalone) {
return $this->__call($command, $args);
} else {
\array_unshift($args, $command);
return $this->__call('rawCommand', $args);
}
}
/**
* @throws CredisException
*/
public function __call($name, $args)
{
// Lazy connection
$this->connect();
$name = strtolower($name);
// Send request via native PHP
if ($this->standalone) {
// Early returns should verify how phpredis behaves!
$trackedArgs = array();
switch ($name) {
case 'eval':
case 'evalsha':
$script = array_shift($args);
$keys = (array)array_shift($args);
$eArgs = (array)array_shift($args);
$args = array($script, count($keys), $keys, $eArgs);
break;
case 'zinterstore':
case 'zunionstore':
$dest = array_shift($args);
$keys = (array)array_shift($args);
$weights = array_shift($args);
$aggregate = array_shift($args);
$args = array($dest, count($keys), $keys);
if ($weights) {
$args[] = (array)$weights;
}
if ($aggregate) {
$args[] = $aggregate;