Compare commits

...

203 Commits

Author SHA1 Message Date
Till Krüss fdd52d0284 Tag v2.4.0-RC1 (#1523) 2025-03-24 10:07:15 -07:00
Vladyslav Vildanov 48a861053e Added new hash-field expiration commands (#1520)
* Added new hash-field expiration commands

* Changed argument default value

* Marked test as skipped

* Removed version restriction

* Updated CHANGELOG.md
2025-03-24 17:50:12 +02:00
messikiller 7bf1f6eb29 optimize redis cluster slotmap with compact slot range object (#1493)
Co-authored-by: heqiming <heqiming@kingsoft.com>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
Co-authored-by: Vladyslav Vildanov <117659936+vladvildanov@users.noreply.github.com>
2025-03-19 09:24:53 -07:00
Vladyslav Vildanov 067b051900 Added missing FT._LIST and BITFIELD_RO commands (#1521)
* Added missing FT._LIST and BITFIELD_RO commands

* Codestyle fixes
2025-03-19 09:57:52 +02:00
Till Krüss df4a318b80 remove performance rambling from FAQ 2025-03-18 12:50:00 -07:00
Vladyslav Vildanov a904a3a273 Backport #1517 (#1518)
* Backport #1517

* Added versions restrictions

* Removed Relay for cluster with coverage

* Added phpcov package
2025-03-05 19:29:38 +02:00
Vladyslav Vildanov 8b240d15a5 Backport #1512 (#1515)
* Backport #1512
* Removed outdated test
2025-02-25 09:12:10 -08:00
Vladyslav Vildanov 02e2a7e1cc Added test coverage for compatibility with Redis 8.0 (#1513)
* Added testing with 8.0

* Removed old service

* Moved checkout stage above image

* Changed service name

* Override config options for Redis < 7

* Exported to github env

* Print major version output

* Added double quotes

* Test fixes

* Merge cluster and standalone infrastructure

* Removed separate cluster job and merge together with standalone

* Merge stack tests into main test job

* Fixed annotation condition

* tweaks

* Moved docker-compose.yml to root folder

* Added compose file to expected

* fixed in v0.10.1

* move docker file

* Added -all profile in docker-compose

* Removed redis official image, reduce test matrix, moved docker-compose.yml

* Revert docker-compose moving

* Added test coverage to verify compatibility with 8.0

* Mark tests as relay-incompatible

* Codestyle fix

* Marked as relay-incompatible

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2025-02-24 09:22:45 -08:00
Vladyslav Vildanov 9a22450a65 Added testing with 8.0 (#1510)
* Added testing with 8.0

* Removed old service

* Moved checkout stage above image

* Changed service name

* Override config options for Redis < 7

* Exported to github env

* Print major version output

* Added double quotes

* Test fixes

* Merge cluster and standalone infrastructure

* Removed separate cluster job and merge together with standalone

* Merge stack tests into main test job

* Fixed annotation condition

* tweaks

* Moved docker-compose.yml to root folder

* Added compose file to expected

* fixed in v0.10.1

* move docker file

* Added -all profile in docker-compose

* Removed redis official image, reduce test matrix, moved docker-compose.yml

* Revert docker-compose moving

* test php 8.0 and redis 4.0

* Revert changes related to official image

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2025-02-20 17:47:05 +02:00
zxin ac933cc548 Fix eval_ro cluster support (#1449) 2025-02-13 09:40:23 -08:00
Stephan 355faa099f ClientInterface: update watch command accepting string and string[] (#1476) 2025-02-13 09:39:51 -08:00
Radu Neacsu 549889b198 Mark GEOSEARCH as read-only to ensure execution on replica instead of… (#1481) 2025-02-13 09:39:19 -08:00
Denny Septian Panggabean d1c657aac5 refactor: use parallel on PHP-CS-Fixer (#1489) 2025-02-13 09:06:51 -08:00
Jan Nedbal b196809d3a Prevent named arguments runtime failure (#1509) 2025-02-12 09:13:01 -08:00
Till Krüss 52489ea703 Update CHANGELOG.md 2025-01-22 09:26:10 -08:00
Till Krüss ba66e22c92 bump year to 2025 2025-01-22 09:24:26 -08:00
Nicolas Chapleau 37aa6fb515 PHP 8.4.0 compatibility with call to stream_context_set_option (#1503)
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2025-01-22 09:08:12 -08:00
Till Krüss deed24c418 update year 2025-01-20 09:52:18 -08:00
Till Krüss 93895d02b6 Update composer.json 2025-01-16 08:48:12 -08:00
asafpamzn 275606843e Update composer.json 2025-01-16 08:48:12 -08:00
asafpamzn 976c9daa4f Update composer.json 2025-01-16 08:48:12 -08:00
Till Krüss 205ae75bd8 Update README.md 2025-01-16 08:48:12 -08:00
asafpamzn a5f46d0913 Update README.md to include that the client is compatible with Valkey
Added documentation clarifying that predis is compatible with Valkey. This information could be really helpful for developers using Valkey in their projects, saving them time and ensuring they are confident in their choice of predis.
2025-01-16 08:48:12 -08:00
Till Krüss b36c2f928f Update .editorconfig (#1494) 2024-11-25 09:58:29 -08:00
Vladyslav Vildanov bf6e97e7fb Fixed broken search test (#1492) 2024-11-22 07:54:01 -08:00
Till Krüss da40e1253c bump dev version [skip ci] 2024-11-21 12:14:32 -08:00
Till Krüss bac46bfdb7 Prepare v2.3.0 (#1491)
* mark as redis 7.4 compatible
* run more tests on 8.4
* add 2.3.0 changelog
* don't skip errors
2024-11-21 12:00:02 -08:00
Till Krüss 7631d317fd update year 2024-11-21 11:37:10 -08:00
Vladyslav Vildanov aaec13d074 Added support for INDEXMISSING and INDEXEMPTY arguments (#1464)
* Added support for INDEXMISSING and INDEXEMPTY arguments

* Added version restriction for test

* Codestyle fixes

* Updated test case to remove DIALECT 5

* Updated another test case

* Added correct versions restriction

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2024-11-21 10:19:51 -08:00
Vladyslav Vildanov 52bdcf0c1f Added test case for enhanced exact matching (#1466)
* Added test case for enhanced exact matching

* Added version restriction for test

* Updated test case to use Tag Field instead

* Codestyle fix

* Added edge to stack matrix

* Updated test case to switch DIALECT

* Updated version restriction
2024-11-21 10:00:34 -08:00
Vladyslav Vildanov 1726db0f47 Codestyle updates (#1485) 2024-10-22 09:16:07 -07:00
Vladyslav Vildanov 8fbd34c6b3 Added support for hash field expiration commands (#1456)
* Added support for hash field expiration commands

* Added support for HSETF, HGETF commands

* Removed non-printable ASCII chars from docs

* Removed more non-printable ASCII

* Fixed code style issues

* Extended codespell ignore words list

* Added FIELDS argument, fixes related to comments

* Codestyle fixes

* Fixed typo

* Removed HSETF, HGETF commands

* Added 7.4-rc1 to test matrix

* Fixed test with new response types

* Updated tests against 7.4-rc2 image
2024-10-15 10:01:39 -07:00
Christian Flothmann 0a92618fa1 keep key and value when filtering SET arguments (#1471) 2024-07-11 09:46:52 +03:00
Vladyslav Vildanov d8bb9ac46e Added support for new IGNORE filter (#1458)
* Added support for new IGNORE filter

* Fixed arguments to be mandatory

* Added more test cases

* Codestyle fixes

* Added missing test case

* Updated test cases

* Added additional timeout after index creation

* Fixed broken test and removed non-related functionality

* Fixed tests version requirements

* Updated error message
2024-07-11 09:35:52 +03:00
Vladyslav Vildanov 274e0c17cd Fixed bug with null arguments in SET command (#1470) 2024-07-09 14:10:58 +03:00
Vladyslav Vildanov c27dafa40d [2.x] Added Redis 7.4 commands interface changes (#1459)
* [2.x] Added Redis 7.4 commands interface changes

* Removed RESP3 test case

* Added 7.4-rc1 to test matrix

* Added 7.4.0-rc1 to stack matrix

* Added version restriction for test

* Updated stack image to edge
2024-07-05 16:36:58 +03:00
Vladyslav Vildanov 8c2aac4f66 Added GEOSHAPE field and test polygon search (#1467)
* Added GEOSHAPE field and test polygon search

* Added version restriction for test

* Added edge to stack amtrix

* Added same values assertion

* Codestyle changes
2024-07-05 16:16:16 +03:00
Alexander Mohorev 5d22ed775a Fix prefix for SMISMEMBER (#1468) 2024-07-02 12:41:07 -07:00
Vladyslav Vildanov c5fdfc81ef Added tests case with FLOAT16 and BFLOAT16 vectors (#1465)
* Added tests case with FLOAT16 and BFLOAT16 vectors

* Added version restriction for test

* Updated version restrictions
2024-06-28 11:18:07 -07:00
Markus Reinhold cbef71090b Fix prefixes for LMOVE and BLMOVE (#1455)
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2024-05-02 08:55:20 -07:00
mahshidhp 4dc72458e8 Fix prefix for GEOSEARCH (#1453) 2024-04-30 12:29:30 -07:00
Christian Flothmann e83b393e09 explicitly mark nullable parameters as nullable (#1448)
* explicitly mark nullable parameters as nullable
* add job to run tests with PHP 8.4
2024-04-30 12:14:13 -07:00
Till Krüss ed90750c1f fix prefixes for ZPOPMIN, ZPOPMAX and ZMSCORE (#1451) 2024-04-10 18:07:03 -07:00
René Højbjerg Larsen 45b18eb2e0 Filter out available slaves based on master-link-status flag (#1440) 2024-03-06 08:19:48 -08:00
Till Krüss d44f07339a Run tests under PHP 8.3 (#1396) 2023-10-25 10:08:55 -07:00
Till Krüss a9d18b182c tweak fixer rules 2023-10-24 09:17:43 -07:00
Tobias Bengtsson 5c8b19ebaa Fix operator precedence (#1405)
&& binds tighter than ?? so a parentheses is needed for desired result
2023-09-26 09:11:00 -07:00
Stephan 577bd39872 ClientInterface: using set with NX flag can return null (#1394)
Calling `$client->set('key', '1', 'EX', 7200, 'NX')` for a key that is already set will return null instead of Status
2023-09-14 09:44:52 -07:00
Jiří Bok 6372661dbf Make Relay work with Redis cluster (#1397) 2023-09-13 09:59:50 -07:00
Till Krüss 4846e2ab94 back to dev version 2023-09-13 09:55:14 -07:00
Sergei Predvoditelev 92b284967e Fix cmsincrby method annotation in ClientInterface (#1333) 2023-09-13 09:50:19 -07:00
Till Krüss 08d5298080 fix typos 2023-09-13 09:49:11 -07:00
Igor Malinovskiy d88153b63e Add 7.2 to supported Redis versions (#1367) 2023-09-13 09:47:35 -07:00
Till Krüss b1d3255ed9 tag v2.2.2 2023-09-13 09:42:03 -07:00
Till Krüss cbf394b882 Disable CLIENT SETINFO calls by default (#1399)
Add `client_info` parameter
2023-09-13 09:35:49 -07:00
Till Krüss c6bf644872 bump dev version 2023-09-13 09:34:52 -07:00
Vladyslav Vildanov 16bdd83d23 Added EXPIRETIME command to KeyPrefixProcessor (#1369)
* Added EXPIRETIME command to KeyPrefixProcessor

* Fixed test responses for Redis 7.2

* Marked test as relay-incompatible
2023-08-25 14:27:24 -07:00
Vladyslav Vildanov 912af82bfd Added support for CLUSTER container command (#1360)
* Added support for CLUSTER container command

* Codestyle fixes
2023-08-17 09:34:01 +03:00
Vladyslav Vildanov 2d74db1bde Changes related to Redis 7.2 image update (#1366)
* Added new assertion, fixed RESP3 JSON responses and versions

* Removed expectations for error messages

* Changed tests group for RESP3 not supported tests

* Removed 3.x test case

* Added missing test decorators

* Fixed typo

* Removed redisgraph module upload, as not a part of a redis-stack anymore
2023-08-16 08:18:45 -07:00
Till Krüss c5ee202179 bump version (#1365)
* bump version

* Update Client.php
2023-08-15 16:06:03 -07:00
Till Krüss 5f2b410a74 Update CHANGELOG.md (#1364)
* Update CHANGELOG.md

* Update CHANGELOG.md

* Update CHANGELOG.md
2023-08-15 16:01:46 -07:00
Vladyslav Vildanov f6cf2afe47 Updated CHANGELOG.md (#1363)
* Updated CHANGELOG.md

* Added quotes to CHANGELOG.md

* Codestyle fix
2023-08-15 08:43:46 -07:00
Vladyslav Vildanov 311cd2b79e Added support for WAITAOF command (#1357)
* Added support for WAITAOF command

* Added call to parent setUp method
2023-08-14 09:18:19 +03:00
Vladyslav Vildanov ffd31cfdef Added missing redis-stack commands to KeyPrefix processor (#1358) 2023-08-10 18:57:16 +03:00
Vladyslav Vildanov 1b2fd527ed Added support for Redis 7.0 arguments (#1359) 2023-08-10 18:57:00 +03:00
Vladyslav Vildanov 4172d2265f Client set name and version on connection (#1347)
* Added client metadata on server connection

* Added try...catch around server exception to supress CLIENT command errors

* Added exclusion for Relay connection
2023-08-03 09:04:04 +03:00
Vladyslav Vildanov a3311d6869 2.2.1 version changes (#1349) 2023-08-03 09:03:21 +03:00
Vladyslav Vildanov df14e11c3a Added support for tests running against redis cluster (#1236)
* Added support for tests running against redis cluster

* Test coverage

* Added comment about master nodes

* Codestyle fix

* Revert changes

* Revert DBNUM

* Added cluster endpoints to relay tests env configuration

* Exclude cluster tests from relay tests environment

* Removed TODO comment

* Changed cluster image version to unstable

* Updated configuration to match unstable cluster

* Fixed path

* Updated cluster CI configuration

* Removed redundant flag

* Removed backslash

* Updated file path

* Updated file path variable

* Added docker cluster initialization as additional step

* Run cluster tests as separate workflow

* Codestyle fixes

* Updated exported files

* Added additional timeout so cluster image could be settled

* Added support for different cluster image, use docker compose for cluster tests CI

* Remove unused flag

* Removed variable from volume path

* Added sleep timeout to allow docker setup after running

* Added timeout before tests run

* Updated linter settings

* Include indent changes for.sh files

* Added missing coverage

* Revert expected files and mark docker folder as exclusion

* Specify folder itself as excluded

* Moved cluster tests as separate job in tests.yml

* Updated name to contain cluster word

---------

Co-authored-by: Chayim <chayim@users.noreply.github.com>
2023-07-24 10:21:43 +03:00
Vladyslav Vildanov 7c2e8e01d8 Added support for FUNCTION KILL, FUNCTION LIST, FUNCTION STATS commands (#1334)
* Added support for FUNCTION KILL, FUNCTION LIST, FUNCTION STATS commands

* Marked tests as relay-incompatible
2023-07-12 09:58:00 +03:00
Vladyslav Vildanov 0b6ab4dea4 Added support for CLIENT NO-EVICT command (#1335) 2023-07-12 09:57:42 +03:00
Vladyslav Vildanov dd64569e06 Added support for FUNCTION DUMP, FUNCTION FLUSH, FUNCTION RESTORE commands (#1332) 2023-07-03 10:41:32 +03:00
Vladyslav Vildanov 90da582efc Fixed bug with incorrect multiple words processing (#1325)
* Fixed bug with incorrect multiple words processing

* Convert subcommand string to lower case

* Update SubcommandStrategyResolver.php

* Added test coverage

* Codestyle fixes

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-06-21 12:00:58 +03:00
Till Krüss 732abc88a2 Update CHANGELOG.md 2023-06-14 13:42:52 +03:00
Till Krüss 33b70b971a Update CHANGELOG.md 2023-06-14 13:37:31 +03:00
Vladyslav Vildanov e46d56c45c Fixed subcommand test bug (#1313) 2023-06-08 11:33:25 -04:00
Vladyslav Vildanov c57a6744bb Added support for JSON.MSET command (#1307) 2023-06-08 17:35:04 +03:00
Vladyslav Vildanov df83c94bb3 Added support for JSON.MERGE command (#1304) 2023-06-08 12:16:14 +03:00
Vladyslav Vildanov a711ef96e2 Added GETDEL command to KeyPrefixProcessor (#1306)
* Added GETDEL command to KeyPrefixProcessor

* Added test coverage

* Codestyle fixes

* Added timeout after FT.CREATE call
2023-06-08 11:32:05 +03:00
Vladyslav Vildanov 3c322fc4e3 Codestyle changes related to php-cs-fixer update (#1311)
* Codestyle changes

* Added missing type-hints
2023-06-07 17:05:36 +03:00
Till Krüss 95c23fb94d tag 2.2.0-RC1 2023-05-09 10:45:20 -07:00
Till Krüss 946c4b7bd7 [v2.x] Relay support (#1263) 2023-05-09 10:39:00 -07:00
Vladyslav Vildanov 538c65946d Added timeout to prevent search before create (#1269) 2023-05-03 11:00:31 -07:00
Till Krüss e8ea05dafe spacing 2023-04-19 13:52:53 -07:00
Nicolas Grekas bf2075a176 Add missing @return annotations (#1265)
* Add missing `@return` annotations

* formatting

* formatting

* Update ProcessorChain.php

* Update Handler.php

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-04-19 13:51:42 -07:00
Till Krüss d2cd99492d don't export bin 2023-04-13 09:51:16 -07:00
Vladyslav Vildanov 971e47672d Added Redis stack support (JSON, Search, TimeSeries, Bloom) (#1253) 2023-04-11 08:09:14 -07:00
Till Krüss f9b755ece9 changes [skip ci] 2023-04-05 08:33:26 -07:00
Jess Archer 98d4f80263 Add missing stream key prefixes (#1230)
* Added missing stream key prefixes

* Tested stream command key prefixing
2023-03-29 07:03:45 -07:00
Vladyslav Vildanov 0e019cc08d Extended core support by implementing ACL SETUSER, GETUSER, DRYRUN (#1193)
* Added support for ACL GETUSER, SETUSER, DRYRUN commands

* Change test to support Redis > 6.0.0

* Removed selectors check
2023-03-15 14:57:12 +02:00
Till Krüss b898172009 typo 2023-03-12 09:22:07 -07:00
Vladyslav Vildanov f68543af37 Extended core support by implementing FCALL_RO command (#1191) 2023-03-12 08:52:20 -07:00
Till Krüss a77a43913a tag v2.1.2 2023-03-02 10:32:04 -08:00
Till Krüss fea402743f Deprecate webdis and phpiredis (#1179)
* Deprecate webdis and phpiredis

* remove space
2023-02-28 13:09:56 -08:00
Vladyslav Vildanov 84844acb93 Added CODEOWNERS file (#1181)
* Added CODEOWNERS file

* Update CODEOWNERS

* Applied whole Redis commands path as @vladvildanov codeowner

* Set @predis/team as Redis commands codeowners

* Update CODEOWNERS

---------

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-02-28 13:07:06 -08:00
Till Krüss 26c625230f match MasterSlaveReplication (#1175)
* match `MasterSlaveReplication`

also the name of this method 😬

* Update SentinelReplication.php
2023-02-21 08:30:43 -08:00
David Bomba 8ef75ba6b2 Add option for disabling reads to slaves in replication topologies (#1168)
* Add option for disabling reads to slaves in replication topologies

(cherry picked from commit e132c312a9)

* remove empty line

---------

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-02-21 08:15:58 -08:00
Stephan 8a5ced5251 Fix return type of ReplicationInterface::getSlaves (#1111) 2023-02-08 07:26:27 -08:00
Vladyslav Vildanov 29350952d0 Added stream commands to KeyPrefixProcessor (#1051)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-31 08:50:14 -08:00
Vladyslav Vildanov 98222f47b0 Added support for container commands (#1049)
* Added support for container commands FUNCTION LOAD, FUNCTION DELETE and FCALL

* Changed ContainerInterface and AbstractContainer

* Re-implement logic of abstract methods

---------

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-31 08:48:48 -08:00
Till Krüss 38e955bc26 fix deprecated call 2023-01-29 11:58:46 -08:00
Vladyslav Vildanov db65e5ebd3 Extended core support by implementing SORT_RO command (#1044)
* Added support for SORT_RO command

* Codestyle fixes

* Added command description

---------

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-29 11:38:30 -08:00
Vladyslav Vildanov 50e005bfe3 Added support for new arguments for EXPIRE, EXPIREAT commands (#1046) 2023-01-25 08:00:23 -08:00
Vladyslav Vildanov c541617333 Added support for new arguments for BITPOS, BITCOUNT commands (#1045) 2023-01-25 07:59:44 -08:00
Till Krüss 0a8e0c2f96 remove CONTRIBUTING file 2023-01-21 17:20:25 -08:00
Till Krüss 793de36822 Update README.md 2023-01-21 17:17:25 -08:00
Till Krüss fa13640ddd try another format 2023-01-21 17:05:13 -08:00
Viktor Szépe 5331d943fe Upgrade static analysis to PHPStan level 2 (#1043)
* Upgrade static analysis to PHPStan level 2

* Fix CS and CI

* Fix coverage path

* Start debugging

* Stop debugging
2023-01-21 17:03:53 -08:00
Viktor Szépe 74d5ad22dd Add Coverage badge to README (#1042) 2023-01-21 15:59:53 -08:00
Till Krüss a04bcb94fc try different license format 2023-01-21 14:10:06 -08:00
Till Krüss 9f77e5178f fix license header 2023-01-21 14:08:25 -08:00
Viktor Szépe ac259bdb6f Add complete CI (#1036)
* Add complete CI

* Fix CI

* Fix spelling

* Fix indentation

* Fix CI

* Fix CI

* Revert disabling unit tests

* Add coverage driver to CI

* Start coverage debugging

* Fix debugging
ignored, and an empty message aborts the commit.

* Stop debugging

* Move TODO-s from source to GitHub issues

* Ignore too long lines in certain files

* Revert requiring php-parallel-lint/php-parallel-lint

* formatting

* try shorter formatting

* formatting

* fix syntax

* try two paths?

* Update .editorconfig

Co-authored-by: Viktor Szépe <viktor@szepe.net>

* indentation

* make it a group

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-01-21 13:22:13 -08:00
Till Krüss 6e45ca5154 Create README.md 2023-01-21 13:17:31 -08:00
Viktor Szépe c201af5ad3 Fix PHPStan level 2 problems (#1025)
* Fix almost all PHPStan level 2 problems

* Fix master loop and remove empty line

* Fix variadic functions

* Fix CS

* Disable xdebug in CI and improve a condition

* Fix CI fix
2023-01-20 14:20:53 -08:00
Vladyslav Vildanov 1c6c5feb3a Extended core support by implementing EVALSHA_RO command (#1034) 2023-01-20 11:15:39 -08:00
Vladyslav Vildanov a8c5794b8a Added support for LCS command (#1035) 2023-01-20 11:14:50 -08:00
Vladyslav Vildanov ccc2860ad2 Added support for EVAL_RO command (#1032) 2023-01-20 11:13:46 -08:00
Till Krüss 1cd78095e6 drop phpcs version to 3.3 for php 7.2 support 2023-01-19 09:49:27 -08:00
Till Krüss f6f4830b3c tweak composer config 2023-01-19 09:28:33 -08:00
Vladyslav Vildanov e3ad353125 Extended Sets support by implementing SINTERCARD command (#1027)
* Added support for SINTERCARD command

* Codestyle fixes, added support for php-cs-fixer

* Moved php-cs-fixer dependency to dev

* Removed trailed comma

* Added support for php 7.2

* update scripts

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-01-19 09:17:15 -08:00
Vladyslav Vildanov e00d1a0bd3 Added support for EXPIRETIME command (#1029)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-19 09:15:20 -08:00
Vladyslav Vildanov 64604de751 Added support for PEXPIRETIME command (#1031)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-19 09:14:55 -08:00
Viktor Szépe 20dcb4bb73 Fix LICENSE file (#1026)
GitHub has problems with it
`curl "https://api.github.com/repos/predis/predis" -H "Accept: application/vnd.github.drax-preview+json" -s | jq '.license'`
2023-01-18 16:03:08 -08:00
Fran Moreno 3daf75508d Add phpstan level 0 (#1022)
* Remove unused arguments

* Fix return types

* Removed unused parameter and argument

* Add phpstan job

* merge files

* Delete phpstan-baseline.neon

* Delete static-analysis.yml

* merge workflows

* Update composer.json

* format yaml

* install composer reps

* fix yaml

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-01-18 13:33:51 -08:00
Till Krüss 7a4b3d1d0f Update .editorconfig 2023-01-18 13:27:04 -08:00
Till Krüss 3cf958580a Update .editorconfig 2023-01-18 13:26:53 -08:00
Fran Moreno d6dc6e51e1 Add CS job (#1024)
* Add CS job

* Apply PHP71Migration ruleset
2023-01-18 10:02:26 -08:00
Till Krüss 113145f306 more code formatting 2023-01-17 15:08:18 -08:00
Till Krüss 47a7cbc862 unify code formatting 2023-01-17 15:08:18 -08:00
Till Krüss 3c8a811ca3 update examples 2023-01-17 15:08:18 -08:00
Till Krüss f4bd6d44b1 update cs-fixer config 2023-01-17 15:08:18 -08:00
Till Krüss 6b6179ee44 don’t run tests twice 2023-01-17 15:08:18 -08:00
Till Krüss 82791e55e1 format tests 2023-01-17 15:08:18 -08:00
Till Krüss ea7698e12f use single quotes 2023-01-17 15:08:18 -08:00
Till Krüss af2e5cc553 order imports 2023-01-17 15:08:18 -08:00
Till Krüss b1009f46ac unify spacing 2023-01-17 15:08:18 -08:00
Till Krüss a09da4f3b0 trailing multiline commas 2023-01-17 15:08:18 -08:00
Till Krüss 06c00ac43f import global namespace 2023-01-17 15:08:18 -08:00
Till Krüss f3deda22cd no @link tags 2023-01-17 15:08:18 -08:00
Till Krüss c412594217 align phpdoc vertically 2023-01-17 15:08:18 -08:00
Till Krüss cc40219268 use short array syntax 2023-01-17 15:08:18 -08:00
Till Krüss 31b65f614b Remove @author tags 2023-01-17 13:41:35 -08:00
Till Krüss c9babb1984 update copyright comments 2023-01-17 13:41:35 -08:00
Till Krüss c2af9427c5 update MIT license template 2023-01-17 13:41:35 -08:00
Till Krüss c5b60884e8 tag v2.1.1 2023-01-17 12:57:35 -08:00
Till Krüss 836ab07d40 Fix support options array in ZINTERSTORE and ZUNIONSTORE (#1018)
* support old options array

* fix zinterstore as well

* single override
2023-01-17 12:50:15 -08:00
Fran Moreno 2bfc8a9316 Fix Client template (#1017) 2023-01-17 12:48:39 -08:00
Till Krüss d21576669d remove phpiredis suggestion 2023-01-17 09:42:23 -08:00
Till Krüss 65fe24e346 bump version 2023-01-17 09:42:15 -08:00
Till Krüss fbf270156f tweak workflow formatting 2023-01-16 15:33:05 -08:00
Till Krüss 24630fbd5b tag 2.1.0 2023-01-16 15:21:30 -08:00
Till Krüss bded73f516 tweak release draft template [skip ci] 2023-01-16 15:21:19 -08:00
Till Krüss 6a3f4a4c08 Update release-drafter-config.yml 2023-01-16 15:12:32 -08:00
Vladyslav Vildanov 47896f1be7 Extended core support by implementing BLMPOP command (#1015)
* Added support for LMPOP command

* Added support for BLMPOP command

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2023-01-16 08:46:59 -08:00
erikn69 586b039289 Fix builds badge (#1014) 2023-01-16 08:45:19 -08:00
Vladyslav Vildanov d1acca607e Added support for LMPOP command (#1013)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2023-01-16 08:45:04 -08:00
Vladyslav Vildanov 721c829042 Extended server functionality by implementing FAILOVER command (#875)
* Added arrayable arguments classes

* Updated count trait to accept additional modifier argument

* Added new With traits, moved into separate directory

* Added traits for geo command arguments resolving

* Remove BaseWith trait, not working with traits nesting

* Added AscDesc trait

* Rename AscDesc traint into Sorting

* Fixed trait keyword

* Removed unnecessary traits

* Updated count trait to handle default argument value

* Fixed With traits offset check condition

* Added GeoFrom, GeoBy traits

* Fixes for Count and Sorting traits

* Fixed variable names in with traits

* [WIP] Added GEOSEARCH command support, without test coverage

* Changed functionality to support only lower case units (Redis 6.0 support)

* Changed namespace for WITHSCORES trait

* Added more test coverage, added response parsing

* Added test coverage for tratis

* Added support for FAILOVER command

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-29 12:19:17 -08:00
Vladyslav Vildanov b8cc7c643a Extended Key Space support by implementing COPY command (#866)
* Added support for COPY command

* Revert getCLient signature changes, used createClient instead

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-29 12:18:08 -08:00
Vladyslav Vildanov b47aa7ad3a Extended Geospatial support by implementing GEOSEARCHSTORE command (#873)
* Added arrayable arguments classes

* Updated count trait to accept additional modifier argument

* Added new With traits, moved into separate directory

* Added traits for geo command arguments resolving

* Remove BaseWith trait, not working with traits nesting

* Added AscDesc trait

* Rename AscDesc traint into Sorting

* Fixed trait keyword

* Removed unnecessary traits

* Updated count trait to handle default argument value

* Fixed With traits offset check condition

* Added GeoFrom, GeoBy traits

* Fixes for Count and Sorting traits

* Fixed variable names in with traits

* [WIP] Added GEOSEARCH command support, without test coverage

* Changed functionality to support only lower case units (Redis 6.0 support)

* Changed namespace for WITHSCORES trait

* Added more test coverage, added response parsing

* Added support for GEOSEARCHSTORE command

* Added test coverage for tratis

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Chayim <chayim@users.noreply.github.com>
2022-12-29 12:16:51 -08:00
Vladyslav Vildanov bb65b31580 Extend Geospatial support by implementing GEOSEARCH command (#867)
* Added arrayable arguments classes

* Updated count trait to accept additional modifier argument

* Added new With traits, moved into separate directory

* Added traits for geo command arguments resolving

* Remove BaseWith trait, not working with traits nesting

* Added AscDesc trait

* Rename AscDesc traint into Sorting

* Fixed trait keyword

* Removed unnecessary traits

* Updated count trait to handle default argument value

* Fixed With traits offset check condition

* Added GeoFrom, GeoBy traits

* Fixes for Count and Sorting traits

* Fixed variable names in with traits

* [WIP] Added GEOSEARCH command support, without test coverage

* Changed functionality to support only lower case units (Redis 6.0 support)

* Changed namespace for WITHSCORES trait

* Added more test coverage, added response parsing

* Added test coverage for tratis

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Chayim <chayim@users.noreply.github.com>
2022-12-28 09:10:03 -08:00
Vladyslav Vildanov e540ca062b Added support for SISMEMBER command (#871)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-23 11:18:50 -08:00
Vladyslav Vildanov 9c543ef5b1 Added support for HRANDFIELD command (#870)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-23 11:18:33 -08:00
Vladyslav Vildanov 83fb0020a1 Added support for GETEX command (#872)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-23 11:17:24 -08:00
Vladyslav Vildanov 4a77aea9ef Added support for GETDEL command (#869)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-20 09:32:58 -08:00
Vladyslav Vildanov 72bc11eb63 Extended Sorted Set support by adding ZINTER command (#859)
* Refactored zinterstore, zunionstore commands and command traits

* Merge conflicts resolve, update cluster strategy test with new arguments

* Updated assertion in case if command executed faster then duration minimal threshold

* Added support for ZINTER command

* Added command link and description

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-14 08:54:30 -08:00
Vladyslav Vildanov f26fd899f9 Extend Sorted Set support by implementing BZPOPMAX command (#864)
* Refactored zinterstore, zunionstore commands and command traits

* Merge conflicts resolve, update cluster strategy test with new arguments

* Updated assertion in case if command executed faster then duration minimal threshold

* Updated Keys trait to handle cases when no numkeys modifier needed

* Added support for BZPOPMIN command

* Added command link and description

* Added support for BZPOPMAX command

* Added absract command to fix inheritance chain

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-13 10:26:47 -08:00
Vladyslav Vildanov 65447807ed Extended Sorted Set support by adding ZUNION command (#860)
* Refactored zinterstore, zunionstore commands and command traits

* Merge conflicts resolve, update cluster strategy test with new arguments

* Updated assertion in case if command executed faster then duration minimal threshold

* Added support for ZUNION command

* Added command link and description

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-13 08:41:56 -08:00
Vladyslav Vildanov 5418cd5813 Extended Sorted Set support by adding BLMOVE command (#865)
* Added support for LMOVE command

* Added support for BLMOVE command

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-13 08:38:35 -08:00
Vladyslav Vildanov bc5892e260 Extended Sorted Set support by adding BZPOPMIN command (#862)
* Refactored zinterstore, zunionstore commands and command traits

* Merge conflicts resolve, update cluster strategy test with new arguments

* Updated assertion in case if command executed faster then duration minimal threshold

* Updated Keys trait to handle cases when no numkeys modifier needed

* Added support for BZPOPMIN command

* Added command link and description

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-12 08:38:26 -08:00
Vladyslav Vildanov 7c0cc7bdbe Extended Sorted Set support by adding ZINTERCARD command (#861)
* Refactored zinterstore, zunionstore commands and command traits

* Merge conflicts resolve, update cluster strategy test with new arguments

* Updated assertion in case if command executed faster then duration minimal threshold

* Updated Limit trait to handle integer values

* Updated Limit trait to return previous arguments if limit argument isn't set

* Added support for ZINTERCARD command

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-12 08:38:06 -08:00
Vladyslav Vildanov 87ecd7bde2 Added support for LMOVE command (#863)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-12 08:37:28 -08:00
Vladyslav Vildanov f9e77a0562 Refactored ZUNIONSTORE, ZINTERSTORE, removed Numkeys trait, improved Withscores response parsing (#858) 2022-12-09 07:37:22 -08:00
Vladyslav Vildanov d2b05ff58a Added mixin annotations for traits (#835)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-07 09:19:04 -08:00
Chayim e24ecbbf90 Fixing the release drafter, to honour the main branch (#857) 2022-12-07 12:08:16 +02:00
Vladyslav Vildanov 9f3bdd5616 Extend Sorted Set support by implementing ZRANGESTORE command (#829)
* Added support for ZRANGESTORE command

* Added missing test coverage, added new filter method

* Added test coverage for new traits

* Updated offset for unexpected value tests

* Added missing offset

* Removed version annotation for inconsistency

* Update ZDIFF.php

* Update ZRANGESTORE.php

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-12-06 08:40:06 -08:00
Chayim 57a24413c2 Adding the release drafter for release management (#811) 2022-12-05 09:25:47 -08:00
Vladyslav Vildanov 0e6126ba9d Added support for BZMPOP command (#833) 2022-12-05 08:33:43 -08:00
Vladyslav Vildanov 7904fed6da Added support for ZMPOP command (#831)
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-12-01 12:10:20 -08:00
Vladyslav Vildanov cfd6f030bc Extend Sorted Set support by implementing ZDIFFSTORE command (#828)
* Added support for ZDIFF, added new WITHSCORE trait

* Added trait to resolve numkeys argument

* Added trait for unpacking keys array

* Added static binding for Numkeys trait

* Added ZDIFFSTORE command support

* Changed access modifier type to more strict

* Removed version annotation for inconsistency

* Update ZDIFFSTORE.php

Co-authored-by: Vladislav <vladislav@Admins-MacBook-Pro.local>
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-11-30 13:23:08 -08:00
Vladyslav Vildanov 35d18d739a Added response parser for WithScore trait (#830)
* Added response parser for WithScore trait

* Added test coverage for new method

Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-11-30 13:20:56 -08:00
Vladyslav Vildanov 573c54ac4c Extend Sorted Set support by implementing ZDIFF command (#826)
* Added support for ZDIFF, added new WITHSCORE trait

* Added trait to resolve numkeys argument

* Added trait for unpacking keys array

* Added static binding for Numkeys trait

* Changed access modifier type to more strict

Co-authored-by: Vladislav <vladislav@Admins-MacBook-Pro.local>
Co-authored-by: Vladyslav Vildanov <vladyslavvildanov@Vladyslav-Vildanov-MacBook-Pro.local>
2022-11-28 13:16:30 -08:00
Vladyslav Vildanov 169604bf74 Extend Sorted Set support by implementing ZRANDMEMBER command (#825)
* Added support for ZRANDMEMBER, added test coverage

* Changed key to more specific on exception testing

Co-authored-by: Vladislav <vladislav@Admins-MacBook-Pro.local>
2022-11-21 08:37:04 -08:00
vladvildanov 94bd54b2af Extend Sorted Set support by implementing ZMSCORE (#823) 2022-11-17 07:48:16 -08:00
Josh England bdebad7d62 added annotations to suppress PHP 8.1 return type deprecation warning… (#810)
* added annotations to suppress PHP 8.1 return type deprecation warning for `IteratorAggregate::toIterator()`

* move import

Co-authored-by: Josh England <joshua.england@trinet.com>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-11-02 17:07:32 -07:00
Till Krüss 1a411d2ad7 back to dev version 2022-10-11 09:57:28 -07:00
Till Krüss 1400689df8 switch to actions/checkout@v3 [skip ci] 2022-10-11 09:56:57 -07:00
Till Krüss ff59f74581 bump version 2022-10-11 09:52:29 -07:00
Mehmet Tolga Avcioglu 1a0eb7ee85 sentinel default to no password when replica authentication is used (#807)
* set default nopass if password is not provided

* remove debug output

* added tests for noauth sentinel

* Update SentinelReplication.php

Co-authored-by: Mehmet Tolga Avcioglu <mehmet.avcioglu@pusula.net.tr>
Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-10-06 08:14:47 -07:00
Tobias Bengtsson bb6c1a7b6d Add partial support for Stream commands (#804)
Adds support for the following commands not related to groups/consumers:
XADD, XDEL, XLEN, XRANGE, XREVRANGE, XTRIM.
2022-09-27 09:39:17 -07:00
streamingsystems 42c33a406f Check if socket is resource before reading (#802) 2022-09-18 15:01:02 -07:00
Stefano Borghi 7ad74217c2 check resource before writing, w/ test (#800) 2022-09-16 17:03:13 -07:00
Alexandru Pătrănescu 72d7675563 improve PHP 8.2 support (#797)
* use static::class . '::<method>' instead of 'static::method'

* extract concatenation so it can be improved easier at a later point

one improvement at some point could be to replace static::class . '::<method>' with static::<method>(...) in PHP 8.1+

Co-authored-by: Alexandru Patranescu <alexandru.patranescu@payu.com>
2022-09-08 11:25:37 -07:00
Till Krüss 8b5fa92856 mention php version [no ci] 2022-09-06 07:34:14 -07:00
Till Krüss 076a62e3d3 bump version to 2.0.2 2022-09-06 07:32:44 -07:00
Dries Vints 85dc1752b7 PHP 8.2 Support (#796) 2022-09-06 07:13:46 -07:00
Till Krüss 7683215023 bump tag to v2.0.1 2022-09-04 14:57:36 -07:00
Till Krüss dd4ddf6504 Update CHANGELOG.md 2022-08-03 11:53:59 -07:00
Till Krüss 6468e6cc2e Update CHANGELOG.md 2022-08-03 11:51:22 -07:00
digital2real 12f6d30502 Add retry logic to support temporary redis cluster failure (#788)
* Add retry logic to support temporary redis cluster failure

* formatting

* Use exponential backoff retries.
$minRetryAfter cant be changed if needed with RedisCluster::setMinRetryAfter

* fix formating

* (hotfix) formaing + import import  \Predis\Response\Error and \Predis\Connection\ConnectionException

* Update RedisCluster.php

* formatting

* tweaks

* Update RedisCluster.php

* Update RedisCluster.php

* Update RedisCluster.php

* Update unit tests regarding renaming of "retryInterval"

* spacing

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-08-03 11:49:56 -07:00
Linc a602fc7425 Fix sentinel reconnect issue on long-running PHP processes (#784)
* Fix no sentinel server available for autodiscovery on Swoole

* Fix errors in PHPUnit 9.5

the reason: https://github.com/sebastianbergmann/phpunit/commit/68582043e149039cfa3596b42ed35753dcf54fb2?fbclid=IwAR1qy1jFNFeJ3hUt5k7XAflqyCTUTWZhEqVSeizkybVHUEqXjBZ1gJM739U

* add restart sentinel test
2022-07-12 09:44:28 -07:00
John Paul E. Balandan, CPA 4ec74cc5fe Declare $parameters property of Predis\Connection\Parameters (#781) 2022-06-29 07:58:14 -07:00
BrightQi 78fd4cb998 bugfix for srem type to accept array #779 (#780)
* bugfix for srem  type to accept array #779

* add test to test SREM accept members as array type #779
2022-06-28 08:23:35 -07:00
Tomáš Fedor 2a8dd6a7f1 Add array as possible return type to spop (#774)
* Add array as possible return type to spop

* Update ClientInterface.php

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-06-14 19:59:10 -07:00
Jayin Taung 7d7b3416a8 Add example for installing predis by Composer (#772)
* Add example for installing predis by Composer

* Update README.md

Co-authored-by: Till Krüss <tillkruss@users.noreply.github.com>
2022-06-13 07:54:46 -07:00
1121 changed files with 55455 additions and 6581 deletions
+6
View File
@@ -0,0 +1,6 @@
[codespell]
skip=./.git
check-hidden=
check-filenames=
builtin=clear,rare,informal,usage,code,names
ignore-words-list=master,masters,slave,slaves,whitelist,cas,exat,smove,SUGGET,sugget,ro,DOF,dof
+1
View File
@@ -0,0 +1 @@
coverage_clover: build/logs/clover-*.xml
+15 -5
View File
@@ -1,5 +1,3 @@
# http://editorconfig.org
root = true
[*]
@@ -8,10 +6,22 @@ indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
block_comment_start = /*
block_comment = *
block_comment_end = */
[*.php]
trim_trailing_whitespace = true
max_line_length = 120
max_line_length = 150
[*.{md,yml}]
[*.{md,yml,yaml,neon,sh}]
indent_size = 2
[VERSION]
insert_final_newline = false
[tests/**.php]
max_line_length = unset
[{src/ClientInterface.php,src/ClientContextInterface.php}]
max_line_length = unset
+13 -2
View File
@@ -1,9 +1,20 @@
* text=auto
/tests export-ignore
/.github export-ignore
/bin export-ignore
/examples export-ignore
/tests export-ignore
/.codespellrc export-ignore linguist-language=INI
/.coveralls.yml export-ignore
/.editorconfig export-ignore
/.gitattributes export-ignore
/.gitignore export-ignore
/.php_cs.dist export-ignore
/.php-cs-fixer.dist.php export-ignore
/CHANGELOG.md export-ignore linguist-documentation
/CONTRIBUTING.md export-ignore linguist-documentation
/FAQ.md export-ignore linguist-documentation
/VERSION export-ignore
/phpunit.relay.xml export-ignore
/phpunit.xml.dist export-ignore
/phpstan.dist.neon export-ignore
/phpstan-tests.dist.neon export-ignore
+14
View File
@@ -0,0 +1,14 @@
# Default
* @tillkruss
# Redis commands
src/Command/Redis/* @predis/team @tillkruss
# Redis Stack
src/Command/Redis/Json/* @predis/team
src/Command/Redis/Search/* @predis/team
src/Command/Redis/TopK/* @predis/team
src/Command/Redis/TDigest/* @predis/team
src/Command/Redis/BloomFilter/* @predis/team
src/Command/Redis/CuckooFilter/* @predis/team
src/Command/Redis/CountMinSketch/* @predis/team
+4 -4
View File
@@ -19,10 +19,10 @@ Steps to reproduce the behavior:
A clear and concise description of what you expected to happen.
**Versions (please complete the following information):**
- Predis: [e.g. 1.1.2]
- PHP [e.g. 8.0.0]
- Redis Server [e.g. 6.0.0]
- OS [e.g. Ubuntu 20.10]
- Predis: [e.g. 1.1.2]
- PHP [e.g. 8.0.0]
- Redis Server [e.g. 6.0.0]
- OS [e.g. Ubuntu 20.10]
**Code sample**
If applicable, a small snippet of code that reproduces the issue.
+73
View File
@@ -0,0 +1,73 @@
---
services:
redis-official:
image: ${REDIS_IMAGE_NAME:-redis:7.4}
container_name: redis-standalone
healthcheck:
test: [ "CMD", "redis-cli", "PING" ]
interval: 10s
timeout: 5s
retries: 3
ports:
- "6379:6379"
profiles:
- all
- official
- standalone
redis-clients:
image: ${REDIS_IMAGE_NAME:-redislabs/client-libs-test:7.4.2}
container_name: redis-standalone
environment:
- TLS_ENABLED=yes
- REDIS_CLUSTER=no
- PORT=6379
- TLS_PORT=6666
command: ${REDIS_EXTRA_ARGS:---enable-debug-command yes --enable-module-command yes --tls-auth-clients optional --save ""}
ports:
- 6379:6379
- 6666:6666 # TLS port
volumes:
- "./dockers/standalone:/redis/work"
profiles:
- all
- clients
- standalone
redis-cluster:
image: ${REDIS_IMAGE_NAME:-redislabs/client-libs-test:7.4.2}
container_name: redis-cluster
environment:
- REDIS_CLUSTER=yes
- NODES=6
- REPLICAS=1
- TLS_ENABLED=yes
- PORT=16379
- TLS_PORT=27379
command: ${REDIS_EXTRA_ARGS:---enable-debug-command yes --enable-module-command yes --tls-auth-clients optional --save ""}
ports:
- "6372-6377:16379-16384"
volumes:
- "./dockers/cluster:/redis/work"
profiles:
- all
- clients
- cluster
redis-stack:
image: ${REDIS_STACK_IMAGE_NAME:-redislabs/client-libs-test:rs-7.4.0-v2}
container_name: redis-stack
ports:
- "6479:6379"
environment:
- REDIS_CLUSTER=no
- PORT=6379
command: ${REDIS_EXTRA_ARGS:---enable-debug-command yes --enable-module-command yes --save ""}
volumes:
- "./dockers/redis-stack:/redis/work"
profiles:
- all
- clients
- stack
+49
View File
@@ -0,0 +1,49 @@
name-template: 'v$NEXT_MINOR_VERSION'
tag-template: 'v$NEXT_MINOR_VERSION'
change-template: '- $TITLE (#$NUMBER)'
autolabeler:
- label: 'maintenance'
files:
- '*.md'
- '.github/*'
- label: 'bug'
branch:
- '/bug-.+'
- label: 'maintenance'
branch:
- '/maintenance-.+'
- label: 'feature'
branch:
- '/feature-.+'
categories:
- title: 'Breaking Changes'
labels:
- 'breakingchange'
- title: 'Experimental Features'
labels:
- 'experimental'
- title: 'New Features'
labels:
- 'feature'
- 'enhancement'
- title: 'Bug Fixes'
labels:
- 'fix'
- 'bugfix'
- 'bug'
- 'BUG'
- title: 'Maintenance'
label: 'maintenance'
exclude-labels:
- 'skip-changelog'
template: |
$CHANGES
## Contributors
We'd like to thank all the contributors who worked on this release!
$CONTRIBUTORS
+9
View File
@@ -0,0 +1,9 @@
# Workflows
## Delete runs by workflow name
```bash
gh run list --workflow 'redis-server-tests.yml' --limit 1000 --json databaseId \
| jq '.[].databaseId' \
| xargs -I % gh api --silent -X DELETE /repos/predis/predis/actions/runs/%
```
+167
View File
@@ -0,0 +1,167 @@
# yaml-language-server: $schema=https://json.schemastore.org/github-workflow
name: Linters
on:
push:
branches:
- main
- v2.**
pull_request: null
permissions: {}
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
byte_level:
name: Byte-level
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Check file permissions
run: test "$(find . -type f -not -path './.git/*' -executable)" = "./bin/create-command-test"
- name: "Find non-printable ASCII characters"
run: |
! LC_ALL=C.UTF-8 find . -type f -name '*.php' -print0 \
| xargs --null -- grep --perl-regexp --with-filename --line-number '[^ -~ü]'
syntax_errors:
name: Syntax errors
runs-on: ubuntu-latest
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: "8.1"
coverage: none
tools: parallel-lint
- name: Checkout repository
uses: actions/checkout@v3
- name: Check source code for syntax errors
run: composer exec -- parallel-lint bin/ examples/ src/ tests/
static_analysis:
name: Static Analysis
needs:
- byte_level
- syntax_errors
runs-on: ubuntu-latest
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: "8.2"
coverage: none
- name: Checkout repository
uses: actions/checkout@v3
- name: Validate Composer configuration
run: composer validate --no-interaction --strict
- name: Install dependencies
uses: ramsey/composer-install@v2
with:
dependency-versions: highest
- name: Check PSR-4 mapping
run: composer dump-autoload --no-interaction --optimize --strict-psr
- name: Perform static analysis
run: composer run phpstan
- name: Perform static analysis on tests
run: composer run phpstan -- --configuration=phpstan-tests.dist.neon
coding_standards:
name: Coding Standards
needs:
- byte_level
- syntax_errors
runs-on: ubuntu-latest
steps:
- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: "8.1"
coverage: none
- name: Checkout repository
uses: actions/checkout@v3
- name: Check EditorConfig configuration
run: test -f .editorconfig
- name: Check adherence to EditorConfig
uses: greut/eclint-action@v0
- name: Install dependencies
uses: ramsey/composer-install@v2
with:
dependency-versions: highest
- name: Check coding style
run: composer exec -- php-cs-fixer fix --diff --dry-run --allow-risky=yes --using-cache=no
- name: Search for TODO-s and FIXME-s
run: |
! git grep --extended-regexp --ignore-case '\b(TODO|FIXME)\b' -- ':/' ':!tests/*' ':!*/linters\.yml'
exported_files:
name: Exported files
needs:
- byte_level
- syntax_errors
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Check exported files
run: |
EXPECTED="LICENSE,README.md,autoload.php,composer.json"
CURRENT="$(
git archive HEAD \
| tar --list --exclude="src" --exclude="src/*" --exclude="bin" --exclude="bin/*" \
| paste --serial --delimiters=","
)"
echo "CURRENT =${CURRENT}"
echo "EXPECTED=${EXPECTED}"
test "${CURRENT}" = "${EXPECTED}"
spelling:
name: Spelling
needs:
- byte_level
- syntax_errors
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v3
- name: Cache pip
uses: actions/cache@v3
with:
path: ~/.cache/pip
key: ${{ runner.os }}-pip-codespell
- name: Install codespell
run: pip install --user 'codespell>=2.2'
- name: Search for misspellings
run: $(python -m site --user-base)/bin/codespell
+25
View File
@@ -0,0 +1,25 @@
name: Release Drafter
on:
push:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
update_release_draft:
name: Update release draft
runs-on: ubuntu-latest
steps:
- uses: release-drafter/release-drafter@v5
with:
config-name: release-drafter-config.yml
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+164 -33
View File
@@ -1,52 +1,183 @@
name: Tests
on:
- push
- pull_request
push:
branches:
- main
- v2.**
pull_request:
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
predis:
name: PHP ${{ matrix.php-versions }} (Redis ${{ matrix.redis-versions }})
name: PHP ${{ matrix.php }} (Redis ${{ matrix.redis }})
runs-on: ubuntu-latest
services:
redis:
image: redis:${{ matrix.redis-versions }}
ports:
- 6379:6379
options: --health-cmd="redis-cli ping" --health-interval=10s --health-timeout=5s --health-retries=3
strategy:
fail-fast: false
matrix:
php-versions: ['7.2', '7.3', '7.4', '8.0', '8.1']
redis-versions: ['3', '4', '5', '6', '7']
php:
- '7.2'
- '8.0'
- '8.3'
- '8.4'
redis:
- '4.0'
- '6.2'
- '7.2'
- '7.4'
- '8.0'
steps:
- name: Checkout
uses: actions/checkout@v2
- name: Setup PHP with Composer and extensions
with:
php-version: ${{ matrix.php-versions }}
uses: shivammathur/setup-php@v2
- name: Resolve container name
run: |
# Mapping of original redis versions to client test containers
declare -A redis_clients_version_mapping=(
["8.0"]="8.0-M05-pre"
["7.4"]="7.4.2"
["7.2"]="7.2.7"
["6.2"]="6.2.17"
)
- name: Get Composer cache directory
id: composercache
run: echo "::set-output name=dir::$(composer config cache-files-dir)"
# Mapping of redis version to stack version
declare -A redis_stack_version_mapping=(
["7.4"]="rs-7.4.0-v3"
["7.2"]="rs-7.2.0-v15"
["6.2"]="rs-6.2.6-v19"
)
- name: Cache Composer dependencies
uses: actions/cache@v2
with:
path: ${{ steps.composercache.outputs.dir }}
key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }}
restore-keys: ${{ runner.os }}-composer-
if [[ -v redis_clients_version_mapping[${{ matrix.redis }}] ]]; then
echo "REDIS_IMAGE_NAME=redislabs/client-libs-test:${redis_clients_version_mapping[${{ matrix.redis }}]}" >> $GITHUB_ENV
echo "REDIS_STACK_IMAGE_NAME=redislabs/client-libs-test:${redis_stack_version_mapping[${{ matrix.redis }}]}" >> $GITHUB_ENV
echo "DOCKER_SERVICE=redis-clients" >> $GITHUB_ENV
- name: Install Composer dependencies
env:
PHP_VERSION: ${{ matrix.php-versions }}
run: composer install --no-progress --prefer-dist --optimize-autoloader $(if [ "$PHP_VERSION" == "8.0" ]; then echo "--ignore-platform-reqs"; fi;)
redis_major_version=$(echo "${{ matrix.redis }}" | grep -oP '^\d+')
- name: Test with PHPUnit
run: vendor/bin/phpunit
# Some configuration options available since Redis > 7
if (( redis_major_version < 7 )); then
echo "REDIS_EXTRA_ARGS="--tls-auth-clients optional --save ''"" >> $GITHUB_ENV
else
# Since 8.0 modules are bundled with core
echo "REDIS_STACK_SERVER_PORT=6379" >> $GITHUB_ENV
fi
else
echo "REDIS_IMAGE_NAME=redis:${{ matrix.redis }}" >> $GITHUB_ENV
echo "DOCKER_SERVICE=redis-official" >> $GITHUB_ENV
fi
- name: Checkout repository
uses: actions/checkout@v3
- name: Start Redis standalone image
uses: hoverkraft-tech/compose-action@v2.0.1
with:
compose-file: .github/docker-compose.yml
services: ${{ env.DOCKER_SERVICE }}
- name: Start Redis stack image
id: stack_infra
uses: hoverkraft-tech/compose-action@v2.0.1
if: ${{ matrix.redis >= '6.2' && matrix.redis < '8.0' }}
with:
compose-file: .github/docker-compose.yml
services: redis-stack
- name: Start Redis cluster image
id: cluster_infra
uses: hoverkraft-tech/compose-action@v2.0.1
if: ${{ matrix.redis > '4.0' }}
with:
compose-file: .github/docker-compose.yml
services: redis-cluster
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: relay
coverage: ${{ (matrix.php == '8.4' && matrix.redis == '7.4') && 'xdebug' || 'none' }}
- name: Install Composer dependencies
uses: ramsey/composer-install@v2
with:
dependency-versions: highest
composer-options: ${{ matrix.php == '8.0' && '--ignore-platform-reqs' || '' }}
- name: Run tests
if: ${{ matrix.php != '8.4' || matrix.redis != '7.4' }}
run: vendor/bin/phpunit
- name: Run tests with coverage
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' }}
run: vendor/bin/phpunit --coverage-php build/cov/coverage-predis.cov --coverage-filter ./src
- name: Run tests using Relay
if: ${{ matrix.php != '8.4' && matrix.redis >= '6.2' }}
run: vendor/bin/phpunit -c phpunit.relay.xml
- name: Run tests using Relay with coverage
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' }}
run: vendor/bin/phpunit -c phpunit.relay.xml --coverage-php build/cov/coverage-relay.cov --coverage-filter ./src
- name: Run stack tests
if: ${{ (matrix.php != '8.4' || matrix.redis != '7.4') && matrix.redis >= '6.2' }}
run: vendor/bin/phpunit --group realm-stack
- name: Run stack tests with coverage
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' && steps.stack_infra.conclusion == 'success' }}
run: vendor/bin/phpunit --group realm-stack --coverage-php build/cov/coverage-stack.cov --coverage-filter ./src
env:
REDIS_STACK_SERVER_PORT: 6479
- name: Run stack tests using Relay
if: ${{ matrix.php != '8.4' && matrix.redis == '7.4' }}
run: vendor/bin/phpunit --group realm-stack -c phpunit.relay.xml
- name: Run stack tests using Relay with coverage
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' }}
run: vendor/bin/phpunit --group realm-stack -c phpunit.relay.xml --coverage-php build/cov/coverage-stack-relay.cov --coverage-filter ./src
env:
REDIS_STACK_SERVER_PORT: 6479
- name: Run tests against cluster
if: ${{ (matrix.php != '8.4' || matrix.redis != '7.4') && steps.cluster_infra.conclusion == 'success' }}
run: |
vendor/bin/phpunit --group cluster
- name: Run tests against cluster with coverage
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' && steps.cluster_infra.conclusion == 'success' }}
run: |
vendor/bin/phpunit --group cluster --coverage-php build/cov/coverage-cluster.cov --coverage-filter ./src
- name: Run tests against cluster using Relay
if: ${{ matrix.php != '8.4' && matrix.redis == '7.4' }}
run: |
vendor/bin/phpunit -c phpunit.relay.xml --group cluster
- name: Merge coverage reports
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' }}
run: php vendor/bin/phpcov merge --clover build/logs/clover.xml build/cov
- name: Send coverage to Coveralls
uses: coverallsapp/github-action@v2
if: ${{ matrix.php == '8.4' && matrix.redis == '7.4' }}
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
parallel: true
finish:
name: Finish Coverall
needs: predis
if: ${{ always() }}
runs-on: ubuntu-latest
steps:
- name: Coveralls Finished
uses: coverallsapp/github-action@v2
with:
parallel-finished: true
+2
View File
@@ -1,6 +1,8 @@
/build
/vendor
.php-version
.php_cs.cache
.phpunit.result.cache
.php-cs-fixer.cache
composer.lock
phpunit.xml
+43
View File
@@ -0,0 +1,43 @@
<?php
$PREDIS_HEADER = <<<EOS
This file is part of the Predis package.
(c) 2009-2020 Daniele Alessandri
(c) 2021-2025 Till Krüss
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOS;
$fixer = new PhpCsFixer\Config;
$fixer->setParallelConfig(
\PhpCsFixer\Runner\Parallel\ParallelConfigFactory::detect()
);
$fixer->setRules([
'@PHP71Migration' => true,
'header_comment' => ['header' => $PREDIS_HEADER],
'@Symfony' => true,
'phpdoc_separation' => false,
'phpdoc_annotation_without_dot' => false,
'no_superfluous_phpdoc_tags' => false,
'no_unneeded_curly_braces' => false,
'no_unneeded_braces' => false,
'global_namespace_import' => true,
'yoda_style' => false,
'single_line_throw' => false,
'concat_space' => ['spacing' => 'one'],
'increment_style' => false,
'trailing_comma_in_multiline' => ['after_heredoc' => true, 'elements' => ['array_destructuring', 'arrays']]
])
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__ . '/bin')
->in(__DIR__ . '/examples')
->in(__DIR__ . '/src')
->in(__DIR__ . '/tests')
);
return $fixer;
-33
View File
@@ -1,33 +0,0 @@
<?php
$PREDIS_HEADER = <<<EOS
This file is part of the Predis package.
(c) Daniele Alessandri <suppakilla@gmail.com>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOS;
return PhpCsFixer\Config::create()
->setUsingCache(true)
->setRules(array(
'@Symfony' => true,
'header_comment' => array(
'header' => $PREDIS_HEADER,
),
'ordered_imports' => true,
'phpdoc_order' => true,
'binary_operator_spaces' => array(
'align_double_arrow' => false,
'align_equals' => false,
),
'array_syntax' => array('syntax' => 'long'),
))
->setFinder(
PhpCsFixer\Finder::create()
->in(__DIR__.'/bin')
->in(__DIR__.'/src')
->in(__DIR__.'/tests')
->in(__DIR__.'/examples')
);
+175 -5
View File
@@ -1,5 +1,175 @@
## Changelog
## v2.4.0-RC1 (2024-11-21)
### Added
- Added new hash-field expiration commands (#1520)
- Added missing `FT._LIST` and `BITFIELD_RO` commands (#1521)
### Changed
- Update `WATCH` command to accept `string|string[]` (#1476)
- Optimize cluster slotmap with compact slot range object (#1493)
### Fixed
- Fixed `EVAL_RO` cluster support (#1449)
- Fixed PHP 8.4 compatibility with `stream_context_set_option()` (#1503)
- Prevent named arguments runtime failure (#1509)
- Mark `GEOSEARCH` as read-only to ensure execution on replica (#1481)
### Maintenance
- Added CI testing with Redis 8.0 (#1510)
- Added test coverage for compatibility with Redis 8.0 (#1513)
- Use parallel on PHP-CS-Fixer (#1489)
## v2.3.0 (2024-11-21)
### Added
- Added `GeoShapeField` field (#1467)
- Added hash expiration commands (#1456)
- Added support for time series `IGNORE` filter (#1458)
- Added `XREAD` commands (#1459)
- Added `NOVALUES` argument support to `HSCAN` (#1459)
- Added support for search `INDEXMISSING` and `INDEXEMPTY` arguments (#1464)
### Changed
- Explicitly mark nullable parameters as nullable (#1448)
- Filter out available replicas based on link status flag (#1440)
- Respect `prefix` for `ZPOPMIN`, `ZPOPMAX`, `ZMSCORE`, `LMOVE`, `BLMOVE`, `SMISMEMBER` and `GEOSEARCH` (#1451, #1453, #1455, #1468)
- Updated test infrastructure (#1510)
### Fixed
- Fixed Relay support when using Redis Cluster (#1397)
- Fixed `cmsincrby()` type annotation (#1333)
- Fixed `set()` type annotation (#1394)
- Fixed operator precedence in connection factory (#1405)
- Fixed a bug with `null` arguments in `set()` method (#1470, #1471)
## v2.2.2 (2023-09-13)
### Added
- Added `client_info` client parameter
- Added support for `CLUSTER` container command
### Fixed
- Fixed `EXPIRETIME` not using `prefix`
- Disabled `CLIENT SETINFO` calls by default
## v2.2.1 (2023-08-15)
### Added
- Added support for `WAITAOF` command (#1357)
- Added support for `SHUTDOWN` command (#1359)
- Added support for `FUNCTION` command (#1332)
- Added support for new optional `PEXPIRE`, `PEXPIREAT` and `COMMAND`
- Added missing Redis Stack commands to `KeyPrefixProcessor` (#1358)
### Changed
- Set client name and version when establishing a connection (#1347)
## v2.2.0 (2023-06-14)
Predis v2.2.0 introduces official support for [Redis Stack](https://redis.io/docs/stack/) as well as a [Relay](https://github.com/cachewerk/relay) integration for substantially [faster read performance](https://github.com/predis/predis/wiki/Using-Relay).
### Added
- Added support for [Relay](https://github.com/predis/predis/wiki/Using-Relay) (#1263)
- Added support for `FCALL_RO` command (#1191)
- Added support for Redis `JSON`, `Bloom`, `Search` and `TimeSeries` module (#1253)
- Added support for `ACL SETUSER, GETUSER, DRYRUN` commands (#1193)
### Changed
- Minor code style and type-hint changes (#1311)
### Fixed
- Fixed prefixes for `XTRIM` and `XREVRANGE` commands (#1230)
- Fixed `fclose()` being called on invalid stream resource (#1199)
- Fixed `BitByte` and `ExpireOptions` traits skip processing on null values (#1169)
- Fixed missing `@return` annotations (#1265)
- Fixed `GETDEL` prefixing (#1306)
## v2.1.2 (2023-03-02)
### Added
- Added stream commands to `KeyPrefixProcessor` (#1051)
- Added `ReplicationStrategy::$loadBalancing` option to disable replica reads (#1168)
- Added support for `FCALL` and `FUNCTIONS` commands (#1049)
- Added support for `PEXPIRETIME` command (#1031)
- Added support for `EXPIRETIME` command (#1029)
- Added support for `EVAL_RO` command (#1032)
- Added support for `LCS` command (#1035)
- Added support for `SORT_RO` command (#1044)
- Added support for `SINTERCARD` command (#1027)
- Added support for `EVALSHA_RO` command (#1034)
- Added support for new arguments for `BITPOS` and `BITCOUNT` commands (#1045)
- Added support for new arguments for `EXPIRE` and `EXPIREAT` commands (#1046)
### Bug Fixes
- Fixed deprecated function call syntax
### Deprecated
- Further deprecated phpiredis and webdis integration (#1179)
### Maintenance
- Applied coding standards
- Pass PHPStan level 2
## v2.1.1 (2023-01-17)
### Bug Fixes
- Fix `@template` in `Predis\Client` (#1017)
- Fix support options array in `ZINTERSTORE` and `ZUNIONSTORE` (#1018)
### Deprecated
- Deprecated phpiredis and webdis connections
## v2.1.0 (2023-01-16)
### New Features
- Implemented `GETEX` command (#872)
- Implemented `GETDEL` command (#869)
- Implemented `COPY` command (#866)
- Implemented `FAILOVER` command (#875)
- Implemented `LMOVE` command (#863)
- Implemented `LMPOP` command (#1013)
- Implemented `HRANDFIELD` command (#870)
- Implemented `SMISMEMBER` command (#871)
- Implemented `ZMPOP` command (#831)
- Implemented `BLMOVE` command (#865)
- Implemented `BLMPOP` command (#1015)
- Implemented `BZMPOP` command (#833)
- Implemented `BZPOPMIN` command (#862)
- Implemented `BZPOPMAX` command (#864)
- Implemented `ZUNION` command (#860)
- Implemented `ZINTER` command (#859)
- Implemented `ZINTERCARD` command (#861)
- Implemented `ZRANGESTORE` command (#829)
- Implemented `ZDIFFSTORE` command (#828)
- Implemented `ZDIFF` command (#826)
- Implemented `ZRANDMEMBER` command (#825)
- Implemented `ZMSCORE` (#823)
- Implemented `GEOSEARCH` command (#867)
- Implemented `GEOSEARCHSTORE` command (#873)
### Bug Fixes
- Added annotations to suppress PHP 8.1 return type deprecation warning (#810)
### Maintenance
- Added mixin annotations for traits (#835)
## v2.0.3 (2022-10-11)
- Improved PHP 8.2 support
- Call `is_resource()` before reading/writing
- Added partial support for Redis Stream commands
- Fixed Sentinel authentication issue
## v2.0.2 (2022-09-06)
- Fixed PHP 8.2 deprecation notice: Use of "static" in callables
## v2.0.1 (2022-09-04)
- Added retry interval to `RedisCluster` with a default of `10ms`
- Avoid PHP 8.2 warning in `Connection\Parameters`
- Fixed Sentinel reconnect issue in long-running PHP processes
## v2.0.0 (2022-06-08)
- Dropped support for PHP 7.1 and older
@@ -11,7 +181,7 @@
- `cluster`: string value (`predis`, `redis`), callable returning an aggregate
connection.
- `replication`: string value (`predis`, `sentinel`), callable returning an
aggregate connection.
aggregate connection.
- `commands`: command factory, named array mapping command IDs to PHP classes,
callable returning a command factory or a named array.
- `connections`: connection factory, callable object returning a connection
@@ -24,7 +194,7 @@
acting as initializer instead of an aggregate connection instance.
- The `connections` client option now accepts certain string values identifying
certain combinations of configurations for the connection factory. Currenlty
certain combinations of configurations for the connection factory. Currently
this is used to provide a short way to configure Predis to load our phpiredis
based connection backends simply, accepted values are:
@@ -49,7 +219,7 @@
supported by the redis-sentinel backend due to its dynamic nature (connections
are retrieved and initialized at runtime from sentinels) but it is possible to
get a single connection from the pool by using its ID. It is also possible to
retrive a connection by role using the method getConnectionByRole().
retrieve a connection by role using the method getConnectionByRole().
- The concept of connection ID (ip:port pair) and connection alias (the `alias`
parameter) in `Predis\Connection\Cluster\PredisCluster` has been separated.
@@ -109,7 +279,7 @@
- Support Pub/Sub and Pipelines when using replication
- The class `Predis\Transaction\AbortedMultiExecException` now uses the correct
- The class `Predis\Transaction\AbortedMultiExecException` now uses the correct
default types for the `$code` (integer) parameter.
- __FIX__: using `strval` in `getScanOptions()` method, part of
@@ -117,7 +287,7 @@
string value of `$this->match` and not passing `null` to `strlen()` function.
- __FIX__: the value returned from `getArgument()` in `isReadOperation()` method,
part of `Predis\Replication\ReplicationStrategy` class, is checked to not pass
part of `Predis\Replication\ReplicationStrategy` class, is checked to not pass
`null` to `sha1` function.
- __FIX__: the value returned from `getArgument()` in `parseResponse()`method,
-44
View File
@@ -1,44 +0,0 @@
## Filing bug reports ##
Bugs or feature requests can be posted on the [GitHub issues](http://github.com/predis/predis/issues)
section of the project.
When reporting bugs, in addition to the obvious description of your issue you __must__ always provide
some essential information about your environment such as:
1. version of Predis (check the `VERSION` file or the `Predis\Client::VERSION` constant).
2. version of Redis (check `redis_version` returned by [`INFO`](http://redis.io/commands/info)).
3. version of PHP.
4. name and version of the operating system.
5. when possible, a small snippet of code that reproduces the issue.
__Think about it__: we do not have a crystal ball and cannot predict things or peer into the unknown
so please provide as much details as possible to help us isolating issues and fix them.
__Never__ use GitHub issues to post generic questions about Predis! When you have questions about
how Predis works or how it can be used, please just hop me an email and I will get back to you as
soon as possible.
## Contributing code ##
If you want to work on Predis, it is highly recommended that you first run the test suite in order
to check that everything is OK and report strange behaviours or bugs. When modifying Predis please
make sure that no warnings or notices are emitted by PHP running the interpreter in your development
environment with the `error_reporting` variable set to `E_ALL | E_STRICT`.
The recommended way to contribute to Predis is to fork the project on GitHub, create topic branches
on your newly created repository to fix bugs or add new features (possibly with tests covering your
modifications) and then open a pull request with a description of the applied changes. Obviously you
can use any other Git hosting provider of your preference.
We always aim for consistency in our code base so you should follow basic coding rules as defined by
[PSR-1](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)
and [PSR-2](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)
and stick with the conventions used in Predis to name classes and interfaces. Indentation should be
done with 4 spaces and code should be wrapped at 100 columns (please try to stay within this limit
even if the above mentioned official coding guidelines set the soft limit to 120 columns).
Please follow these [commit guidelines](http://git-scm.com/book/ch5-2.html#Commit-Guidelines) when
committing your code to Git and always write a meaningful (not necessarily extended) description of
your changes before opening pull requests.
+30 -110
View File
@@ -1,10 +1,9 @@
# Some frequently asked questions about Predis #
________________________________________________
# Frequently asked questions about Predis #
### What is the point of Predis? ###
## What is the point of Predis? ##
The main point of Predis is about offering a highly customizable and extensible client for Redis,
that can be easily extended by developers while still being reasonabily fast. With Predis you can
that can be easily extended by developers while still being reasonably fast. With Predis you can
swap almost any class with your own custom implementation: you can have custom connection classes,
new distribution strategies for client-side sharding, or handlers to replace or add Redis commands.
All of this can be achieved without messing with the source code of the library and directly in your
@@ -13,12 +12,12 @@ a great asset since it allows developers to add new and still missing features o
the standard behaviour of the library without the need to break dependencies in production code (at
least to some degree).
### Does Predis support UNIX domain sockets and persistent connections? ###
## Does Predis support UNIX domain sockets and persistent connections? ##
Yes. Obviously persistent connections actually work only when using PHP configured as a persistent
process reused by the web server (see [PHP-FPM](http://php-fpm.org)).
### Does Predis support SSL-encrypted connections? ###
## Does Predis support SSL-encrypted connections? ##
Yes. Encrypted connections are mostly useful when connecting to Redis instances exposed by various
cloud hosting providers without the need to configure an SSL proxy, but you should also take into
@@ -26,16 +25,21 @@ account the general performances degradation especially during the connect() ope
handshake must be performed to secure the connection. Persistent SSL-encrypted connections may help
in that respect, but they are supported only when running on PHP >= 7.0.0.
### Does Predis support transparent (de)serialization of values? ###
## Does Predis support transparent (de)serialization of values? ##
No and it will not ever do that by default. The reason behind this decision is that serialization is
usually something that developers prefer to customize depending on their needs and can not be easily
generalized when using Redis because of the many possible access patterns for your data. This does
not mean that it is impossible to have such a feature since you can leverage the extensibility of
this library to define your own serialization-aware commands. You can find more details about how to
do that [on this issue](http://github.com/predis/predis/issues/29#issuecomment-1202624).
When using [Relay](https://github.com/cachewerk/relay) as the underlying client, several
serialization and compression algorithms are supported. This slightly increases CPU usage,
but significantly reduces bytes sent over the network and Redis memory usage.
### How can I force Predis to connect to Redis before sending any command? ###
Without Relay, Predis will not serialize data and will never do that by default. The reason
behind this decision is that serialization is usually something that developers prefer to
customize depending on their needs and can not be easily generalized when using Redis because
of the many possible access patterns for your data. This does not mean that it is impossible
to have such a feature since you can leverage the extensibility of this library to define
your own serialization-aware commands. You can find more details about how to do that
[on this issue](http://github.com/predis/predis/issues/29#issuecomment-1202624).
## How can I force Predis to connect to Redis before sending any command? ##
Explicitly connecting to Redis is usually not needed since the client initializes connections lazily
only when they are needed. Admittedly, this behavior can be inconvenient in certain scenarios when
@@ -55,7 +59,7 @@ try {
$client->info();
```
### How Predis abstracts Redis commands? ###
## How Predis abstracts Redis commands? ##
The approach used to implement Redis commands is quite simple: by default each command follows the
same signature as defined on the [Redis documentation](http://redis.io/commands) which makes things
@@ -75,103 +79,19 @@ $client->hmset('my:hash', ['field1'=>'value1', 'field2'=>'value2']); // single n
An exception to this rule is [`SORT`](http://redis.io/commands/sort) for which modifiers are passed
[using a named array](tests/Predis/Command/KeySortTest.php#L54-L75).
## When should I use Relay? ##
# Speaking about performances... #
_________________________________________________
If you care about performance, __always__. [Relay][relay] is free to use.
## When should I use PhpRedis? ###
### Predis is a pure-PHP implementation: it can not be fast enough! ###
Predis is fast enough when Redis is located on the same machine as PHP.
It really depends, but most of the times the answer is: _yes, it is fast enough_. I will give you a
couple of easy numbers with a simple test that uses a single client and is executed by PHP 5.5.6
against a local instance of Redis 2.8 that runs under Ubuntu 13.10 on a Intel Q6600:
[PhpRedis][phpredis] and [Relay][relay] perform significantly better when network I/O is involved,
due to its ability to compress data by ~75%. Fewer bytes and received sent over the network
[means faster operations][performance], and potentially cost savings when network traffic isn't
free (e.g. AWS ElastiCache Inter-AZ transfer costs).
```
21000 SET/sec using 12 bytes for both key and value.
21000 GET/sec while retrieving the very same values.
0.130 seconds to fetch 30000 keys using _KEYS *_.
```
How does it compare with [__phpredis__](http://github.com/nicolasff/phpredis), a nice C extension
providing an efficient client for Redis?
```
30100 SET/sec using 12 bytes for both key and value
29400 GET/sec while retrieving the very same values
0.035 seconds to fetch 30000 keys using "KEYS *"".
```
Wow __phpredis__ seems much faster! Well, we are comparing a C extension with a pure-PHP library so
lower numbers are quite expected but there is a fundamental flaw in them: is this really how you are
going to use Redis in your application? Are you really going to send thousands of commands using a
for-loop on each page request using a single client instance? If so... well I guess you are probably
doing something wrong. Also, if you need to `SET` or `GET` multiple keys you should definitely use
commands such as `MSET` and `MGET`. You can also use pipelining to get more performances when this
technique can be used.
There is one more thing: we have tested the overhead of Predis by connecting on a localhost instance
of Redis but how these numbers change when we hit the physical network by connecting to remote Redis
instances?
```
Using Predis:
3200 SET/sec using 12 bytes for both key and value
3200 GET/sec while retrieving the very same values
0.132 seconds to fetch 30000 keys using "KEYS *".
Using phpredis:
3500 SET/sec using 12 bytes for both key and value
3500 GET/sec while retrieving the very same values
0.045 seconds to fetch 30000 keys using "KEYS *".
```
There you go, you get almost the same average numbers and the reason is simple: network latency is a
real performance killer and you cannot do (almost) anything about that. As a disclaimer, remember
that we are measuring the overhead of client libraries implementations and the effects of network
round-trip times, so we are not really measuring how fast Redis is. Redis shines best with thousands
of concurrent clients doing requests! Also, actual performances should be measured according to how
your application will use Redis.
### I am convinced, but performances for multi-bulk responses are still worse ###
Fair enough, but there is an option available if you need even more speed and consists on installing
__[phpiredis](http://github.com/nrk/phpiredis)__ (note the additional _i_ in the name) and let the
client use it. __phpiredis__ is another C extension that wraps __hiredis__ (the official C client
library for Redis) with a thin layer exposing its features to PHP. You can then choose between two
different connection classes:
- `Predis\Connection\PhpiredisStreamConnection` (using native PHP streams).
- `Predis\Connection\PhpiredisSocketConnection` (requires `ext-socket`).
You will now get the benefits of a faster protocol serializer and parser just by adding a couple of
lines of code:
```php
$client = new Predis\Client('tcp://127.0.0.1', array(
'connections' => array(
'tcp' => 'Predis\Connection\PhpiredisStreamConnection',
'unix' => 'Predis\Connection\PhpiredisSocketConnection',
),
));
```
Dead simple. Nothing changes in the way you use the library in your application. So how fast is it
our basic benchmark script now? There are not much improvements for inline or short bulk responses
like the ones returned by `SET` and `GET`, but the speed for parsing multi-bulk responses is now on
par with phpredis:
```
Fatching 30000 keys with _KEYS *_ using Predis paired with phpiredis::
0.035 seconds from a local Redis instance
0.047 seconds from a remote Redis instance
```
### If I need an extension to get better performances, why not using phpredis? ###
Good question. Generically speaking if you need absolute uber-speed using Redis on the localhost and
you do not care about abstractions built around some Redis features such as MULTI / EXEC, or if you
do not need any kind of extensibility or guaranteed backwards compatibility with different versions
of Redis (Predis currently supports from 1.2 up to 2.8 and the current development version), then
using __phpredis__ makes absolutely sense. Otherwise, Predis is perfect for the job and by adding
__phpiredis__ you can get a nice speed bump almost for free.
[phpredis]: https://github.com/phpredis/phpredis
[relay]: [https://github.com/phpredis/phpredis](https://github.com/cachewerk/relay)
[performance]: https://akalongman.medium.com/phpredis-vs-predis-comparison-on-real-production-data-a819b48cbadb
+19 -19
View File
@@ -1,22 +1,22 @@
Copyright (c) 2009-2021 Daniele Alessandri
MIT License
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
Copyright (c) 2009-2020 Daniele Alessandri (original work)
Copyright (c) 2021-2024 Till Krüss (modified work)
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+20 -48
View File
@@ -1,19 +1,20 @@
# Predis #
[![Software license][ico-license]](LICENSE)
[![Latest stable][ico-version-stable]][link-packagist]
[![Latest development][ico-version-dev]][link-packagist]
[![Latest stable][ico-version-stable]][link-releases]
[![Latest development][ico-version-dev]][link-releases]
[![Monthly installs][ico-downloads-monthly]][link-downloads]
[![Build status][ico-build]][link-actions]
[![Coverage Status][ico-coverage]][link-coverage]
A flexible and feature-complete [Redis](http://redis.io) client for PHP 7.2 and newer.
A flexible and feature-complete [Redis](http://redis.io) / [Valkey](https://github.com/valkey-io/valkey) client for PHP 7.2 and newer.
More details about this project can be found on the [frequently asked questions](FAQ.md).
## Main features ##
- Support for Redis from __3.0__ to __7.0__.
- Support for Redis from __3.0__ to __7.4__.
- Support for clustering using client-side sharding and pluggable keyspace distributors.
- Support for [redis-cluster](http://redis.io/topics/cluster-tutorial) (Redis >= 3.0).
- Support for master-slave replication setups and [redis-sentinel](http://redis.io/topics/sentinel).
@@ -24,7 +25,6 @@ More details about this project can be found on the [frequently asked questions]
- Abstraction for `SCAN`, `SSCAN`, `ZSCAN` and `HSCAN` (Redis >= 2.8) based on PHP iterators.
- Connections are established lazily by the client upon the first command and can be persisted.
- Connections can be established via TCP/IP (also TLS/SSL-encrypted) or UNIX domain sockets.
- Support for [Webdis](http://webd.is) (requires both `ext-curl` and `ext-phpiredis`).
- Support for custom connection classes for providing different network or protocol backends.
- Flexible system for defining custom commands and override the default ones.
@@ -35,6 +35,10 @@ This library can be found on [Packagist](http://packagist.org/packages/predis/pr
management of projects dependencies using [Composer](http://packagist.org/about-composer).
Compressed archives of each release are [available on GitHub](https://github.com/predis/predis/releases).
```shell
composer require predis/predis
```
### Loading the library ###
@@ -392,31 +396,16 @@ $response = $client->lpushrand('random_values', $seed = mt_rand());
### Customizable connection backends ###
Predis can use different connection backends to connect to Redis. Two of them leverage a third party
extension such as [phpiredis](https://github.com/nrk/phpiredis) resulting in major performance gains
especially when dealing with big multibulk responses. While one is based on PHP streams, the other
is based on socket resources provided by `ext-socket`. Both support TCP/IP and UNIX domain sockets:
Predis can use different connection backends to connect to Redis. The builtin Relay integration
leverages the [Relay](https://github.com/cachewerk/relay) extension for PHP for major performance
gains, by caching a partial replica of the Redis dataset in PHP shared runtime memory.
```php
$client = new Predis\Client('tcp://127.0.0.1', [
'connections' => [
'tcp' => 'Predis\Connection\PhpiredisStreamConnection', // PHP stream resources
'unix' => 'Predis\Connection\PhpiredisSocketConnection', // ext-socket resources
],
'connections' => 'relay',
]);
```
The client can also be configured to rely on a [phpiredis](https://github.com/nrk/phpiredis)-backend
by specifying a descriptive string for the `connections` client option. Supported string values are:
- `phpiredis-stream` maps `tcp`, `redis` and `unix` to `Predis\Connection\PhpiredisStreamConnection`
- `phpiredis-socket` maps `tcp`, `redis` and `unix` to `Predis\Connection\PhpiredisSocketConnection`
- `phpiredis` is simply an alias of `phpiredis-stream`
```php
$client = new Predis\Client('tcp://127.0.0.1', ['connections' => 'phpiredis']);
```
Developers can create their own connection classes to support whole new network backends, extend
existing classes or provide completely different implementations. Connection classes must implement
`Predis\Connection\NodeConnectionInterface` or extend `Predis\Connection\AbstractConnection`:
@@ -443,9 +432,7 @@ implementation of the standard connection classes available in the `Predis\Conne
### Reporting bugs and contributing code ###
Contributions to Predis are highly appreciated either in the form of pull requests for new features,
bug fixes, or just bug reports. We only ask you to adhere to a [basic set of rules](CONTRIBUTING.md)
before submitting your changes or filing bugs on the issue tracker to make it easier for everyone to
stay consistent while working on the project.
bug fixes, or just bug reports. We only ask you to adhere to issue and pull request templates.
### Test suite ###
@@ -462,33 +449,18 @@ be disabled. See [the tests README](tests/README.md) for more details about test
Predis uses GitHub Actions for continuous integration and the history for past and current builds can be
found [on its actions page](https://github.com/predis/predis/actions).
## Other ##
### Project related links ###
- [Source code](https://github.com/predis/predis)
- [Wiki](https://github.com/predis/predis/wiki)
- [Issue tracker](https://github.com/predis/predis/issues)
### Author ###
- [Daniele Alessandri](mailto:suppakilla@gmail.com) ([twitter](http://twitter.com/JoL1hAHN))
- [Till Krüss](https://till.im) ([Twitter](http://twitter.com/tillkruss))
### License ###
The code for Predis is distributed under the terms of the MIT license (see [LICENSE](LICENSE)).
[ico-license]: https://img.shields.io/github/license/predis/predis.svg?style=flat-square
[ico-version-stable]: https://img.shields.io/packagist/v/predis/predis.svg?style=flat-square
[ico-version-dev]: https://img.shields.io/packagist/vpre/predis/predis.svg?style=flat-square
[ico-version-stable]: https://img.shields.io/github/v/tag/predis/predis?label=stable&style=flat-square
[ico-version-dev]: https://img.shields.io/github/v/tag/predis/predis?include_prereleases&label=pre-release&style=flat-square
[ico-downloads-monthly]: https://img.shields.io/packagist/dm/predis/predis.svg?style=flat-square
[ico-build]: https://img.shields.io/github/workflow/status/predis/predis/Tests/main?style=flat-square
[ico-build]: https://img.shields.io/github/actions/workflow/status/predis/predis/tests.yml?branch=main&style=flat-square
[ico-coverage]: https://img.shields.io/coverallsCoverage/github/predis/predis?style=flat-square
[link-packagist]: https://packagist.org/packages/predis/predis
[link-releases]: https://github.com/predis/predis/releases
[link-actions]: https://github.com/predis/predis/actions
[link-downloads]: https://packagist.org/packages/predis/predis/stats
[link-coverage]: https://coveralls.io/github/predis/predis
+1 -1
View File
@@ -1 +1 @@
2.0.0
2.4.0-RC1
-2
View File
@@ -3,8 +3,6 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+1 -5
View File
@@ -4,8 +4,6 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
@@ -119,7 +117,7 @@ class CommandTestCaseGenerator
protected function getTestRealm()
{
if (empty($this->options['realm'])) {
throw new RuntimeException('Invalid value for realm has been sepcified (empty).');
throw new RuntimeException('Invalid value for realm has been specified (empty).');
}
return $this->options['realm'];
@@ -170,8 +168,6 @@ class CommandTestCaseGenerator
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
+17 -15
View File
@@ -1,7 +1,7 @@
{
"name": "predis/predis",
"type": "library",
"description": "A flexible and feature-complete Redis client for PHP.",
"description": "A flexible and feature-complete Redis/Valkey client for PHP.",
"keywords": ["nosql", "redis", "predis"],
"homepage": "http://github.com/predis/predis",
"license": "MIT",
@@ -9,12 +9,6 @@
"issues": "https://github.com/predis/predis/issues"
},
"authors": [
{
"name": "Daniele Alessandri",
"email": "suppakilla@gmail.com",
"homepage": "http://clorophilla.net",
"role": "Creator & Maintainer"
},
{
"name": "Till Krüss",
"homepage": "https://till.im",
@@ -31,20 +25,28 @@
"php": "^7.2 || ^8.0"
},
"require-dev": {
"phpunit/phpunit": "^8.0 || ~9.4.4"
"friendsofphp/php-cs-fixer": "^3.3",
"phpstan/phpstan": "^1.9",
"phpunit/phpunit": "^8.0 || ^9.4",
"phpunit/phpcov": "^6.0 || ^8.0"
},
"suggest": {
"ext-phpiredis": "Allows faster serialization and deserialization of the Redis protocol",
"ext-curl": "Allows access to Webdis when paired with phpiredis"
"ext-relay": "Faster connection with in-memory caching (>=0.6.2)"
},
"scripts": {
"phpstan": "phpstan analyse",
"style": "php-cs-fixer fix --diff --dry-run",
"style:fix": "php-cs-fixer fix"
},
"autoload": {
"psr-4": {
"Predis\\": "src/"
}
},
"extra": {
"branch-alias": {
"dev-main": "2.0-dev"
}
}
"config": {
"sort-packages": true,
"preferred-install": "dist"
},
"minimum-stability": "dev",
"prefer-stable": true
}
@@ -0,0 +1,28 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../../shared.php';
// Example of JSON.DEBUG command usage:
// 1. Set JSON object
$client = new Client();
$client->jsonset('key', '$', '{"key1":"value1","key2":"value2"}');
// 2. Dump information about json memory usage in bytes
$response = $client->jsondebug->memory('key', '$');
echo 'Response:' . "\n";
print_r($response);
+52
View File
@@ -0,0 +1,52 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\SchemaFields\AbstractField;
use Predis\Command\Argument\Search\SchemaFields\NumericField;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.AGGREGATE command usage:
// 1. Create index
$client = new Client();
$ftCreateArguments = (new CreateArguments())->prefix(['user:']);
$schema = [
new TextField('name'),
new TextField('country'),
new NumericField('dob', '', AbstractField::SORTABLE),
];
$client->ftcreate('idx', $schema, $ftCreateArguments);
// 2. Add documents
$client->hset('user:0', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
$client->hset('user:1', 'name', 'Vlad', 'country', 'Israel', 'dob', 782265600);
$client->hset('user:2', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
// 3. Execute aggregation query
$ftAggregateArguments = (new AggregateArguments())
->apply('year(@dob)', 'birth')
->groupBy('@country', '@birth')
->reduce('COUNT', true, 'country_birth_Vlad_count')
->sortBy(0, '@birth', 'DESC');
$response = $client->ftaggregate('idx', '@name: "Vlad"', $ftAggregateArguments);
// Response grouped by user country and birth year, with users count in each group, sorted by birth year from DESC.
echo 'Response:' . "\n";
print_r($response);
+41
View File
@@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.ALTER command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_alter', $schema);
echo 'Default index attributes:' . "\n";
$defaultAttributes = $client->ftinfo('index_alter');
print_r($defaultAttributes[7]);
// 2. Add additional attribute to existing index
$schema = [
new TextField('new_field_name'),
];
$client->ftalter('index_alter', $schema);
echo 'Updated index attributes:' . "\n";
$updatedAttributes = $client->ftinfo('index_alter');
print_r($updatedAttributes[7]);
@@ -0,0 +1,25 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../../shared.php';
// Example of FT.CONFIG HELP command usage:
// 1. Dump helpful information about FT.CONFIG MAXEXPANSIONS option
$client = new Client();
echo 'Response:' . "\n";
print_r(
$client->ftconfig->help('MAXEXPANSIONS')
);
@@ -0,0 +1,29 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../../shared.php';
// Example of FT.CONFIG SET command usage:
// 1. Change default timeout setting
$client = new Client();
echo 'Response:' . "\n";
print_r(
$client->ftconfig->set('TIMEOUT', 42)
);
print_r(
$client->ftconfig->get('TIMEOUT')
);
@@ -0,0 +1,54 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\SchemaFields\AbstractField;
use Predis\Command\Argument\Search\SchemaFields\NumericField;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.CURSOR DEL command usage
// 1. Create index
$client = new Client();
$ftCreateArguments = (new CreateArguments())->prefix(['user:']);
$schema = [
new TextField('name'),
new TextField('country'),
new NumericField('dob', '', AbstractField::SORTABLE),
];
$client->ftcreate('index_cursor_del', $schema, $ftCreateArguments);
// 2. Add documents
$client->hset('user:0', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
$client->hset('user:1', 'name', 'Vlad', 'country', 'Israel', 'dob', 782265600);
$client->hset('user:2', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
// 3. Execute aggregation query
$ftAggregateArguments = (new AggregateArguments())
->apply('year(@dob)', 'birth')
->groupBy('@country', '@birth')
->reduce('COUNT', true, 'country_birth_Vlad_count')
->sortBy(0, '@birth', 'DESC')
->withCursor(1);
[$_, $cursor] = $client->ftaggregate('index_cursor_del', '@name: "Vlad"', $ftAggregateArguments);
// 4. Explicitly remove returned cursor
$client->ftcursor->del('index_cursor_del', $cursor);
echo "Cursor with cursorId - {$cursor} was removed";
@@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\SchemaFields\AbstractField;
use Predis\Command\Argument\Search\SchemaFields\NumericField;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.CURSOR READ command usage
// 1. Create index
$client = new Client();
$ftCreateArguments = (new CreateArguments())->prefix(['user:']);
$schema = [
new TextField('name'),
new TextField('country'),
new NumericField('dob', '', AbstractField::SORTABLE),
];
$client->ftcreate('index_cursor_read', $schema, $ftCreateArguments);
// 2. Add documents
$client->hset('user:0', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
$client->hset('user:1', 'name', 'Vlad', 'country', 'Israel', 'dob', 782265600);
$client->hset('user:2', 'name', 'Vlad', 'country', 'Ukraine', 'dob', 813801600);
// 3. Execute aggregation query
$ftAggregateArguments = (new AggregateArguments())
->apply('year(@dob)', 'birth')
->groupBy('@country', '@birth')
->reduce('COUNT', true, 'country_birth_Vlad_count')
->sortBy(0, '@birth', 'DESC')
->withCursor(1);
[$response, $cursor] = $client->ftaggregate('index_cursor_read', '@name: "Vlad"', $ftAggregateArguments);
// 4. Processing response in loop until cursorId exists
$actualResponse = [];
$cursors = [];
while ($cursor) {
$actualResponse[] = $response[1];
$cursors[] = $cursor;
[$response, $cursor] = $client->ftcursor->read('index_cursor_read', $cursor);
}
echo "Response: \n";
print_r($actualResponse);
+32
View File
@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.EXPLAIN command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_explain', $schema);
// 2. Run query explanations
$response = $client->ftexplain('index_explain', '(foo bar)|(hello world) @date:[100 200]|@date:[500 +inf]');
echo 'Response:' . "\n";
print_r($response);
+38
View File
@@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\ProfileArguments;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.PROFILE command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_profile', $schema);
// 2. Create FT.PROFILE command arguments
$arguments = (new ProfileArguments())
->search()
->query('query');
// 3. Run profile query
$response = $client->ftprofile('index_profile', $arguments);
echo 'Response:' . "\n";
print_r($response);
@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SchemaFields\TextField;
use Predis\Command\Argument\Search\SpellcheckArguments;
require __DIR__ . '/../../shared.php';
// Example of FT.SPELLCHECK command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_spellcheck', $schema);
// 2. Add dictionary with terms
$client->ftdictadd('dict', 'hello', 'help');
// 3. Perform spelling correction query
$response = $client->ftspellcheck(
'index_spellcheck',
'held',
(new SpellcheckArguments())->distance(2)->terms('dict')
);
echo 'Response:' . "\n";
print_r($response);
@@ -0,0 +1,39 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SugAddArguments;
use Predis\Command\Argument\Search\SugGetArguments;
require __DIR__ . '/../../shared.php';
// Example of FT.SUGADD, FT.SUGGET, FT.SUGDEL, FT.SUGLEN commands usage:
// 1. Add suggestion to key with payload
$client = new Client();
$client->ftsugadd('key', 'hello', 2, (new SugAddArguments())->payload('payload'));
echo 'Suggestions dictionary length: ' . $client->ftsuglen('key') . "\n";
// 2. Perform fuzzy search by prefix to get previous suggestion with payload
$response = $client->ftsugget('key', 'hellp', (new SugGetArguments())->fuzzy()->withPayloads());
echo 'Suggestion for "hellp" prefix:' . "\n";
print_r($response);
// 3. Removes previous suggestion from key
$client->ftsugdel('key', 'hello');
$response = $client->ftsugget('key', 'hello');
echo 'Suggestions, after removing "hello" suggestion:' . "\n";
print_r($response);
+35
View File
@@ -0,0 +1,35 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.SYNDUMP command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_syndump', $schema);
// 2. Add synonyms group with terms
$client->ftsynupdate('index_syndump', 'synonym1', null, 'term1', 'term2');
// 3. Dump terms with synonyms
$response = $client->ftsyndump('index_syndump');
echo 'Response:' . "\n";
print_r($response);
+32
View File
@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\SchemaFields\TextField;
require __DIR__ . '/../../shared.php';
// Example of FT.SYNUPDATE command usage:
// 1. Create index
$client = new Client();
$schema = [
new TextField('text_field'),
];
$client->ftcreate('index_synupdate', $schema);
// 2. Add synonyms into synonym group
$response = $client->ftsynupdate('index_synupdate', 'synonym1', null, 'term1', 'term2');
echo 'Response:' . "\n";
print_r($response);
+37
View File
@@ -0,0 +1,37 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\SchemaFields\TagField;
require __DIR__ . '/../../shared.php';
// Example of FT.TAGVALS command usage:
// 1. Create index
$client = new Client();
$schema = [
new TagField('tag_field'),
];
$client->ftcreate('index_tagvals', $schema, (new CreateArguments())->prefix(['prefix:']));
// 2. Add indexed tags
$client->hset('prefix:1', 'tag_field', 'Hello, World');
$client->hset('prefix:2', 'tag_field', 'Hey, World');
// 3. Unique tags value query
$response = $client->fttagvals('index_tagvals', 'tag_field');
echo 'Response:' . "\n";
print_r($response);
+38
View File
@@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\AddArguments;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.ADD command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Add sample into newly created time series
$addArguments = (new AddArguments())
->retentionMsecs(31536000000);
$response = $client->tsadd('temperature:2:32', 123123123123, 27, $addArguments);
echo "Timeseries was added with timestamp: {$response}";
+41
View File
@@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\AlterArguments;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.ALTER command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$response = $client->tscreate('temperature:2:32', $arguments);
echo "Time series creation status: {$response}\n";
// 2. Update Duplicate policy for time series above
$arguments = (new AlterArguments())
->duplicatePolicy(CommonArguments::POLICY_FIRST);
$response = $client->tsalter('temperature:2:32', $arguments);
$output = ($response == 'OK') ? 'Duplicate policy was successfully updated' : $response;
echo $output;
@@ -0,0 +1,31 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.CREATE command usage:
// Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$response = $client->tscreate('temperature:2:32', $arguments);
echo "Time series creation status: {$response}";
@@ -0,0 +1,33 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.CREATERULE command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->labels('type', 'temp', 'location', 'TLV');
$createResponse = $client->tscreate('temp:TLV', $arguments);
echo "Original time series creation status: {$createResponse}\n";
$createResponse = $client->tscreate('dailyAvgTemp:TLV', $arguments);
echo "Compacted time series creation status: {$createResponse}\n";
$createRuleResponse = $client->tscreaterule('temp:TLV', 'dailyAvgTemp:TLV', 'avg', 1000);
echo "Compacted rule for compacted time series creation status: {$createRuleResponse}\n";
@@ -0,0 +1,45 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\AddArguments;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\DecrByArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.DECRBY command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Add sample into newly created time series
$addArguments = (new AddArguments())
->retentionMsecs(31536000000);
$response = $client->tsadd('temperature:2:32', 123123123123, 27, $addArguments);
echo "Timeseries was added with timestamp: {$response}\n";
// 3. Increasing value and timestamp
$client->tsdecrby('temperature:2:32', 1, (new DecrByArguments())->timestamp(123123123124));
$response = $client->tsget('temperature:2:32');
echo "Decreased value to - {$response[1]} and timestamp to {$response[0]}";
+47
View File
@@ -0,0 +1,47 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.GET command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Add samples into time series
$client->tsadd('temperature:2:32', 123123123123, 27);
$client->tsadd('temperature:2:32', 123123123124, 28);
$client->tsadd('temperature:2:32', 123123123125, 29);
$response = $client->tsget('temperature:2:32');
echo "Sample with highest timestamp - {$response[0]} and value {$response[1]}\n";
// 3. Removes 2 samples with the highest timestamps
$response = $client->tsdel('temperature:2:32', 123123123124, 123123123125);
echo "Removed {$response} samples from timeseries.\n";
// 3. Retrieve a timestamp with the highest timestamp
$response = $client->tsget('temperature:2:32');
echo "New sample with highest timestamp - {$response[0]} and value {$response[1]}";
@@ -0,0 +1,37 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.CREATERULE command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->labels('type', 'temp', 'location', 'TLV');
$createResponse = $client->tscreate('temp:TLV', $arguments);
echo "Original time series creation status: {$createResponse}\n";
$createResponse = $client->tscreate('dailyAvgTemp:TLV', $arguments);
echo "Compacted time series creation status: {$createResponse}\n";
$createRuleResponse = $client->tscreaterule('temp:TLV', 'dailyAvgTemp:TLV', 'avg', 1000);
echo "Compacted rule for compacted time series creation status: {$createRuleResponse}\n";
// 2. Remove compaction rule
$deleteRuleResponse = $client->tsdeleterule('temp:TLV', 'dailyAvgTemp:TLV');
echo "Compacted rule for compacted time series deletion status: {$deleteRuleResponse}\n";
+38
View File
@@ -0,0 +1,38 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.GET command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Add samples into time series
$client->tsadd('temperature:2:32', 123123123123, 27);
$client->tsadd('temperature:2:32', 123123123124, 28);
$client->tsadd('temperature:2:32', 123123123125, 29);
// 3. Retrieve a timestamp with highest timestamp
$response = $client->tsget('temperature:2:32');
echo "Sample with highest timestamp - {$response[0]} and value - {$response[1]}";
@@ -0,0 +1,45 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\AddArguments;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\IncrByArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.INCRBY command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Add sample into newly created time series
$addArguments = (new AddArguments())
->retentionMsecs(31536000000);
$response = $client->tsadd('temperature:2:32', 123123123123, 27, $addArguments);
echo "Timeseries was added with timestamp: {$response}\n";
// 3. Increasing value and timestamp
$client->tsincrby('temperature:2:32', 1, (new IncrByArguments())->timestamp(123123123124));
$response = $client->tsget('temperature:2:32');
echo "Increased value to - {$response[1]} and timestamp to {$response[0]}";
+32
View File
@@ -0,0 +1,32 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.CREATE command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
// 2. Show info about given time series
print_r($client->tsinfo('temperature:2:32'));
+36
View File
@@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.MADD command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
$client->tscreate('temperature:2:33', $arguments);
// 2. Add samples into few time series
$response = $client->tsmadd('temperature:2:32', 123123123123, 27, 'temperature:2:33', 123123123124, 28);
$stringResponse = implode(', ', $response);
echo "Samples was added to time series - timestamps: {$stringResponse}";
+41
View File
@@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CommonArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\MGetArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.MGET command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->retentionMsecs(60000)
->duplicatePolicy(CommonArguments::POLICY_MAX)
->labels('type', 'temp', 'sensor_id', 2, 'area_id', 32);
$client->tscreate('temperature:2:32', $arguments);
$client->tscreate('temperature:2:33', $arguments);
// 2. Add samples into time series
$client->tsadd('temperature:2:32', 123123123123, 27);
$client->tsadd('temperature:2:33', 123123123124, 27);
// 3. Get sample from multiple time series matching given filter expression, with selected labels only
$response = $client->tsmget((new MGetArguments())->selectedLabels('type'), 'type=temp');
echo "Sample from time series, with label = 'type':\n";
print_r($response);
@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\MRangeArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.MRANGE command usage:
// 1. Create time series
$client = new Client();
$response = $client->tscreate('stock:A', (new CreateArguments())->labels('type', 'stock', 'name', 'A'));
echo "Time series A creation status: {$response}\n";
$response = $client->tscreate('stock:B', (new CreateArguments())->labels('type', 'stock', 'name', 'B'));
echo "Time series B creation status: {$response}\n";
// 2. Add samples into both time series
$response = $client->tsmadd('stock:A', 1000, 100, 'stock:A', 1010, 110, 'stock:A', 1020, 120);
$stringResponse = implode(', ', $response);
echo "Added samples into time series A with following timestamps: {$stringResponse}\n";
$response = $client->tsmadd('stock:B', 1000, 120, 'stock:B', 1010, 110, 'stock:B', 1020, 100);
$stringResponse = implode(', ', $response);
echo "Added samples into time series B with following timestamps: {$stringResponse}\n";
// 3. Query range across both time series filtered by "type" and grouped by max type
$mrangeArguments = (new MRangeArguments())
->withLabels()
->filter('type=stock')
->groupBy('type', 'max');
$response = $client->tsmrange('-', '+', $mrangeArguments);
echo "Response:\n";
print_r($response);
@@ -0,0 +1,48 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\MRangeArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.MREVRANGE command usage:
// 1. Create time series
$client = new Client();
$response = $client->tscreate('stock:A', (new CreateArguments())->labels('type', 'stock', 'name', 'A'));
echo "Time series A creation status: {$response}\n";
$response = $client->tscreate('stock:B', (new CreateArguments())->labels('type', 'stock', 'name', 'B'));
echo "Time series B creation status: {$response}\n";
// 2. Add samples into both time series
$response = $client->tsmadd('stock:A', 1000, 100, 'stock:A', 1010, 110, 'stock:A', 1020, 120);
$stringResponse = implode(', ', $response);
echo "Added samples into time series A with following timestamps: {$stringResponse}\n";
$response = $client->tsmadd('stock:B', 1000, 120, 'stock:B', 1010, 110, 'stock:B', 1020, 100);
$stringResponse = implode(', ', $response);
echo "Added samples into time series B with following timestamps: {$stringResponse}\n";
// 3. Query range across both time series filtered by "type" and grouped by max type
$mrangeArguments = (new MRangeArguments())
->withLabels()
->filter('type=stock')
->groupBy('type', 'max');
$response = $client->tsmrevrange('-', '+', $mrangeArguments);
echo "Response:\n";
print_r($response);
@@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.QUERYINDEX command usage:
// 1. Create time series
$client = new Client();
$arguments = (new CreateArguments())
->labels('type', 'temp', 'location', 'TLV');
$createResponse = $client->tscreate('temp:TLV', $arguments);
echo "Time series with location TLV creation status: {$createResponse}\n";
$anotherArguments = (new CreateArguments())
->labels('type', 'temp', 'location', 'JER');
$createResponse = $client->tscreate('temp:JER', $anotherArguments);
echo "Time series with location JER creation status: {$createResponse}\n";
echo "Returns all keys with location=TLV:\n";
print_r($client->tsqueryindex('location=TLV'));
+40
View File
@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\RangeArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.RANGE command usage:
// 1. Create time series
$client = new Client();
$createArguments = (new CreateArguments())->labels('type', 'temp', 'location', 'TLV');
$createResponse = $client->tscreate('temp:TLV', $createArguments);
echo "Time series creation status: {$createResponse}\n";
// 2. Add samples into time series
$maddResponse = $client->tsmadd('temp:TLV', 1000, 30, 'temp:TLV', 1010, 35, 'temp:TLV', 1020, 9999, 'temp:TLV', 1030, 40);
$stringResponse = implode(', ', $maddResponse);
echo "Samples was added with following timestamps: {$stringResponse}\n";
// 3. Query samples by values in the given range
$rangeArguments = (new RangeArguments())->filterByValue(-100, 100);
$rangeResponse = $client->tsrange('temp:TLV', '-', '+', $rangeArguments);
echo "Samples with temperature in range -100 to 100 degrees:\n";
print_r($rangeResponse);
@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
use Predis\Command\Argument\TimeSeries\CreateArguments;
use Predis\Command\Argument\TimeSeries\RangeArguments;
require __DIR__ . '/../../shared.php';
// Example of TS.REVRANGE command usage:
// 1. Create time series
$client = new Client();
$createArguments = (new CreateArguments())->labels('type', 'temp', 'location', 'TLV');
$createResponse = $client->tscreate('temp:TLV', $createArguments);
echo "Time series creation status: {$createResponse}\n";
// 2. Add samples into time series
$maddResponse = $client->tsmadd('temp:TLV', 1000, 30, 'temp:TLV', 1010, 35, 'temp:TLV', 1020, 9999, 'temp:TLV', 1030, 40);
$stringResponse = implode(', ', $maddResponse);
echo "Samples was added with following timestamps: {$stringResponse}\n";
// 3. Query samples by values in the given range
$rangeArguments = (new RangeArguments())->filterByValue(-100, 100);
$rangeResponse = $client->tsrevrange('temp:TLV', '-', '+', $rangeArguments);
echo "Samples with temperature in range -100 to 100 degrees in reverse order:\n";
print_r($rangeResponse);
+36
View File
@@ -0,0 +1,36 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../shared.php';
// Example of ACL DRYRUN command usage:
// 1. Set user with permissions to call only 'SET' command.
$client = new Client($single_server);
$response = $client->acl->setUser('Test_dry', '+SET', '~*');
$created = ($response == 'OK') ? 'Yes' : 'No';
echo "User with username 'Test' was created: {$created}. Permissions only to use SET command\n";
// 2. Dry run 'SET' command under 'Test_dry' user
$response = $client->acl->dryRun('Test_dry', 'SET', 'foo', 'bar');
echo 'Dry run "SET" command.' . "\n";
echo 'Response: ' . $response . "\n";
// 3. Dry run 'GET' command under 'Test_dry' user
$response = $client->acl->dryRun('Test_dry', 'GET', 'foo');
echo 'Dry run "GET" command.' . "\n";
echo 'Response: ' . $response;
+28
View File
@@ -0,0 +1,28 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../shared.php';
// Example of ACL GETUSER command usage:
// 1. Set user
$client = new Client($single_server);
$response = $client->acl->setUser('Test');
// 2. Retrieve user rules:
echo 'Rules: ' . "\n";
print_r(
$client->acl->getUser('Test')
);
+24
View File
@@ -0,0 +1,24 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../shared.php';
// Example of ACL SETUSER command usage:
// 1. Set user
$client = new Client($single_server);
$response = $client->acl->setUser('Test');
$created = ($response == 'OK') ? 'Yes' : 'No';
echo "User with username 'Test' was created: {$created}";
+43
View File
@@ -0,0 +1,43 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../shared.php';
// Example of FCALL_RO command usage:
// 1. Set key-value pair
$client = new Client($single_server);
$client->set('foo', 'bar');
echo "Set key 'foo' with value 'bar'\n";
// 2. Load redis function with 'no-writes' flag
$client->function->load(
"#!lua name=mylib
redis.register_function{
function_name='myfunc',
callback=function(keys, args) return redis.call('GET', keys[1]) end,
flags={'no-writes'}
}"
);
echo 'Loaded custom function that perform GET command against provided key.' . "\n";
// 3. Call function above with given key
$response = $client->fcall_ro('myfunc', ['foo']);
echo "Function returned value against provided key 'foo' is '{$response}'";
// 4. Delete test library
$client->function->delete('mylib');
+41
View File
@@ -0,0 +1,41 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use Predis\Client;
require __DIR__ . '/../shared.php';
// Example of WAITAOF command usage:
// 1. Enable appendonly mode if it's not (command works only in appendonly mode)
$client = new Client($single_server);
$info = $client->info();
$enabled = false;
if ($info['Persistence']['aof_enabled'] === '0') {
$client->config('set', 'appendonly', 'yes');
$enabled = true;
}
// 2. Set key value pair
$response = $client->set('foo', 'bar');
echo "Key-value pair set status: {$response}\n";
// 3. Run WAITAOF command to make sure that all previous writes was fsynced
$response = $client->waitaof(1, 0, 0);
echo "Quantity of local instances that was fsynced - {$response[0]}, quantity of replicas - {$response[1]}";
// 4. Disable appendonly mode if it was enabled during script execution
if ($enabled) {
$client->config('set', 'appendonly', 'no');
}
+7 -6
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Developers can implement Predis\Distribution\DistributorInterface to create
// their own distributors used by the client to distribute keys among a cluster
@@ -27,7 +28,7 @@ class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
public function __construct()
{
$this->nodes = array();
$this->nodes = [];
$this->nodesCount = 0;
}
@@ -53,7 +54,7 @@ class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
public function getBySlot($slot)
{
return isset($this->nodes[$slot]) ? $this->nodes[$slot] : null;
return $this->nodes[$slot] ?? null;
}
public function getByHash($hash)
@@ -87,7 +88,7 @@ class NaiveDistributor implements DistributorInterface, HashGeneratorInterface
}
}
$options = array(
$options = [
'cluster' => function () {
$distributor = new NaiveDistributor();
$strategy = new PredisStrategy($distributor);
@@ -95,7 +96,7 @@ $options = array(
return $cluster;
},
);
];
$client = new Predis\Client($multiple_servers, $options);
+17 -16
View File
@@ -3,17 +3,18 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This is an example of how you can easily extend an existing connection class
// and trace the execution of commands for debugging purposes. This can be quite
// useful as a starting poing to understand how your application interacts with
// useful as a starting point to understand how your application interacts with
// Redis.
use Predis\Command\CommandInterface;
@@ -22,7 +23,7 @@ use Predis\Connection\StreamConnection;
class SimpleDebuggableConnection extends StreamConnection
{
private $tstart = 0;
private $debugBuffer = array();
private $debugBuffer = [];
public function connect()
{
@@ -65,11 +66,11 @@ class SimpleDebuggableConnection extends StreamConnection
}
}
$options = array(
'connections' => array(
$options = [
'connections' => [
'tcp' => 'SimpleDebuggableConnection',
),
);
],
];
$client = new Predis\Client($single_server, $options);
$client->set('foo', 'bar');
@@ -80,13 +81,13 @@ var_export($client->getConnection()->getDebugBuffer());
/* OUTPUT:
array (
0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
0 => 'SELECT 15 -> 127.0.0.1:6379 [0.0008s]',
1 => 'SELECT 15 <- 127.0.0.1:6379 [0.001s]',
2 => 'SET foo -> 127.0.0.1:6379 [0.001s]',
3 => 'SET foo <- 127.0.0.1:6379 [0.0011s]',
4 => 'GET foo -> 127.0.0.1:6379 [0.0013s]',
5 => 'GET foo <- 127.0.0.1:6379 [0.0015s]',
6 => 'INFO -> 127.0.0.1:6379 [0.0019s]',
7 => 'INFO <- 127.0.0.1:6379 [0.0022s]',
)
*/
+6 -5
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This is a basic example on how to use the Predis\DispatcherLoop class.
//
@@ -23,7 +24,7 @@ require __DIR__.'/shared.php';
// PUBLISH control terminate_dispatcher
// Create a client and disable r/w timeout on the socket
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
$client = new Predis\Client($single_server + ['read_write_timeout' => 0]);
// Return an initialized PubSub consumer instance from the client.
$pubsub = $client->pubSubLoop();
@@ -38,7 +39,7 @@ class EventsListener implements Countable
public function __construct()
{
$this->events = array();
$this->events = [];
}
public function count()
@@ -58,7 +59,7 @@ class EventsListener implements Countable
}
// Attach our callable class to the dispatcher.
$dispatcher->attachCallback('events', ($events = new EventsListener()));
$dispatcher->attachCallback('events', $events = new EventsListener());
// Attach a function to control the dispatcher loop termination with a message.
$dispatcher->attachCallback('control', function ($payload, $dispatcher) {
+23 -17
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
$client = new Predis\Client($single_server);
@@ -17,41 +18,46 @@ $client = new Predis\Client($single_server);
$client->set('library', 'predis');
$response = $client->get('library');
var_export($response); echo PHP_EOL;
var_export($response);
echo PHP_EOL;
/* OUTPUT: 'predis' */
// Redis has the MSET and MGET commands to set or get multiple keys in one go,
// cases like this Predis accepts arguments for variadic commands both as a list
// of arguments or an array containing all of the keys and/or values.
$mkv = array(
$mkv = [
'uid:0001' => '1st user',
'uid:0002' => '2nd user',
'uid:0003' => '3rd user',
);
];
$client->mset($mkv);
$response = $client->mget(array_keys($mkv));
var_export($response); echo PHP_EOL;
var_export($response);
echo PHP_EOL;
/* OUTPUT:
array (
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
) */
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
)
*/
// Predis can also send "raw" commands to Redis. The difference between sending
// commands to Redis the usual way and the "raw" way is that in the latter case
// their arguments are not filtered nor responses coming from Redis are parsed.
$response = $client->executeRaw(array(
$response = $client->executeRaw([
'MGET', 'uid:0001', 'uid:0002', 'uid:0003',
));
]);
var_export($response); echo PHP_EOL;
var_export($response);
echo PHP_EOL;
/* OUTPUT:
array (
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
) */
0 => '1st user',
1 => '2nd user',
2 => '3rd user',
)
*/
+9 -8
View File
@@ -3,34 +3,35 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Predis can prefix keys found in commands arguments before sending commands to
// Redis, even for complex commands such as SORT, ZUNIONSTORE and ZINTERSTORE.
// Prefixing keys can be useful to create user-level namespaces for you keyspace
// thus reducing the need for separate logical databases in certain scenarios.
$client = new Predis\Client($single_server, array('prefix' => 'nrk:'));
$client = new Predis\Client($single_server, ['prefix' => 'nrk:']);
$client->mset(array('foo' => 'bar', 'lol' => 'wut'));
$client->mset(['foo' => 'bar', 'lol' => 'wut']);
var_export($client->mget('foo', 'lol'));
/*
array (
0 => 'bar',
1 => 'wut',
0 => 'bar',
1 => 'wut',
)
*/
var_export($client->keys('*'));
/*
array (
0 => 'nrk:foo',
1 => 'nrk:lol',
0 => 'nrk:foo',
1 => 'nrk:lol',
)
*/
+15 -14
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This example will not work with versions of Redis < 2.6.
//
@@ -36,11 +37,11 @@ local cmd, insert = redis.call, table.insert
local increment, results = ARGV[1], { }
for idx, key in ipairs(KEYS) do
if cmd('exists', key) == 1 then
insert(results, idx, cmd('incrby', key, increment))
else
insert(results, idx, false)
end
if cmd('exists', key) == 1 then
insert(results, idx, cmd('incrby', key, increment))
else
insert(results, idx, false)
end
end
return results
@@ -48,11 +49,11 @@ LUA;
}
}
$client = new Predis\Client($single_server, array(
'commands' => array(
$client = new Predis\Client($single_server, [
'commands' => [
'increxby' => 'IncrementExistingKeysBy',
),
));
],
]);
$client->mset('foo', 10, 'foobar', 100);
@@ -60,8 +61,8 @@ var_export($client->increxby('foo', 'foofoo', 'foobar', 50));
/*
array (
0 => 60,
1 => NULL,
2 => 150,
0 => 60,
1 => NULL,
2 => 150,
)
*/
+4 -3
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This is a basic example on how to use the Predis\Monitor\Consumer class. You
// can use redis-cli to send commands to the same Redis instance your client is
@@ -17,7 +18,7 @@ require __DIR__.'/shared.php';
// exit the monitor loop and terminate this script in a graceful way.
// Create a client and disable r/w timeout on the socket.
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
$client = new Predis\Client($single_server + ['read_write_timeout' => 0]);
// Use only one instance of DateTime, we will update the timestamp later.
$timestamp = new DateTime();
+14 -13
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// When you have a whole set of consecutive commands to send to a redis server,
// you can use a pipeline to dramatically improve performances. Pipelines can
@@ -30,16 +31,16 @@ var_export($responses);
/* OUTPUT:
array (
0 => Predis\Response\Status::__set_state(array(
'payload' => 'OK',
)),
1 => 10,
2 => 40,
3 => true,
4 => '40',
5 => array (
0 => NULL,
1 => '40',
),
0 => Predis\Response\Status::__set_state(array(
'payload' => 'OK',
)),
1 => 10,
2 => 40,
3 => true,
4 => '40',
5 => array (
0 => NULL,
1 => '40',
),
)
*/
+8 -7
View File
@@ -3,19 +3,20 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Starting from Redis 2.0 clients can subscribe and listen for events published
// on certain channels using a Publish/Subscribe (PUB/SUB) approach.
// Create a client and disable r/w timeout on the socket
$client = new Predis\Client($single_server + array('read_write_timeout' => 0));
$client = new Predis\Client($single_server + ['read_write_timeout' => 0]);
// Initialize a new pubsub consumer.
$pubsub = $client->pubSubLoop();
@@ -23,10 +24,10 @@ $pubsub = $client->pubSubLoop();
// Subscribe to your channels
$pubsub->subscribe('control_channel', 'notifications');
// Start processing the pubsup messages. Open a terminal and use redis-cli
// Start processing the pubsub messages. Open a terminal and use redis-cli
// to push messages to the channels. Examples:
// ./redis-cli PUBLISH notifications "this is a test"
// ./redis-cli PUBLISH control_channel quit_loop
// redis-cli PUBLISH notifications "this is a test"
// redis-cli PUBLISH control_channel quit_loop
foreach ($pubsub as $message) {
switch ($message->kind) {
case 'subscribe':
@@ -43,7 +44,7 @@ foreach ($pubsub as $message) {
}
} else {
echo "Received the following message from {$message->channel}:",
PHP_EOL, " {$message->payload}", PHP_EOL, PHP_EOL;
PHP_EOL, " {$message->payload}", PHP_EOL, PHP_EOL;
}
break;
}
+21 -20
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
use Predis\Collection\Iterator;
@@ -47,9 +48,9 @@ foreach (new Iterator\Keyspace($client, 'predis:*') as $key) {
/* OUTPUT
Scan the keyspace matching only our prefixed keys:
- predis:zset
- predis:set
- predis:hash
- predis:zset
- predis:set
- predis:hash
*/
// === Set iterator based on SSCAN ===
@@ -60,11 +61,11 @@ foreach (new Iterator\SetKey($client, 'predis:set') as $member) {
/* OUTPUT
Scan members of `predis:set`:
- member:1
- member:4
- member:0
- member:3
- member:2
- member:1
- member:4
- member:0
- member:3
- member:2
*/
// === Sorted set iterator based on ZSCAN ===
@@ -75,11 +76,11 @@ foreach (new Iterator\SortedSetKey($client, 'predis:zset') as $member => $rank)
/* OUTPUT
Scan members and ranks of `predis:zset`:
- member:4 [rank: -4]
- member:3 [rank: -3]
- member:2 [rank: -2]
- member:1 [rank: -1]
- member:0 [rank: 0]
- member:4 [rank: -4]
- member:3 [rank: -3]
- member:2 [rank: -2]
- member:1 [rank: -1]
- member:0 [rank: 0]
*/
// === Hash iterator based on HSCAN ===
@@ -90,9 +91,9 @@ foreach (new Iterator\HashKey($client, 'predis:hash') as $field => $value) {
/* OUTPUT
Scan fields and values of `predis:hash`:
- field:0 => value:0
- field:1 => value:1
- field:2 => value:2
- field:3 => value:3
- field:4 => value:4
- field:0 => value:0
- field:1 => value:1
- field:2 => value:2
- field:3 => value:3
- field:4 => value:4
*/
+51
View File
@@ -0,0 +1,51 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/shared.php';
// Enable igbinary serializer as well as LZ4 compression
$options = [
'serializer' => 'igbinary',
'compression' => 'lz4',
];
$client = new Predis\Client($single_server + $options, [
'connections' => 'relay',
]);
$quote = (object) [
'author' => 'Jean-Luc Picard',
'text' => 'I look forward to your report Mr. Broccoli.',
];
// Serialize object and apply LZ4 compression, then write key to Redis
$client->set('quote', $client->pack($quote));
// NOTE: In Predis v3.x serialization and compression will happen
// automatically without the need to call `pack()` and `unpack()`
// Retrieve raw binary value from Redis
$raw = $client->get('quote');
// Decompress and unserialize binary value
$data = $client->unpack($raw);
var_dump($quote == $data); // true
var_dump($data);
/*
object(stdClass)#11 (2) {
["author"]=>string(15) "Jean-Luc Picard"
["text"]=>string(43) "I look forward to your report Mr. Broccoli."
}
*/
+55
View File
@@ -0,0 +1,55 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/shared.php';
$options = [
'timeout' => 1.0,
'read_write_timeout' => 1.0,
// Relay specific options
'cache' => true,
// 'compression' => 'lz4',
// 'serializer' => 'igbinary',
];
$client = new Predis\Client($single_server + $options, [
'connections' => 'relay',
]);
// Write key to Redis
$client->set('torpedo', mt_rand());
// Retrieve key from Redis
$client->get('torpedo');
// Retrieve key from Relay (without talking to Redis)
// This key is now available to all PHP workers in this FPM pool
$client->get('torpedo');
// For debugging only:
var_export(
$client->getConnection()->getClient()->_getKeys()
);
/*
array (
'torpedo' => array (
0 => array (
'type' => 'string',
'local-len' => 10,
'remote-len' => 10,
'size' => 10,
),
),
)
*/
+61
View File
@@ -0,0 +1,61 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/shared.php';
$key = null;
$client = new Predis\Client($single_server, [
'connections' => 'relay',
]);
/** @var Predis\Connection\RelayConnection $relay */
$relay = $client->getConnection();
// establish connection
$client->ping();
// register `FLUSH*` callback
$relay->onFlushed(
static function (Relay\Event $event) use (&$key) {
echo 'Redis was flushed, unsetting $key...' . PHP_EOL;
$key = null;
}
);
// register `INVALIDATE` callback
$relay->onInvalidated(
static function (Relay\Event $event) use (&$key) {
if ($event->key === 'library') {
echo "The `{$event->key}` key was invalidated, unsetting \$key..." . PHP_EOL;
$key = null;
}
}
);
// Write key to Redis
$client->set('library', mt_rand());
// Retrieve key once from Redis, then cached in Relay and $key
$key = $client->get('library');
while (true) {
echo '$key is: ' . var_export($key, true) . PHP_EOL;
// To trigger our event callbacks, we need to either interact with Relay:
$client->get(mt_rand());
// ... or alternatively dispatch events directly on Relay:
$relay->dispatchEvents();
sleep(1);
}
+59
View File
@@ -0,0 +1,59 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__ . '/shared.php';
// Create a Relay client and disable r/w timeout on the connection
$client = new Predis\Client(
$single_server + ['read_write_timeout' => 0],
['connections' => 'relay']
);
// Initialize a new pubsub consumer.
$pubsub = $client->pubSubLoop();
// When using Relay you cannot use foreach-loops to iterate
// over messages instead use a callback function
$poorMansKafka = function ($message, $client) {
switch ($message->kind) {
case 'subscribe':
echo "Subscribed to {$message->channel}", PHP_EOL;
break;
case 'message':
case 'pmessage':
if ($message->channel == 'control_channel') {
if ($message->payload == 'quit_loop') {
echo 'Aborting pubsub loop...', PHP_EOL;
$client->unsubscribe();
} else {
echo "Received an unrecognized command: {$message->payload}.", PHP_EOL;
}
} else {
echo "Received the message from `{$message->channel}` channel:",
PHP_EOL, " {$message->payload}", PHP_EOL, PHP_EOL;
}
}
};
// Subscribe to your channels and start processing the messages.
$pubsub->subscribe('control_channel', 'notifications', $poorMansKafka);
// Open a terminal and use redis-cli to push messages to the channels. Examples:
// redis-cli PUBLISH notifications "this is a test"
// redis-cli PUBLISH control_channel quit_loop
// When using Relay, there is no need to unset the pubsub consumer instance when you are done
// Say goodbye :-)
$version = redis_version($client->info());
echo "Goodbye from Redis $version!", PHP_EOL;
+10 -9
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Predis allows to set Lua scripts as read-only operations for replication.
// This works for both EVAL and EVALSHA and also for the client-side abstraction
@@ -29,7 +30,7 @@ use Predis\Replication\ReplicationStrategy;
class HashMultipleGetAll extends ScriptCommand
{
const BODY = <<<LUA
public const BODY = <<<LUA
local hashes = {}
for _, key in pairs(KEYS) do
table.insert(hashes, key)
@@ -46,15 +47,15 @@ LUA;
// ------------------------------------------------------------------------- //
$parameters = array(
$parameters = [
'tcp://127.0.0.1:6381?role=master&database=15',
'tcp://127.0.0.1:6382?role=slave&alias=slave-01&database=15',
);
];
$options = array(
'commands' => array(
$options = [
'commands' => [
'hmgetall' => 'HashMultipleGetAll',
),
],
'replication' => function () {
$strategy = new ReplicationStrategy();
$strategy->setScriptReadOnly(HashMultipleGetAll::BODY);
@@ -63,7 +64,7 @@ $options = array(
return $replication;
},
);
];
// ------------------------------------------------------------------------- //
+7 -6
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Predis supports redis-sentinel to provide high availability in master / slave
// scenarios. The only but relevant difference with a basic replication scenario
@@ -25,16 +26,16 @@ require __DIR__.'/shared.php';
// without an explicit timeout value.
//
// NOTE: in real-world scenarios sentinels should be running on different hosts!
$sentinels = array(
$sentinels = [
'tcp://127.0.0.1:5380?timeout=0.100',
'tcp://127.0.0.1:5381?timeout=0.100',
'tcp://127.0.0.1:5382?timeout=0.100',
);
];
$client = new Predis\Client($sentinels, array(
$client = new Predis\Client($sentinels, [
'replication' => 'sentinel',
'service' => 'mymaster',
));
]);
// Read operation.
$exists = $client->exists('foo') ? 'yes' : 'no';
+6 -5
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// Predis supports master / slave replication scenarios where write operations
// are performed on the master server and read operations are executed against
@@ -21,12 +22,12 @@ require __DIR__.'/shared.php';
// slave of the first one (see the "SLAVEOF" command).
//
$parameters = array(
$parameters = [
'tcp://127.0.0.1:6381?role=master&database=15',
'tcp://127.0.0.1:6382?role=slave&database=15',
);
];
$options = array('replication' => 'predis');
$options = ['replication' => 'predis'];
$client = new Predis\Client($parameters, $options);
+6 -5
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This example demonstrates how to use Predis to save PHP sessions on Redis.
//
@@ -25,16 +26,16 @@ require __DIR__.'/shared.php';
//
if (!interface_exists('SessionHandlerInterface')) {
die('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 '.
exit('ATTENTION: the session handler implemented by Predis requires PHP >= 5.4.0 ' .
"or a polyfill for SessionHandlerInterface provided by an external package.\n");
}
// Instantiate a new client just like you would normally do. Using a prefix for
// keys will effectively prefix all session keys with the specified string.
$client = new Predis\Client($single_server, array('prefix' => 'sessions:'));
$client = new Predis\Client($single_server, ['prefix' => 'sessions:']);
// Set `gc_maxlifetime` to specify a time-to-live of 5 seconds for session keys.
$handler = new Predis\Session\Handler($client, array('gc_maxlifetime' => 5));
$handler = new Predis\Session\Handler($client, ['gc_maxlifetime' => 5]);
// Register the session handler.
$handler->register();
+20 -19
View File
@@ -3,17 +3,18 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (PHP_SAPI !== 'cli') {
die("Example scripts are meant to be executed locally via CLI.");
exit('Example scripts are meant to be executed locally via CLI.');
}
require __DIR__.'/../autoload.php';
require __DIR__ . '/../autoload.php';
function redis_version($info)
{
@@ -26,23 +27,23 @@ function redis_version($info)
}
}
$single_server = array(
$single_server = [
'host' => '127.0.0.1',
'port' => 6379,
'database' => 15,
);
];
$multiple_servers = array(
array(
'host' => '127.0.0.1',
'port' => 6379,
'database' => 15,
'alias' => 'first',
),
array(
'host' => '127.0.0.1',
'port' => 6380,
'database' => 15,
'alias' => 'second',
),
);
$multiple_servers = [
[
'host' => '127.0.0.1',
'port' => 6379,
'database' => 15,
'alias' => 'first',
],
[
'host' => '127.0.0.1',
'port' => 6380,
'database' => 15,
'alias' => 'second',
],
];
+7 -6
View File
@@ -3,13 +3,14 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
require __DIR__.'/shared.php';
require __DIR__ . '/shared.php';
// This is an implementation of an atomic client-side ZPOP using the support for
// check-and-set (CAS) operations with MULTI/EXEC transactions, as described in
@@ -27,15 +28,15 @@ require __DIR__.'/shared.php';
function zpop($client, $key)
{
$element = null;
$options = array(
$options = [
'cas' => true, // Initialize with support for CAS operations
'watch' => $key, // Key that needs to be WATCHed to detect changes
'retry' => 3, // Number of retries on aborted transactions, after
// which the client bails out with an exception.
);
// which the client bails out with an exception.
];
$client->transaction($options, function ($tx) use ($key, &$element) {
@list($element) = $tx->zrange($key, 0, 0);
@[$element] = $tx->zrange($key, 0, 0);
if (isset($element)) {
$tx->multi(); // With CAS, MULTI *must* be explicitly invoked.
+15
View File
@@ -0,0 +1,15 @@
parameters:
level: 0
paths:
- tests/
ignoreErrors:
# Uses func_get_args()
- message: "#^Static method Predis\\\\Command\\\\RawCommand\\:\\:create\\(\\) invoked with 0 parameters, at least 1 required\\.$#"
count: 1
path: tests/Predis/Command/RawCommandTest.php
# Mockery
- message: "#^Call to an undefined method Predis\\\\Configuration\\\\Option\\\\AggregateTest\\:\\:getMockConnectionClass\\(\\)\\.$#"
count: 2
path: tests/Predis/Configuration/Option/AggregateTest.php
+56
View File
@@ -0,0 +1,56 @@
parameters:
level: 2
paths:
- src/
ignoreErrors:
# Tricky ones
- message: "#^Cannot cast Predis\\\\Response\\\\ResponseInterface to string\\.$#"
count: 1
path: src/Client.php
- message: "#^Cannot cast Predis\\\\Connection\\\\ConnectionInterface to string\\.$#"
count: 1
path: src/Client.php
# phpiredis extension is not installed
- "#^Function phpiredis_\\w+ not found\\.$#"
- "#^Constant PHPIREDIS_#"
# "new static" in non-final classes
- message: "#^Unsafe usage of new static\\(\\)\\.$#"
count: 3
path: src/Client.php
- message: "#^Unsafe usage of new static\\(\\)\\.$#"
count: 1
path: src/Connection/Parameters.php
# Using an interface as concrete type
- message: "#^Call to an undefined method Predis\\\\Command\\\\FactoryInterface\\:\\:define\\(\\)\\.$#"
count: 1
path: src/Configuration/Option/Commands.php
- message: "#^Call to an undefined method Predis\\\\Command\\\\FactoryInterface\\:\\:undefine\\(\\)\\.$#"
count: 1
path: src/Configuration/Option/Commands.php
- message: "#^Access to an undefined property Predis\\\\Configuration\\\\OptionsInterface\\:\\:\\$parameters\\.$#"
count: 1
path: src/Configuration/Option/Connections.php
- message: "#^Access to an undefined property Predis\\\\Connection\\\\ParametersInterface\\:\\:\\$weight\\.$#"
count: 1
path: src/Connection/Cluster/PredisCluster.php
- message: "#^Variable \\$response might not be defined\\.$#"
count: 2
path: src/Connection/Cluster/RedisCluster.php
- message: "#^Access to an undefined property Predis\\\\Connection\\\\ParametersInterface\\:\\:\\$role\\.$#"
count: 1
path: src/Connection/Replication/MasterSlaveReplication.php
- message: "#^Access to an undefined property Predis\\\\Connection\\\\ParametersInterface\\:\\:\\$role\\.$#"
count: 1
path: src/Connection/Replication/SentinelReplication.php
# try/catch problems
- message: "#^Variable \\$connection might not be defined\\.$#"
count: 1
path: src/Connection/Replication/MasterSlaveReplication.php
- message: "#^Variable \\$response might not be defined\\.$#"
count: 1
path: src/Connection/Replication/MasterSlaveReplication.php
- message: "#^Variable \\$response might not be defined\\.$#"
count: 1
path: src/Connection/Replication/SentinelReplication.php
+49
View File
@@ -0,0 +1,49 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
beStrictAboutTestsThatDoNotTestAnything="true"
>
<testsuites>
<testsuite name="Predis Test Suite">
<directory phpVersion="7.4">tests/Predis/</directory>
</testsuite>
</testsuites>
<groups>
<exclude>
<group>relay-incompatible</group>
<group>relay-resp3</group>
<group>realm-webdis</group>
<group>realm-stack</group>
<group>ext-curl</group>
<group>ext-phpiredis</group>
<group>cluster</group>
</exclude>
</groups>
<filter>
<whitelist>
<directory suffix=".php">src/</directory>
</whitelist>
</filter>
<php>
<const name="REDIS_SERVER_HOST" value="127.0.0.1" />
<const name="REDIS_SERVER_PORT" value="6379" />
<const name="REDIS_SERVER_DBNUM" value="0" />
<env name="USE_RELAY" value="true" />
<env name="REDIS_STACK_SERVER_PORT" value="6479" />
<!-- Redis Cluster -->
<!-- Only master nodes endpoints included -->
<const name="REDIS_CLUSTER_ENDPOINTS" value="127.0.0.1:6372,127.0.0.1:6373,127.0.0.1:6374" />
</php>
</phpunit>
+31 -17
View File
@@ -1,14 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
beStrictAboutTestsThatDoNotTestAnything="true">
<phpunit
bootstrap="tests/bootstrap.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
beStrictAboutTestsThatDoNotTestAnything="true"
>
<testsuites>
<testsuite name="Predis Test Suite">
@@ -16,11 +17,23 @@
</testsuite>
</testsuites>
<coverage processUncoveredFiles="true">
<include>
<directory suffix=".php">./src</directory>
</include>
<report>
<clover outputFile="build/logs/clover.xml"/>
</report>
</coverage>
<groups>
<exclude>
<group>ext-phpiredis</group>
<group>ext-curl</group>
<group>realm-webdis</group>
<group>realm-stack</group>
<group>ext-relay</group>
<group>ext-curl</group>
<group>ext-phpiredis</group>
<group>cluster</group>
<!-- <group>connected</group> -->
<!-- <group>disconnected</group> -->
<!-- <group>commands</group> -->
@@ -35,13 +48,14 @@
</filter>
<php>
<!-- Redis -->
<const name="REDIS_SERVER_HOST" value="127.0.0.1" />
<const name="REDIS_SERVER_PORT" value="6379" />
<const name="REDIS_SERVER_DBNUM" value="15" />
<const name="REDIS_SERVER_DBNUM" value="0" />
<env name="USE_RELAY" value="false" />
<env name="REDIS_STACK_SERVER_PORT" value="6479" />
<!-- Webdis -->
<const name="WEBDIS_SERVER_HOST" value="127.0.0.1" />
<const name="WEBDIS_SERVER_PORT" value="7379" />
<!-- Redis Cluster -->
<!-- Only master nodes endpoints included -->
<const name="REDIS_CLUSTER_ENDPOINTS" value="127.0.0.1:6372,127.0.0.1:6373,127.0.0.1:6374" />
</php>
</phpunit>
+5 -4
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -30,7 +31,7 @@ class Autoloader
public function __construct($baseDirectory = __DIR__)
{
$this->directory = $baseDirectory;
$this->prefix = __NAMESPACE__.'\\';
$this->prefix = __NAMESPACE__ . '\\';
$this->prefixLength = strlen($this->prefix);
}
@@ -41,7 +42,7 @@ class Autoloader
*/
public static function register($prepend = false)
{
spl_autoload_register(array(new self(), 'autoload'), true, $prepend);
spl_autoload_register([new self(), 'autoload'], true, $prepend);
}
/**
@@ -53,7 +54,7 @@ class Autoloader
{
if (0 === strpos($className, $this->prefix)) {
$parts = explode('\\', substr($className, $this->prefixLength));
$filepath = $this->directory.DIRECTORY_SEPARATOR.implode(DIRECTORY_SEPARATOR, $parts).'.php';
$filepath = $this->directory . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $parts) . '.php';
if (is_file($filepath)) {
require $filepath;
+132 -54
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,21 +12,35 @@
namespace Predis;
use ArrayIterator;
use InvalidArgumentException;
use IteratorAggregate;
use Predis\Command\CommandInterface;
use Predis\Command\RawCommand;
use Predis\Command\Redis\Container\ContainerFactory;
use Predis\Command\Redis\Container\ContainerInterface;
use Predis\Command\ScriptCommand;
use Predis\Configuration\Options;
use Predis\Configuration\OptionsInterface;
use Predis\Connection\ConnectionInterface;
use Predis\Connection\Parameters;
use Predis\Connection\ParametersInterface;
use Predis\Connection\RelayConnection;
use Predis\Monitor\Consumer as MonitorConsumer;
use Predis\Pipeline\Atomic;
use Predis\Pipeline\FireAndForget;
use Predis\Pipeline\Pipeline;
use Predis\Pipeline\RelayAtomic;
use Predis\Pipeline\RelayPipeline;
use Predis\PubSub\Consumer as PubSubConsumer;
use Predis\PubSub\RelayConsumer as RelayPubSubConsumer;
use Predis\Response\ErrorInterface as ErrorResponseInterface;
use Predis\Response\ResponseInterface;
use Predis\Response\ServerException;
use Predis\Transaction\MultiExec as MultiExecTransaction;
use ReturnTypeWillChange;
use RuntimeException;
use Traversable;
/**
* Client class used for connecting and executing commands on Redis.
@@ -34,13 +49,11 @@ use Predis\Transaction\MultiExec as MultiExecTransaction;
* abstractions are built. Internally it aggregates various other classes each
* one with its own responsibility and scope.
*
* {@inheritdoc}
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* @template-implements \IteratorAggregate<string, static>
*/
class Client implements ClientInterface, \IteratorAggregate
class Client implements ClientInterface, IteratorAggregate
{
const VERSION = '2.0.0';
public const VERSION = '2.4.0-RC1';
/** @var OptionsInterface */
private $options;
@@ -57,8 +70,8 @@ class Client implements ClientInterface, \IteratorAggregate
*/
public function __construct($parameters = null, $options = null)
{
$this->options = static::createOptions($options ?? new Options);
$this->connection = static::createConnection($this->options, $parameters ?? new Parameters);
$this->options = static::createOptions($options ?? new Options());
$this->connection = static::createConnection($this->options, $parameters ?? new Parameters());
$this->commands = $this->options->commands;
}
@@ -67,9 +80,8 @@ class Client implements ClientInterface, \IteratorAggregate
*
* @param array|OptionsInterface $options Set of client options
*
* @throws \InvalidArgumentException
*
* @return OptionsInterface
* @throws InvalidArgumentException
*/
protected static function createOptions($options)
{
@@ -78,7 +90,7 @@ class Client implements ClientInterface, \IteratorAggregate
} elseif ($options instanceof OptionsInterface) {
return $options;
} else {
throw new \InvalidArgumentException('Invalid type for client options');
throw new InvalidArgumentException('Invalid type for client options');
}
}
@@ -103,9 +115,8 @@ class Client implements ClientInterface, \IteratorAggregate
* @param OptionsInterface $options Client options container
* @param mixed $parameters Connection parameters
*
* @throws \InvalidArgumentException
*
* @return ConnectionInterface
* @throws InvalidArgumentException
*/
protected static function createConnection(OptionsInterface $options, $parameters)
{
@@ -127,7 +138,7 @@ class Client implements ClientInterface, \IteratorAggregate
} elseif ($options->defined('aggregate') && $initializer = $options->aggregate) {
return $initializer($parameters, false);
} else {
throw new \InvalidArgumentException(
throw new InvalidArgumentException(
'Array of connection parameters requires `cluster`, `replication` or `aggregate` client option'
);
}
@@ -137,13 +148,13 @@ class Client implements ClientInterface, \IteratorAggregate
$connection = call_user_func($parameters, $options);
if (!$connection instanceof ConnectionInterface) {
throw new \InvalidArgumentException('Callable parameters must return a valid connection');
throw new InvalidArgumentException('Callable parameters must return a valid connection');
}
return $connection;
}
throw new \InvalidArgumentException('Invalid type for connection parameters');
throw new InvalidArgumentException('Invalid type for connection parameters');
}
/**
@@ -196,17 +207,17 @@ class Client implements ClientInterface, \IteratorAggregate
{
$selector = strtolower($selector);
if (!in_array($selector, array('id', 'key', 'slot', 'role', 'alias', 'command'))) {
throw new \InvalidArgumentException("Invalid selector type: `$selector`");
if (!in_array($selector, ['id', 'key', 'slot', 'role', 'alias', 'command'])) {
throw new InvalidArgumentException("Invalid selector type: `$selector`");
}
if (!method_exists($this->connection, $method = "getConnectionBy$selector")) {
$class = get_class($this->connection);
throw new \InvalidArgumentException("Selecting connection by $selector is not supported by $class");
throw new InvalidArgumentException("Selecting connection by $selector is not supported by $class");
}
if (!$connection = $this->connection->$method($value)) {
throw new \InvalidArgumentException("Cannot find a connection by $selector matching `$value`");
throw new InvalidArgumentException("Cannot find a connection by $selector matching `$value`");
}
return new static($connection, $this->getOptions());
@@ -257,6 +268,32 @@ class Client implements ClientInterface, \IteratorAggregate
return $this->connection;
}
/**
* Applies the configured serializer and compression to given value.
*
* @param mixed $value
* @return string
*/
public function pack($value)
{
return $this->connection instanceof RelayConnection
? $this->connection->pack($value)
: $value;
}
/**
* Deserializes and decompresses to given value.
*
* @param mixed $value
* @return string
*/
public function unpack($value)
{
return $this->connection instanceof RelayConnection
? $this->connection->unpack($value)
: $value;
}
/**
* Executes a command without filtering its arguments, parsing the response,
* applying any prefix to keys or throwing exceptions on Redis errors even
@@ -303,11 +340,39 @@ class Client implements ClientInterface, \IteratorAggregate
/**
* {@inheritdoc}
*/
public function createCommand($commandID, $arguments = array())
public function createCommand($commandID, $arguments = [])
{
return $this->commands->create($commandID, $arguments);
}
/**
* @param string $name
* @return ContainerInterface
*/
public function __get(string $name)
{
return ContainerFactory::create($this, $name);
}
/**
* @param string $name
* @param mixed $value
* @return mixed
*/
public function __set(string $name, $value)
{
throw new RuntimeException('Not allowed');
}
/**
* @param string $name
* @return mixed
*/
public function __isset(string $name)
{
throw new RuntimeException('Not allowed');
}
/**
* {@inheritdoc}
*/
@@ -332,9 +397,8 @@ class Client implements ClientInterface, \IteratorAggregate
* @param CommandInterface $command Redis command that generated the error.
* @param ErrorResponseInterface $response Instance of the error response.
*
* @throws ServerException
*
* @return mixed
* @throws ServerException
*/
protected function onErrorResponse(CommandInterface $command, ErrorResponseInterface $response)
{
@@ -357,7 +421,7 @@ class Client implements ClientInterface, \IteratorAggregate
/**
* Executes the specified initializer method on `$this` by adjusting the
* actual invokation depending on the arity (0, 1 or 2 arguments). This is
* actual invocation depending on the arity (0, 1 or 2 arguments). This is
* simply an utility method to create Redis contexts instances since they
* follow a common initialization path.
*
@@ -378,26 +442,24 @@ class Client implements ClientInterface, \IteratorAggregate
: $this->$initializer(null, $argv[0]);
case 2:
list($arg0, $arg1) = $argv;
[$arg0, $arg1] = $argv;
return $this->$initializer($arg0, $arg1);
// @codeCoverageIgnoreStart
default:
return $this->$initializer($this, $argv);
}
// @codeCoverageIgnoreEnd
}
/**
* Creates a new pipeline context and returns it, or returns the results of
* a pipeline executed inside the optionally provided callable object.
*
* @param mixed ... Array of options, a callable for execution, or both.
* @param mixed ...$arguments Array of options, a callable for execution, or both.
*
* @return Pipeline|array
*/
public function pipeline(/* arguments */)
public function pipeline(...$arguments)
{
return $this->sharedContextFactory('createPipeline', func_get_args());
}
@@ -405,19 +467,29 @@ class Client implements ClientInterface, \IteratorAggregate
/**
* Actual pipeline context initializer method.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
* @param array|null $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
*
* @return Pipeline|array
*/
protected function createPipeline(array $options = null, $callable = null)
protected function createPipeline(?array $options = null, $callable = null)
{
if (isset($options['atomic']) && $options['atomic']) {
$class = 'Predis\Pipeline\Atomic';
$class = Atomic::class;
} elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
$class = 'Predis\Pipeline\FireAndForget';
$class = FireAndForget::class;
} else {
$class = 'Predis\Pipeline\Pipeline';
$class = Pipeline::class;
}
if ($this->connection instanceof RelayConnection) {
if (isset($options['atomic']) && $options['atomic']) {
$class = RelayAtomic::class;
} elseif (isset($options['fire-and-forget']) && $options['fire-and-forget']) {
throw new NotSupportedException('The "relay" extension does not support fire-and-forget pipelines.');
} else {
$class = RelayPipeline::class;
}
}
/*
@@ -436,11 +508,11 @@ class Client implements ClientInterface, \IteratorAggregate
* Creates a new transaction context and returns it, or returns the results
* of a transaction executed inside the optionally provided callable object.
*
* @param mixed ... Array of options, a callable for execution, or both.
* @param mixed ...$arguments Array of options, a callable for execution, or both.
*
* @return MultiExecTransaction|array
*/
public function transaction(/* arguments */)
public function transaction(...$arguments)
{
return $this->sharedContextFactory('createTransaction', func_get_args());
}
@@ -448,12 +520,12 @@ class Client implements ClientInterface, \IteratorAggregate
/**
* Actual transaction context initializer method.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
* @param array|null $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
*
* @return MultiExecTransaction|array
*/
protected function createTransaction(array $options = null, $callable = null)
protected function createTransaction(?array $options = null, $callable = null)
{
$transaction = new MultiExecTransaction($this, $options);
@@ -468,11 +540,11 @@ class Client implements ClientInterface, \IteratorAggregate
* Creates a new publish/subscribe context and returns it, or starts its loop
* inside the optionally provided callable object.
*
* @param mixed ... Array of options, a callable for execution, or both.
* @param mixed ...$arguments Array of options, a callable for execution, or both.
*
* @return PubSubConsumer|null
*/
public function pubSubLoop(/* arguments */)
public function pubSubLoop(...$arguments)
{
return $this->sharedContextFactory('createPubSub', func_get_args());
}
@@ -480,14 +552,18 @@ class Client implements ClientInterface, \IteratorAggregate
/**
* Actual publish/subscribe context initializer method.
*
* @param array $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
* @param array|null $options Options for the context.
* @param mixed $callable Optional callable used to execute the context.
*
* @return PubSubConsumer|null
*/
protected function createPubSub(array $options = null, $callable = null)
protected function createPubSub(?array $options = null, $callable = null)
{
$pubsub = new PubSubConsumer($this, $options);
if ($this->connection instanceof RelayConnection) {
$pubsub = new RelayPubSubConsumer($this, $options);
} else {
$pubsub = new PubSubConsumer($this, $options);
}
if (!isset($callable)) {
return $pubsub;
@@ -498,6 +574,8 @@ class Client implements ClientInterface, \IteratorAggregate
$pubsub->stop();
}
}
return null;
}
/**
@@ -511,24 +589,24 @@ class Client implements ClientInterface, \IteratorAggregate
}
/**
* {@inheritdoc}
* @return Traversable<string, static>
*/
#[\ReturnTypeWillChange]
#[ReturnTypeWillChange]
public function getIterator()
{
$clients = array();
$clients = [];
$connection = $this->getConnection();
if (!$connection instanceof \Traversable) {
return new \ArrayIterator(array(
(string) $connection => new static($connection, $this->getOptions())
));
if (!$connection instanceof Traversable) {
return new ArrayIterator([
(string) $connection => new static($connection, $this->getOptions()),
]);
}
foreach ($connection as $node) {
$clients[(string) $node] = new static($node, $this->getOptions());
}
return new \ArrayIterator($clients);
return new ArrayIterator($clients);
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis;
class ClientConfiguration
{
/**
* @var array{modules: array}|string[][]
*/
private static $config = [
'modules' => [
['name' => 'Json', 'commandPrefix' => 'JSON'],
['name' => 'BloomFilter', 'commandPrefix' => 'BF'],
['name' => 'CuckooFilter', 'commandPrefix' => 'CF'],
['name' => 'CountMinSketch', 'commandPrefix' => 'CMS'],
['name' => 'TDigest', 'commandPrefix' => 'TDIGEST'],
['name' => 'TopK', 'commandPrefix' => 'TOPK'],
['name' => 'Search', 'commandPrefix' => 'FT'],
['name' => 'TimeSeries', 'commandPrefix' => 'TS'],
],
];
/**
* Returns available modules with configuration.
*
* @return array|string[][]
*/
public static function getModules(): array
{
return self::$config['modules'];
}
}
+218 -21
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,16 +12,51 @@
namespace Predis;
use Predis\Command\Argument\Geospatial\ByInterface;
use Predis\Command\Argument\Geospatial\FromInterface;
use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\AlterArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\DropArguments;
use Predis\Command\Argument\Search\ExplainArguments;
use Predis\Command\Argument\Search\ProfileArguments;
use Predis\Command\Argument\Search\SchemaFields\FieldInterface;
use Predis\Command\Argument\Search\SearchArguments;
use Predis\Command\Argument\Search\SugAddArguments;
use Predis\Command\Argument\Search\SugGetArguments;
use Predis\Command\Argument\Search\SynUpdateArguments;
use Predis\Command\Argument\Server\LimitOffsetCount;
use Predis\Command\Argument\Server\To;
use Predis\Command\Argument\TimeSeries\AddArguments;
use Predis\Command\Argument\TimeSeries\AlterArguments as TSAlterArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments as TSCreateArguments;
use Predis\Command\Argument\TimeSeries\DecrByArguments;
use Predis\Command\Argument\TimeSeries\GetArguments;
use Predis\Command\Argument\TimeSeries\IncrByArguments;
use Predis\Command\Argument\TimeSeries\InfoArguments;
use Predis\Command\Argument\TimeSeries\MGetArguments;
use Predis\Command\Argument\TimeSeries\MRangeArguments;
use Predis\Command\Argument\TimeSeries\RangeArguments;
use Predis\Command\CommandInterface;
use Predis\Command\Redis\Container\ACL;
use Predis\Command\Redis\Container\CLUSTER;
use Predis\Command\Redis\Container\FunctionContainer;
use Predis\Command\Redis\Container\Json\JSONDEBUG;
use Predis\Command\Redis\Container\Search\FTCONFIG;
use Predis\Command\Redis\Container\Search\FTCURSOR;
use Predis\Command\Redis\HGETEX;
use Predis\Command\Redis\HSETEX;
/**
* Interface defining a client-side context such as a pipeline or transaction.
*
* @method $this copy(string $source, string $destination, int $db = -1, bool $replace = false)
* @method $this del(array|string $keys)
* @method $this dump($key)
* @method $this exists($key)
* @method $this expire($key, $seconds)
* @method $this expireat($key, $timestamp)
* @method $this expire($key, $seconds, string $expireOption = '')
* @method $this expireat($key, $timestamp, string $expireOption = '')
* @method $this expiretime(string $key)
* @method $this keys($pattern)
* @method $this move($key, $db)
* @method $this object($subcommand, $key)
@@ -31,20 +67,81 @@ use Predis\Command\CommandInterface;
* @method $this randomkey()
* @method $this rename($key, $target)
* @method $this renamenx($key, $target)
* @method $this scan($cursor, array $options = null)
* @method $this sort($key, array $options = null)
* @method $this scan($cursor, ?array $options = null)
* @method $this sort($key, ?array $options = null)
* @method $this sort_ro(string $key, ?string $byPattern = null, ?LimitOffsetCount $limit = null, array $getPatterns = [], ?string $sorting = null, bool $alpha = false)
* @method $this ttl($key)
* @method $this type($key)
* @method $this append($key, $value)
* @method $this bitcount($key, $start = null, $end = null)
* @method $this bfadd(string $key, $item)
* @method $this bfexists(string $key, $item)
* @method $this bfinfo(string $key, string $modifier = '')
* @method $this bfinsert(string $key, int $capacity = -1, float $error = -1, int $expansion = -1, bool $noCreate = false, bool $nonScaling = false, string ...$item)
* @method $this bfloadchunk(string $key, int $iterator, $data)
* @method $this bfmadd(string $key, ...$item)
* @method $this bfmexists(string $key, ...$item)
* @method $this bfreserve(string $key, float $errorRate, int $capacity, int $expansion = -1, bool $nonScaling = false)
* @method $this bfscandump(string $key, int $iterator)
* @method $this bitcount(string $key, $start = null, $end = null, string $index = 'byte')
* @method $this bitop($operation, $destkey, $key)
* @method $this bitfield($key, $subcommand, ...$subcommandArg)
* @method $this bitpos($key, $bit, $start = null, $end = null)
* @method $this bitfield_ro(string $key, ?array $encodingOffsetMap = null)
* @method $this bitpos($key, $bit, $start = null, $end = null, string $index = 'byte')
* @method $this blmpop(int $timeout, array $keys, string $modifier = 'left', int $count = 1)
* @method $this bzpopmax(array $keys, int $timeout)
* @method $this bzpopmin(array $keys, int $timeout)
* @method $this bzmpop(int $timeout, array $keys, string $modifier = 'min', int $count = 1)
* @method $this cfadd(string $key, $item)
* @method $this cfaddnx(string $key, $item)
* @method $this cfcount(string $key, $item)
* @method $this cfdel(string $key, $item)
* @method $this cfexists(string $key, $item)
* @method $this cfloadchunk(string $key, int $iterator, $data)
* @method $this cfmexists(string $key, ...$item)
* @method $this cfinfo(string $key)
* @method $this cfinsert(string $key, int $capacity = -1, bool $noCreate = false, string ...$item)
* @method $this cfinsertnx(string $key, int $capacity = -1, bool $noCreate = false, string ...$item)
* @method $this cfreserve(string $key, int $capacity, int $bucketSize = -1, int $maxIterations = -1, int $expansion = -1)
* @method $this cfscandump(string $key, int $iterator)
* @method $this cmsincrby(string $key, string|int...$itemIncrementDictionary)
* @method $this cmsinfo(string $key)
* @method $this cmsinitbydim(string $key, int $width, int $depth)
* @method $this cmsinitbyprob(string $key, float $errorRate, float $probability)
* @method $this cmsmerge(string $destination, array $sources, array $weights = [])
* @method $this cmsquery(string $key, string ...$item)
* @method $this decr($key)
* @method $this decrby($key, $decrement)
* @method $this failover(?To $to = null, bool $abort = false, int $timeout = -1)
* @method $this fcall(string $function, array $keys, ...$args)
* @method $this fcall_ro(string $function, array $keys, ...$args)
* @method $this ft_list()
* @method $this ftaggregate(string $index, string $query, ?AggregateArguments $arguments = null)
* @method $this ftaliasadd(string $alias, string $index)
* @method $this ftaliasdel(string $alias)
* @method $this ftaliasupdate(string $alias, string $index)
* @method $this ftalter(string $index, FieldInterface[] $schema, ?AlterArguments $arguments = null)
* @method $this ftcreate(string $index, FieldInterface[] $schema, ?CreateArguments $arguments = null)
* @method $this ftdictadd(string $dict, ...$term)
* @method $this ftdictdel(string $dict, ...$term)
* @method $this ftdictdump(string $dict)
* @method $this ftdropindex(string $index, ?DropArguments $arguments = null)
* @method $this ftexplain(string $index, string $query, ?ExplainArguments $arguments = null)
* @method $this ftinfo(string $index)
* @method $this ftprofile(string $index, ProfileArguments $arguments)
* @method $this ftsearch(string $index, string $query, ?SearchArguments $arguments = null)
* @method $this ftspellcheck(string $index, string $query, ?SearchArguments $arguments = null)
* @method $this ftsugadd(string $key, string $string, float $score, ?SugAddArguments $arguments = null)
* @method $this ftsugdel(string $key, string $string)
* @method $this ftsugget(string $key, string $prefix, ?SugGetArguments $arguments = null)
* @method $this ftsuglen(string $key)
* @method $this ftsyndump(string $index)
* @method $this ftsynupdate(string $index, string $synonymGroupId, ?SynUpdateArguments $arguments = null, string ...$terms)
* @method $this fttagvals(string $index, string $fieldName)
* @method $this get($key)
* @method $this getbit($key, $offset)
* @method $this getex(string $key, $modifier = '', $value = false)
* @method $this getrange($key, $start, $end)
* @method $this getdel(string $key)
* @method $this getset($key, $value)
* @method $this incr($key)
* @method $this incrby($key, $increment)
@@ -61,25 +158,64 @@ use Predis\Command\CommandInterface;
* @method $this strlen($key)
* @method $this hdel($key, array $fields)
* @method $this hexists($key, $field)
* @method $this hexpire(string $key, int $seconds, array $fields, string $flag = null)
* @method $this hexpireat(string $key, int $unixTimeSeconds, array $fields, string $flag = null)
* @method $this hexpiretime(string $key, array $fields)
* @method $this hpersist(string $key, array $fields)
* @method $this hpexpire(string $key, int $milliseconds, array $fields, string $flag = null)
* @method $this hpexpireat(string $key, int $unixTimeMilliseconds, array $fields, string $flag = null)
* @method $this hpexpiretime(string $key, array $fields)
* @method $this hget($key, $field)
* @method $this hgetex(string $key, array $fields, string $modifier = HGETEX::NULL)
* @method $this hgetall($key)
* @method $this hgetdel(string $key, array $fields)
* @method $this hincrby($key, $field, $increment)
* @method $this hincrbyfloat($key, $field, $increment)
* @method $this hkeys($key)
* @method $this hlen($key)
* @method $this hmget($key, array $fields)
* @method $this hmset($key, array $dictionary)
* @method $this hscan($key, $cursor, array $options = null)
* @method $this hrandfield(string $key, int $count = 1, bool $withValues = false)
* @method $this hscan($key, $cursor, ?array $options = null)
* @method $this hset($key, $field, $value)
* @method $this hsetex(string $key, array $fieldValueMap, string $setModifier = HSETEX::SET_NULL, string $ttlModifier = HSETEX::TTL_NULL, int|bool $ttlModifierValue = false)
* @method $this hsetnx($key, $field, $value)
* @method $this httl(string $key, array $fields)
* @method $this hpttl(string $key, array $fields)
* @method $this hvals($key)
* @method $this hstrlen($key, $field)
* @method $this jsonarrappend(string $key, string $path = '$', ...$value)
* @method $this jsonarrindex(string $key, string $path, string $value, int $start = 0, int $stop = 0)
* @method $this jsonarrinsert(string $key, string $path, int $index, string ...$value)
* @method $this jsonarrlen(string $key, string $path = '$')
* @method $this jsonarrpop(string $key, string $path = '$', int $index = -1)
* @method $this jsonarrtrim(string $key, string $path, int $start, int $stop)
* @method $this jsonclear(string $key, string $path = '$')
* @method $this jsondel(string $key, string $path = '$')
* @method $this jsonforget(string $key, string $path = '$')
* @method $this jsonget(string $key, string $indent = '', string $newline = '', string $space = '', string ...$paths)
* @method $this jsonnumincrby(string $key, string $path, int $value)
* @method $this jsonmerge(string $key, string $path, string $value)
* @method $this jsonmget(array $keys, string $path)
* @method $this jsonmset(string ...$keyPathValue)
* @method $this jsonobjkeys(string $key, string $path = '$')
* @method $this jsonobjlen(string $key, string $path = '$')
* @method $this jsonresp(string $key, string $path = '$')
* @method $this jsonset(string $key, string $path, string $value, ?string $subcommand = null)
* @method $this jsonstrappend(string $key, string $path, string $value)
* @method $this jsonstrlen(string $key, string $path = '$')
* @method $this jsontoggle(string $key, string $path)
* @method $this jsontype(string $key, string $path = '$')
* @method $this blmove(string $source, string $destination, string $where, string $to, int $timeout)
* @method $this blpop(array|string $keys, $timeout)
* @method $this brpop(array|string $keys, $timeout)
* @method $this brpoplpush($source, $destination, $timeout)
* @method $this lcs(string $key1, string $key2, bool $len = false, bool $idx = false, int $minMatchLen = 0, bool $withMatchLen = false)
* @method $this lindex($key, $index)
* @method $this linsert($key, $whence, $pivot, $value)
* @method $this llen($key)
* @method $this lmove(string $source, string $destination, string $where, string $to)
* @method $this lmpop(array $keys, string $modifier = 'left', int $count = 1)
* @method $this lpop($key)
* @method $this lpush($key, array $values)
* @method $this lpushx($key, array $values)
@@ -96,37 +232,86 @@ use Predis\Command\CommandInterface;
* @method $this sdiff(array|string $keys)
* @method $this sdiffstore($destination, array|string $keys)
* @method $this sinter(array|string $keys)
* @method $this sintercard(array $keys, int $limit = 0)
* @method $this sinterstore($destination, array|string $keys)
* @method $this sismember($key, $member)
* @method $this smembers($key)
* @method $this smismember(string $key, string ...$members)
* @method $this smove($source, $destination, $member)
* @method $this spop($key, $count = null)
* @method $this srandmember($key, $count = null)
* @method $this srem($key, $member)
* @method $this sscan($key, $cursor, array $options = null)
* @method $this sscan($key, $cursor, ?array $options = null)
* @method $this sunion(array|string $keys)
* @method $this sunionstore($destination, array|string $keys)
* @method $this tdigestadd(string $key, float ...$value)
* @method $this tdigestbyrank(string $key, int ...$rank)
* @method $this tdigestbyrevrank(string $key, int ...$reverseRank)
* @method $this tdigestcdf(string $key, int ...$value)
* @method $this tdigestcreate(string $key, int $compression = 0)
* @method $this tdigestinfo(string $key)
* @method $this tdigestmax(string $key)
* @method $this tdigestmerge(string $destinationKey, array $sourceKeys, int $compression = 0, bool $override = false)
* @method $this tdigestquantile(string $key, float ...$quantile)
* @method $this tdigestmin(string $key)
* @method $this tdigestrank(string $key, ...$value)
* @method $this tdigestreset(string $key)
* @method $this tdigestrevrank(string $key, float ...$value)
* @method $this tdigesttrimmed_mean(string $key, float $lowCutQuantile, float $highCutQuantile)
* @method $this topkadd(string $key, ...$items)
* @method $this topkincrby(string $key, ...$itemIncrement)
* @method $this topkinfo(string $key)
* @method $this topklist(string $key, bool $withCount = false)
* @method $this topkquery(string $key, ...$items)
* @method $this topkreserve(string $key, int $topK, int $width = 8, int $depth = 7, float $decay = 0.9)
* @method $this tsadd(string $key, int $timestamp, float $value, ?AddArguments $arguments = null)
* @method $this tsalter(string $key, ?TSAlterArguments $arguments = null)
* @method $this tscreate(string $key, ?TSCreateArguments $arguments = null)
* @method $this tscreaterule(string $sourceKey, string $destKey, string $aggregator, int $bucketDuration, int $alignTimestamp = 0)
* @method $this tsdecrby(string $key, float $value, ?DecrByArguments $arguments = null)
* @method $this tsdel(string $key, int $fromTimestamp, int $toTimestamp)
* @method $this tsdeleterule(string $sourceKey, string $destKey)
* @method $this tsget(string $key, ?GetArguments $arguments = null)
* @method $this tsincrby(string $key, float $value, ?IncrByArguments $arguments = null)
* @method $this tsinfo(string $key, ?InfoArguments $arguments = null)
* @method $this tsmadd(mixed ...$keyTimestampValue)
* @method $this tsmget(MGetArguments $arguments, string ...$filterExpression)
* @method $this tsmrange($fromTimestamp, $toTimestamp, MRangeArguments $arguments)
* @method $this tsmrevrange($fromTimestamp, $toTimestamp, MRangeArguments $arguments)
* @method $this tsqueryindex(string ...$filterExpression)
* @method $this tsrange(string $key, $fromTimestamp, $toTimestamp, ?RangeArguments $arguments = null)
* @method $this tsrevrange(string $key, $fromTimestamp, $toTimestamp, ?RangeArguments $arguments = null)
* @method $this zadd($key, array $membersAndScoresDictionary)
* @method $this zcard($key)
* @method $this zcount($key, $min, $max)
* @method $this zdiff(array $keys, bool $withScores = false)
* @method $this zdiffstore(string $destination, array $keys)
* @method $this zincrby($key, $increment, $member)
* @method $this zinterstore($destination, array|string $keys, array $options = null)
* @method $this zrange($key, $start, $stop, array $options = null)
* @method $this zrangebyscore($key, $min, $max, array $options = null)
* @method $this zintercard(array $keys, int $limit = 0)
* @method $this zinterstore(string $destination, array $keys, int[] $weights = [], string $aggregate = 'sum')
* @method $this zinter(array $keys, int[] $weights = [], string $aggregate = 'sum', bool $withScores = false)
* @method $this zmpop(array $keys, string $modifier = 'min', int $count = 1)
* @method $this zmscore(string $key, string ...$member)
* @method $this zrandmember(string $key, int $count = 1, bool $withScores = false)
* @method $this zrange($key, $start, $stop, ?array $options = null)
* @method $this zrangebyscore($key, $min, $max, ?array $options = null)
* @method $this zrangestore(string $destination, string $source, int|string $min, string|int $max, string|bool $by = false, bool $reversed = false, bool $limit = false, int $offset = 0, int $count = 0)
* @method $this zrank($key, $member)
* @method $this zrem($key, $member)
* @method $this zremrangebyrank($key, $start, $stop)
* @method $this zremrangebyscore($key, $min, $max)
* @method $this zrevrange($key, $start, $stop, array $options = null)
* @method $this zrevrangebyscore($key, $max, $min, array $options = null)
* @method $this zrevrange($key, $start, $stop, ?array $options = null)
* @method $this zrevrangebyscore($key, $max, $min, ?array $options = null)
* @method $this zrevrank($key, $member)
* @method $this zunionstore($destination, array|string $keys, array $options = null)
* @method $this zunion(array $keys, int[] $weights = [], string $aggregate = 'sum', bool $withScores = false)
* @method $this zunionstore(string $destination, array $keys, int[] $weights = [], string $aggregate = 'sum')
* @method $this zscore($key, $member)
* @method $this zscan($key, $cursor, array $options = null)
* @method $this zrangebylex($key, $start, $stop, array $options = null)
* @method $this zrevrangebylex($key, $start, $stop, array $options = null)
* @method $this zscan($key, $cursor, ?array $options = null)
* @method $this zrangebylex($key, $start, $stop, ?array $options = null)
* @method $this zrevrangebylex($key, $start, $stop, ?array $options = null)
* @method $this zremrangebylex($key, $min, $max)
* @method $this zlexcount($key, $min, $max)
* @method $this pexpiretime(string $key)
* @method $this pfadd($key, array $elements)
* @method $this pfmerge($destinationKey, array|string $sourceKeys)
* @method $this pfcount(array|string $keys)
@@ -136,10 +321,14 @@ use Predis\Command\CommandInterface;
* @method $this exec()
* @method $this multi()
* @method $this unwatch()
* @method $this waitaof(int $numLocal, int $numReplicas, int $timeout)
* @method $this watch($key)
* @method $this eval($script, $numkeys, $keyOrArg1 = null, $keyOrArgN = null)
* @method $this eval_ro(string $script, array $keys, ...$argument)
* @method $this evalsha($script, $numkeys, $keyOrArg1 = null, $keyOrArgN = null)
* @method $this evalsha_ro(string $sha1, array $keys, ...$argument)
* @method $this script($subcommand, $argument = null)
* @method $this shutdown(?bool $noSave = null, bool $now = false, bool $force = false, bool $abort = false)
* @method $this auth($password)
* @method $this echo($message)
* @method $this ping($message = null)
@@ -162,10 +351,18 @@ use Predis\Command\CommandInterface;
* @method $this geohash($key, array $members)
* @method $this geopos($key, array $members)
* @method $this geodist($key, $member1, $member2, $unit = null)
* @method $this georadius($key, $longitude, $latitude, $radius, $unit, array $options = null)
* @method $this georadiusbymember($key, $member, $radius, $unit, array $options = null)
* @method $this georadius($key, $longitude, $latitude, $radius, $unit, ?array $options = null)
* @method $this georadiusbymember($key, $member, $radius, $unit, ?array $options = null)
* @method $this geosearch(string $key, FromInterface $from, ByInterface $by, ?string $sorting = null, int $count = -1, bool $any = false, bool $withCoord = false, bool $withDist = false, bool $withHash = false)
* @method $this geosearchstore(string $destination, string $source, FromInterface $from, ByInterface $by, ?string $sorting = null, int $count = -1, bool $any = false, bool $storeDist = false)
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* Container commands
* @property CLUSTER $cluster
* @property FunctionContainer $function
* @property FTCONFIG $ftconfig
* @property FTCURSOR $ftcursor
* @property JSONDEBUG $jsondebug
* @property ACL $acl
*/
interface ClientContextInterface
{
+2 -3
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -13,8 +14,6 @@ namespace Predis;
/**
* Exception class that identifies client-side errors.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class ClientException extends PredisException
{
+360 -154
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,8 +12,41 @@
namespace Predis;
use Predis\Command\Argument\Geospatial\ByInterface;
use Predis\Command\Argument\Geospatial\FromInterface;
use Predis\Command\Argument\Search\AggregateArguments;
use Predis\Command\Argument\Search\AlterArguments;
use Predis\Command\Argument\Search\CreateArguments;
use Predis\Command\Argument\Search\DropArguments;
use Predis\Command\Argument\Search\ExplainArguments;
use Predis\Command\Argument\Search\ProfileArguments;
use Predis\Command\Argument\Search\SchemaFields\FieldInterface;
use Predis\Command\Argument\Search\SearchArguments;
use Predis\Command\Argument\Search\SugAddArguments;
use Predis\Command\Argument\Search\SugGetArguments;
use Predis\Command\Argument\Search\SynUpdateArguments;
use Predis\Command\Argument\Server\LimitOffsetCount;
use Predis\Command\Argument\Server\To;
use Predis\Command\Argument\TimeSeries\AddArguments;
use Predis\Command\Argument\TimeSeries\AlterArguments as TSAlterArguments;
use Predis\Command\Argument\TimeSeries\CreateArguments as TSCreateArguments;
use Predis\Command\Argument\TimeSeries\DecrByArguments;
use Predis\Command\Argument\TimeSeries\GetArguments;
use Predis\Command\Argument\TimeSeries\IncrByArguments;
use Predis\Command\Argument\TimeSeries\InfoArguments;
use Predis\Command\Argument\TimeSeries\MGetArguments;
use Predis\Command\Argument\TimeSeries\MRangeArguments;
use Predis\Command\Argument\TimeSeries\RangeArguments;
use Predis\Command\CommandInterface;
use Predis\Command\FactoryInterface;
use Predis\Command\Redis\Container\ACL;
use Predis\Command\Redis\Container\CLUSTER;
use Predis\Command\Redis\Container\FunctionContainer;
use Predis\Command\Redis\Container\Json\JSONDEBUG;
use Predis\Command\Redis\Container\Search\FTCONFIG;
use Predis\Command\Redis\Container\Search\FTCURSOR;
use Predis\Command\Redis\HGETEX;
use Predis\Command\Redis\HSETEX;
use Predis\Configuration\OptionsInterface;
use Predis\Connection\ConnectionInterface;
use Predis\Response\Status;
@@ -25,159 +59,331 @@ use Predis\Response\Status;
* and more friendly interface to ease programming which is described in the
* following list of methods:
*
* @method int del(string[]|string $keyOrKeys, string ...$keys = null)
* @method string|null dump(string $key)
* @method int exists(string $key)
* @method int expire(string $key, int $seconds)
* @method int expireat(string $key, int $timestamp)
* @method array keys(string $pattern)
* @method int move(string $key, int $db)
* @method mixed object($subcommand, string $key)
* @method int persist(string $key)
* @method int pexpire(string $key, int $milliseconds)
* @method int pexpireat(string $key, int $timestamp)
* @method int pttl(string $key)
* @method string|null randomkey()
* @method mixed rename(string $key, string $target)
* @method int renamenx(string $key, string $target)
* @method array scan($cursor, array $options = null)
* @method array sort(string $key, array $options = null)
* @method int ttl(string $key)
* @method mixed type(string $key)
* @method int append(string $key, $value)
* @method int bitcount(string $key, $start = null, $end = null)
* @method int bitop($operation, $destkey, $key)
* @method array|null bitfield(string $key, $subcommand, ...$subcommandArg)
* @method int bitpos(string $key, $bit, $start = null, $end = null)
* @method int decr(string $key)
* @method int decrby(string $key, int $decrement)
* @method string|null get(string $key)
* @method int getbit(string $key, $offset)
* @method string getrange(string $key, $start, $end)
* @method string|null getset(string $key, $value)
* @method int incr(string $key)
* @method int incrby(string $key, int $increment)
* @method string incrbyfloat(string $key, int|float $increment)
* @method array mget(string[]|string $keyOrKeys, string ...$keys = null)
* @method mixed mset(array $dictionary)
* @method int msetnx(array $dictionary)
* @method Status psetex(string $key, $milliseconds, $value)
* @method Status set(string $key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
* @method int setbit(string $key, $offset, $value)
* @method Status setex(string $key, $seconds, $value)
* @method int setnx(string $key, $value)
* @method int setrange(string $key, $offset, $value)
* @method int strlen(string $key)
* @method int hdel(string $key, array $fields)
* @method int hexists(string $key, string $field)
* @method string|null hget(string $key, string $field)
* @method array hgetall(string $key)
* @method int hincrby(string $key, string $field, int $increment)
* @method string hincrbyfloat(string $key, string $field, int|float $increment)
* @method array hkeys(string $key)
* @method int hlen(string $key)
* @method array hmget(string $key, array $fields)
* @method mixed hmset(string $key, array $dictionary)
* @method array hscan(string $key, $cursor, array $options = null)
* @method int hset(string $key, string $field, string $value)
* @method int hsetnx(string $key, string $field, string $value)
* @method array hvals(string $key)
* @method int hstrlen(string $key, string $field)
* @method array|null blpop(array|string $keys, int|float $timeout)
* @method array|null brpop(array|string $keys, int|float $timeout)
* @method string|null brpoplpush(string $source, string $destination, int|float $timeout)
* @method string|null lindex(string $key, int $index)
* @method int linsert(string $key, $whence, $pivot, $value)
* @method int llen(string $key)
* @method string|null lpop(string $key)
* @method int lpush(string $key, array $values)
* @method int lpushx(string $key, array $values)
* @method string[] lrange(string $key, int $start, int $stop)
* @method int lrem(string $key, int $count, string $value)
* @method mixed lset(string $key, int $index, string $value)
* @method mixed ltrim(string $key, int $start, int $stop)
* @method string|null rpop(string $key)
* @method string|null rpoplpush(string $source, string $destination)
* @method int rpush(string $key, array $values)
* @method int rpushx(string $key, array $values)
* @method int sadd(string $key, array $members)
* @method int scard(string $key)
* @method string[] sdiff(array|string $keys)
* @method int sdiffstore(string $destination, array|string $keys)
* @method string[] sinter(array|string $keys)
* @method int sinterstore(string $destination, array|string $keys)
* @method int sismember(string $key, string $member)
* @method string[] smembers(string $key)
* @method int smove(string $source, string $destination, string $member)
* @method string|null spop(string $key, int $count = null)
* @method string|null srandmember(string $key, int $count = null)
* @method int srem(string $key, string $member)
* @method array sscan(string $key, int $cursor, array $options = null)
* @method string[] sunion(array|string $keys)
* @method int sunionstore(string $destination, array|string $keys)
* @method int touch(string[]|string $keyOrKeys, string ...$keys = null)
* @method int zadd(string $key, array $membersAndScoresDictionary)
* @method int zcard(string $key)
* @method string zcount(string $key, int|string $min, int|string $max)
* @method string zincrby(string $key, int $increment, string $member)
* @method int zinterstore(string $destination, array|string $keys, array $options = null)
* @method array zpopmin(string $key, int $count = 1)
* @method array zpopmax(string $key, int $count = 1)
* @method array zrange(string $key, int|string $start, int|string $stop, array $options = null)
* @method array zrangebyscore(string $key, int|string $min, int|string $max, array $options = null)
* @method int|null zrank(string $key, string $member)
* @method int zrem(string $key, string ...$member)
* @method int zremrangebyrank(string $key, int|string $start, int|string $stop)
* @method int zremrangebyscore(string $key, int|string $min, int|string $max)
* @method array zrevrange(string $key, int|string $start, int|string $stop, array $options = null)
* @method array zrevrangebyscore(string $key, int|string $max, int|string $min, array $options = null)
* @method int|null zrevrank(string $key, string $member)
* @method int zunionstore(string $destination, array|string $keys, array $options = null)
* @method string|null zscore(string $key, string $member)
* @method array zscan(string $key, int $cursor, array $options = null)
* @method array zrangebylex(string $key, string $start, string $stop, array $options = null)
* @method array zrevrangebylex(string $key, string $start, string $stop, array $options = null)
* @method int zremrangebylex(string $key, string $min, string $max)
* @method int zlexcount(string $key, string $min, string $max)
* @method int pfadd(string $key, array $elements)
* @method mixed pfmerge(string $destinationKey, array|string $sourceKeys)
* @method int pfcount(string[]|string $keyOrKeys, string ...$keys = null)
* @method mixed pubsub($subcommand, $argument)
* @method int publish($channel, $message)
* @method mixed discard()
* @method array|null exec()
* @method mixed multi()
* @method mixed unwatch()
* @method mixed watch(string $key)
* @method mixed eval(string $script, int $numkeys, string ...$keyOrArg = null)
* @method mixed evalsha(string $script, int $numkeys, string ...$keyOrArg = null)
* @method mixed script($subcommand, $argument = null)
* @method mixed auth(string $password)
* @method string echo(string $message)
* @method mixed ping(string $message = null)
* @method mixed select(int $database)
* @method mixed bgrewriteaof()
* @method mixed bgsave()
* @method mixed client($subcommand, $argument = null)
* @method mixed config($subcommand, $argument = null)
* @method int dbsize()
* @method mixed flushall()
* @method mixed flushdb()
* @method array info($section = null)
* @method int lastsave()
* @method mixed save()
* @method mixed slaveof(string $host, int $port)
* @method mixed slowlog($subcommand, $argument = null)
* @method array time()
* @method array command()
* @method int geoadd(string $key, $longitude, $latitude, $member)
* @method array geohash(string $key, array $members)
* @method array geopos(string $key, array $members)
* @method string|null geodist(string $key, $member1, $member2, $unit = null)
* @method array georadius(string $key, $longitude, $latitude, $radius, $unit, array $options = null)
* @method array georadiusbymember(string $key, $member, $radius, $unit, array $options = null)
* @method int copy(string $source, string $destination, int $db = -1, bool $replace = false)
* @method int del(string[]|string $keyOrKeys, string ...$keys = null)
* @method string|null dump(string $key)
* @method int exists(string $key)
* @method int expire(string $key, int $seconds, string $expireOption = '')
* @method int expireat(string $key, int $timestamp, string $expireOption = '')
* @method int expiretime(string $key)
* @method array keys(string $pattern)
* @method int move(string $key, int $db)
* @method mixed object($subcommand, string $key)
* @method int persist(string $key)
* @method int pexpire(string $key, int $milliseconds)
* @method int pexpireat(string $key, int $timestamp)
* @method int pttl(string $key)
* @method string|null randomkey()
* @method mixed rename(string $key, string $target)
* @method int renamenx(string $key, string $target)
* @method array scan($cursor, ?array $options = null)
* @method array sort(string $key, ?array $options = null)
* @method array sort_ro(string $key, ?string $byPattern = null, ?LimitOffsetCount $limit = null, array $getPatterns = [], ?string $sorting = null, bool $alpha = false)
* @method int ttl(string $key)
* @method mixed type(string $key)
* @method int append(string $key, $value)
* @method int bfadd(string $key, $item)
* @method int bfexists(string $key, $item)
* @method array bfinfo(string $key, string $modifier = '')
* @method array bfinsert(string $key, int $capacity = -1, float $error = -1, int $expansion = -1, bool $noCreate = false, bool $nonScaling = false, string ...$item)
* @method Status bfloadchunk(string $key, int $iterator, $data)
* @method array bfmadd(string $key, ...$item)
* @method array bfmexists(string $key, ...$item)
* @method Status bfreserve(string $key, float $errorRate, int $capacity, int $expansion = -1, bool $nonScaling = false)
* @method array bfscandump(string $key, int $iterator)
* @method int bitcount(string $key, $start = null, $end = null, string $index = 'byte')
* @method int bitop($operation, $destkey, $key)
* @method array|null bitfield(string $key, $subcommand, ...$subcommandArg)
* @method array|null bitfield_ro(string $key, ?array $encodingOffsetMap = null)
* @method int bitpos(string $key, $bit, $start = null, $end = null, string $index = 'byte')
* @method array blmpop(int $timeout, array $keys, string $modifier = 'left', int $count = 1)
* @method array bzpopmax(array $keys, int $timeout)
* @method array bzpopmin(array $keys, int $timeout)
* @method array bzmpop(int $timeout, array $keys, string $modifier = 'min', int $count = 1)
* @method int cfadd(string $key, $item)
* @method int cfaddnx(string $key, $item)
* @method int cfcount(string $key, $item)
* @method int cfdel(string $key, $item)
* @method int cfexists(string $key, $item)
* @method Status cfloadchunk(string $key, int $iterator, $data)
* @method int cfmexists(string $key, ...$item)
* @method array cfinfo(string $key)
* @method array cfinsert(string $key, int $capacity = -1, bool $noCreate = false, string ...$item)
* @method array cfinsertnx(string $key, int $capacity = -1, bool $noCreate = false, string ...$item)
* @method Status cfreserve(string $key, int $capacity, int $bucketSize = -1, int $maxIterations = -1, int $expansion = -1)
* @method array cfscandump(string $key, int $iterator)
* @method array cmsincrby(string $key, string|int ...$itemIncrementDictionary)
* @method array cmsinfo(string $key)
* @method Status cmsinitbydim(string $key, int $width, int $depth)
* @method Status cmsinitbyprob(string $key, float $errorRate, float $probability)
* @method Status cmsmerge(string $destination, array $sources, array $weights = [])
* @method array cmsquery(string $key, string ...$item)
* @method int decr(string $key)
* @method int decrby(string $key, int $decrement)
* @method Status failover(?To $to = null, bool $abort = false, int $timeout = -1)
* @method mixed fcall(string $function, array $keys, ...$args)
* @method mixed fcall_ro(string $function, array $keys, ...$args)
* @method array ft_list()
* @method array ftaggregate(string $index, string $query, ?AggregateArguments $arguments = null)
* @method Status ftaliasadd(string $alias, string $index)
* @method Status ftaliasdel(string $alias)
* @method Status ftaliasupdate(string $alias, string $index)
* @method Status ftalter(string $index, FieldInterface[] $schema, ?AlterArguments $arguments = null)
* @method Status ftcreate(string $index, FieldInterface[] $schema, ?CreateArguments $arguments = null)
* @method int ftdictadd(string $dict, ...$term)
* @method int ftdictdel(string $dict, ...$term)
* @method array ftdictdump(string $dict)
* @method Status ftdropindex(string $index, ?DropArguments $arguments = null)
* @method string ftexplain(string $index, string $query, ?ExplainArguments $arguments = null)
* @method array ftinfo(string $index)
* @method array ftprofile(string $index, ProfileArguments $arguments)
* @method array ftsearch(string $index, string $query, ?SearchArguments $arguments = null)
* @method array ftspellcheck(string $index, string $query, ?SearchArguments $arguments = null)
* @method int ftsugadd(string $key, string $string, float $score, ?SugAddArguments $arguments = null)
* @method int ftsugdel(string $key, string $string)
* @method array ftsugget(string $key, string $prefix, ?SugGetArguments $arguments = null)
* @method int ftsuglen(string $key)
* @method array ftsyndump(string $index)
* @method Status ftsynupdate(string $index, string $synonymGroupId, ?SynUpdateArguments $arguments = null, string ...$terms)
* @method array fttagvals(string $index, string $fieldName)
* @method string|null get(string $key)
* @method int getbit(string $key, $offset)
* @method int|null getex(string $key, $modifier = '', $value = false)
* @method string getrange(string $key, $start, $end)
* @method string getdel(string $key)
* @method string|null getset(string $key, $value)
* @method int incr(string $key)
* @method int incrby(string $key, int $increment)
* @method string incrbyfloat(string $key, int|float $increment)
* @method array mget(string[]|string $keyOrKeys, string ...$keys = null)
* @method mixed mset(array $dictionary)
* @method int msetnx(array $dictionary)
* @method Status psetex(string $key, $milliseconds, $value)
* @method Status|null set(string $key, $value, $expireResolution = null, $expireTTL = null, $flag = null)
* @method int setbit(string $key, $offset, $value)
* @method Status setex(string $key, $seconds, $value)
* @method int setnx(string $key, $value)
* @method int setrange(string $key, $offset, $value)
* @method int strlen(string $key)
* @method int hdel(string $key, array $fields)
* @method int hexists(string $key, string $field)
* @method array|null hexpire(string $key, int $seconds, array $fields, string $flag = null)
* @method array|null hexpireat(string $key, int $unixTimeSeconds, array $fields, string $flag = null)
* @method array|null hexpiretime(string $key, array $fields)
* @method array|null hpersist(string $key, array $fields)
* @method array|null hpexpire(string $key, int $milliseconds, array $fields, string $flag = null)
* @method array|null hpexpireat(string $key, int $unixTimeMilliseconds, array $fields, string $flag = null)
* @method array|null hpexpiretime(string $key, array $fields)
* @method string|null hget(string $key, string $field)
* @method array|null hgetex(string $key, array $fields, string $modifier = HGETEX::NULL, int|bool $modifierValue = false)
* @method array hgetall(string $key)
* @method array hgetdel(string $key, array $fields)
* @method int hincrby(string $key, string $field, int $increment)
* @method string hincrbyfloat(string $key, string $field, int|float $increment)
* @method array hkeys(string $key)
* @method int hlen(string $key)
* @method array hmget(string $key, array $fields)
* @method mixed hmset(string $key, array $dictionary)
* @method array hrandfield(string $key, int $count = 1, bool $withValues = false)
* @method array hscan(string $key, $cursor, ?array $options = null)
* @method int hset(string $key, string $field, string $value)
* @method int hsetex(string $key, array $fieldValueMap, string $setModifier = HSETEX::SET_NULL, string $ttlModifier = HSETEX::TTL_NULL, int|bool $ttlModifierValue = false)
* @method int hsetnx(string $key, string $field, string $value)
* @method array|null httl(string $key, array $fields)
* @method array|null hpttl(string $key, array $fields)
* @method array hvals(string $key)
* @method int hstrlen(string $key, string $field)
* @method array jsonarrappend(string $key, string $path = '$', ...$value)
* @method array jsonarrindex(string $key, string $path, string $value, int $start = 0, int $stop = 0)
* @method array jsonarrinsert(string $key, string $path, int $index, string ...$value)
* @method array jsonarrlen(string $key, string $path = '$')
* @method array jsonarrpop(string $key, string $path = '$', int $index = -1)
* @method int jsonclear(string $key, string $path = '$')
* @method array jsonarrtrim(string $key, string $path, int $start, int $stop)
* @method int jsondel(string $key, string $path = '$')
* @method int jsonforget(string $key, string $path = '$')
* @method string jsonget(string $key, string $indent = '', string $newline = '', string $space = '', string ...$paths)
* @method string jsonnumincrby(string $key, string $path, int $value)
* @method Status jsonmerge(string $key, string $path, string $value)
* @method array jsonmget(array $keys, string $path)
* @method Status jsonmset(string ...$keyPathValue)
* @method array jsonobjkeys(string $key, string $path = '$')
* @method array jsonobjlen(string $key, string $path = '$')
* @method array jsonresp(string $key, string $path = '$')
* @method string jsonset(string $key, string $path, string $value, ?string $subcommand = null)
* @method array jsonstrappend(string $key, string $path, string $value)
* @method array jsonstrlen(string $key, string $path = '$')
* @method array jsontoggle(string $key, string $path)
* @method array jsontype(string $key, string $path = '$')
* @method string blmove(string $source, string $destination, string $where, string $to, int $timeout)
* @method array|null blpop(array|string $keys, int|float $timeout)
* @method array|null brpop(array|string $keys, int|float $timeout)
* @method string|null brpoplpush(string $source, string $destination, int|float $timeout)
* @method mixed lcs(string $key1, string $key2, bool $len = false, bool $idx = false, int $minMatchLen = 0, bool $withMatchLen = false)
* @method string|null lindex(string $key, int $index)
* @method int linsert(string $key, $whence, $pivot, $value)
* @method int llen(string $key)
* @method string lmove(string $source, string $destination, string $where, string $to)
* @method array|null lmpop(array $keys, string $modifier = 'left', int $count = 1)
* @method string|null lpop(string $key)
* @method int lpush(string $key, array $values)
* @method int lpushx(string $key, array $values)
* @method string[] lrange(string $key, int $start, int $stop)
* @method int lrem(string $key, int $count, string $value)
* @method mixed lset(string $key, int $index, string $value)
* @method mixed ltrim(string $key, int $start, int $stop)
* @method string|null rpop(string $key)
* @method string|null rpoplpush(string $source, string $destination)
* @method int rpush(string $key, array $values)
* @method int rpushx(string $key, array $values)
* @method int sadd(string $key, array $members)
* @method int scard(string $key)
* @method string[] sdiff(array|string $keys)
* @method int sdiffstore(string $destination, array|string $keys)
* @method string[] sinter(array|string $keys)
* @method int sintercard(array $keys, int $limit = 0)
* @method int sinterstore(string $destination, array|string $keys)
* @method int sismember(string $key, string $member)
* @method string[] smembers(string $key)
* @method array smismember(string $key, string ...$members)
* @method int smove(string $source, string $destination, string $member)
* @method string|array|null spop(string $key, ?int $count = null)
* @method string|null srandmember(string $key, ?int $count = null)
* @method int srem(string $key, array|string $member)
* @method array sscan(string $key, int $cursor, ?array $options = null)
* @method string[] sunion(array|string $keys)
* @method int sunionstore(string $destination, array|string $keys)
* @method int touch(string[]|string $keyOrKeys, string ...$keys = null)
* @method Status tdigestadd(string $key, float ...$value)
* @method array tdigestbyrank(string $key, int ...$rank)
* @method array tdigestbyrevrank(string $key, int ...$reverseRank)
* @method array tdigestcdf(string $key, int ...$value)
* @method Status tdigestcreate(string $key, int $compression = 0)
* @method array tdigestinfo(string $key)
* @method string tdigestmax(string $key)
* @method Status tdigestmerge(string $destinationKey, array $sourceKeys, int $compression = 0, bool $override = false)
* @method string[] tdigestquantile(string $key, float ...$quantile)
* @method string tdigestmin(string $key)
* @method array tdigestrank(string $key, float ...$value)
* @method Status tdigestreset(string $key)
* @method array tdigestrevrank(string $key, float ...$value)
* @method string tdigesttrimmed_mean(string $key, float $lowCutQuantile, float $highCutQuantile)
* @method array topkadd(string $key, ...$items)
* @method array topkincrby(string $key, ...$itemIncrement)
* @method array topkinfo(string $key)
* @method array topklist(string $key, bool $withCount = false)
* @method array topkquery(string $key, ...$items)
* @method Status topkreserve(string $key, int $topK, int $width = 8, int $depth = 7, float $decay = 0.9)
* @method int tsadd(string $key, int $timestamp, float $value, ?AddArguments $arguments = null)
* @method Status tsalter(string $key, ?TSAlterArguments $arguments = null)
* @method Status tscreate(string $key, ?TSCreateArguments $arguments = null)
* @method Status tscreaterule(string $sourceKey, string $destKey, string $aggregator, int $bucketDuration, int $alignTimestamp = 0)
* @method int tsdecrby(string $key, float $value, ?DecrByArguments $arguments = null)
* @method int tsdel(string $key, int $fromTimestamp, int $toTimestamp)
* @method Status tsdeleterule(string $sourceKey, string $destKey)
* @method array tsget(string $key, ?GetArguments $arguments = null)
* @method int tsincrby(string $key, float $value, ?IncrByArguments $arguments = null)
* @method array tsinfo(string $key, ?InfoArguments $arguments = null)
* @method array tsmadd(mixed ...$keyTimestampValue)
* @method array tsmget(MGetArguments $arguments, string ...$filterExpression)
* @method array tsmrange($fromTimestamp, $toTimestamp, MRangeArguments $arguments)
* @method array tsmrevrange($fromTimestamp, $toTimestamp, MRangeArguments $arguments)
* @method array tsqueryindex(string ...$filterExpression)
* @method array tsrange(string $key, $fromTimestamp, $toTimestamp, ?RangeArguments $arguments = null)
* @method array tsrevrange(string $key, $fromTimestamp, $toTimestamp, ?RangeArguments $arguments = null)
* @method string xadd(string $key, array $dictionary, string $id = '*', ?array $options = null)
* @method int xdel(string $key, string ...$id)
* @method int xlen(string $key)
* @method array xrevrange(string $key, string $end, string $start, ?int $count = null)
* @method array xrange(string $key, string $start, string $end, ?int $count = null)
* @method string xtrim(string $key, array|string $strategy, string $threshold, ?array $options = null)
* @method array|null xread(int $count = null, int $block = null, array $streams = null, string ...$id)
* @method int zadd(string $key, array $membersAndScoresDictionary)
* @method int zcard(string $key)
* @method string zcount(string $key, int|string $min, int|string $max)
* @method array zdiff(array $keys, bool $withScores = false)
* @method int zdiffstore(string $destination, array $keys)
* @method string zincrby(string $key, int $increment, string $member)
* @method int zintercard(array $keys, int $limit = 0)
* @method int zinterstore(string $destination, array $keys, int[] $weights = [], string $aggregate = 'sum')
* @method array zinter(array $keys, int[] $weights = [], string $aggregate = 'sum', bool $withScores = false)
* @method array zmpop(array $keys, string $modifier = 'min', int $count = 1)
* @method array zmscore(string $key, string ...$member)
* @method array zpopmin(string $key, int $count = 1)
* @method array zpopmax(string $key, int $count = 1)
* @method mixed zrandmember(string $key, int $count = 1, bool $withScores = false)
* @method array zrange(string $key, int|string $start, int|string $stop, ?array $options = null)
* @method array zrangebyscore(string $key, int|string $min, int|string $max, ?array $options = null)
* @method int zrangestore(string $destination, string $source, int|string $min, int|string $max, string|bool $by = false, bool $reversed = false, bool $limit = false, int $offset = 0, int $count = 0)
* @method int|null zrank(string $key, string $member)
* @method int zrem(string $key, string ...$member)
* @method int zremrangebyrank(string $key, int|string $start, int|string $stop)
* @method int zremrangebyscore(string $key, int|string $min, int|string $max)
* @method array zrevrange(string $key, int|string $start, int|string $stop, ?array $options = null)
* @method array zrevrangebyscore(string $key, int|string $max, int|string $min, ?array $options = null)
* @method int|null zrevrank(string $key, string $member)
* @method array zunion(array $keys, int[] $weights = [], string $aggregate = 'sum', bool $withScores = false)
* @method int zunionstore(string $destination, array $keys, int[] $weights = [], string $aggregate = 'sum')
* @method string|null zscore(string $key, string $member)
* @method array zscan(string $key, int $cursor, ?array $options = null)
* @method array zrangebylex(string $key, string $start, string $stop, ?array $options = null)
* @method array zrevrangebylex(string $key, string $start, string $stop, ?array $options = null)
* @method int zremrangebylex(string $key, string $min, string $max)
* @method int zlexcount(string $key, string $min, string $max)
* @method int pexpiretime(string $key)
* @method int pfadd(string $key, array $elements)
* @method mixed pfmerge(string $destinationKey, array|string $sourceKeys)
* @method int pfcount(string[]|string $keyOrKeys, string ...$keys = null)
* @method mixed pubsub($subcommand, $argument)
* @method int publish($channel, $message)
* @method mixed discard()
* @method array|null exec()
* @method mixed multi()
* @method mixed unwatch()
* @method array waitaof(int $numLocal, int $numReplicas, int $timeout)
* @method mixed watch(string[]|string $keyOrKeys)
* @method mixed eval(string $script, int $numkeys, string ...$keyOrArg = null)
* @method mixed eval_ro(string $script, array $keys, ...$argument)
* @method mixed evalsha(string $script, int $numkeys, string ...$keyOrArg = null)
* @method mixed evalsha_ro(string $sha1, array $keys, ...$argument)
* @method mixed script($subcommand, $argument = null)
* @method Status shutdown(?bool $noSave = null, bool $now = false, bool $force = false, bool $abort = false)
* @method mixed auth(string $password)
* @method string echo(string $message)
* @method mixed ping(?string $message = null)
* @method mixed select(int $database)
* @method mixed bgrewriteaof()
* @method mixed bgsave()
* @method mixed client($subcommand, $argument = null)
* @method mixed config($subcommand, $argument = null)
* @method int dbsize()
* @method mixed flushall()
* @method mixed flushdb()
* @method array info($section = null)
* @method int lastsave()
* @method mixed save()
* @method mixed slaveof(string $host, int $port)
* @method mixed slowlog($subcommand, $argument = null)
* @method array time()
* @method array command()
* @method int geoadd(string $key, $longitude, $latitude, $member)
* @method array geohash(string $key, array $members)
* @method array geopos(string $key, array $members)
* @method string|null geodist(string $key, $member1, $member2, $unit = null)
* @method array georadius(string $key, $longitude, $latitude, $radius, $unit, ?array $options = null)
* @method array georadiusbymember(string $key, $member, $radius, $unit, ?array $options = null)
* @method array geosearch(string $key, FromInterface $from, ByInterface $by, ?string $sorting = null, int $count = -1, bool $any = false, bool $withCoord = false, bool $withDist = false, bool $withHash = false)
* @method int geosearchstore(string $destination, string $source, FromInterface $from, ByInterface $by, ?string $sorting = null, int $count = -1, bool $any = false, bool $storeDist = false)
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* Container commands
* @property CLUSTER $cluster
* @property FunctionContainer $function
* @property FTCONFIG $ftconfig
* @property FTCURSOR $ftcursor
* @property JSONDEBUG $jsondebug
* @property ACL $acl
*
* @no-named-arguments
*/
interface ClientInterface
{
@@ -220,7 +426,7 @@ interface ClientInterface
*
* @return CommandInterface
*/
public function createCommand($method, $arguments = array());
public function createCommand($method, $arguments = []);
/**
* Executes the specified Redis command.
+78 -52
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,21 +12,17 @@
namespace Predis\Cluster;
use InvalidArgumentException;
use Predis\Command\CommandInterface;
use Predis\Command\ScriptCommand;
/**
* Common class implementing the logic needed to support clustering strategies.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
abstract class ClusterStrategy implements StrategyInterface
{
protected $commands;
/**
*
*/
public function __construct()
{
$this->commands = $this->getDefaultCommands();
@@ -38,10 +35,10 @@ abstract class ClusterStrategy implements StrategyInterface
*/
protected function getDefaultCommands()
{
$getKeyFromFirstArgument = array($this, 'getKeyFromFirstArgument');
$getKeyFromAllArguments = array($this, 'getKeyFromAllArguments');
$getKeyFromFirstArgument = [$this, 'getKeyFromFirstArgument'];
$getKeyFromAllArguments = [$this, 'getKeyFromAllArguments'];
return array(
return [
/* commands operating on the key space */
'EXISTS' => $getKeyFromAllArguments,
'DEL' => $getKeyFromAllArguments,
@@ -53,9 +50,10 @@ abstract class ClusterStrategy implements StrategyInterface
'PEXPIREAT' => $getKeyFromFirstArgument,
'TTL' => $getKeyFromFirstArgument,
'PTTL' => $getKeyFromFirstArgument,
'SORT' => array($this, 'getKeyFromSortCommand'),
'SORT' => [$this, 'getKeyFromSortCommand'],
'DUMP' => $getKeyFromFirstArgument,
'RESTORE' => $getKeyFromFirstArgument,
'FLUSHDB' => [$this, 'getFakeKey'],
/* commands operating on string values */
'APPEND' => $getKeyFromFirstArgument,
@@ -72,13 +70,13 @@ abstract class ClusterStrategy implements StrategyInterface
'INCRBYFLOAT' => $getKeyFromFirstArgument,
'SETBIT' => $getKeyFromFirstArgument,
'SETEX' => $getKeyFromFirstArgument,
'MSET' => array($this, 'getKeyFromInterleavedArguments'),
'MSETNX' => array($this, 'getKeyFromInterleavedArguments'),
'MSET' => [$this, 'getKeyFromInterleavedArguments'],
'MSETNX' => [$this, 'getKeyFromInterleavedArguments'],
'SETNX' => $getKeyFromFirstArgument,
'SETRANGE' => $getKeyFromFirstArgument,
'STRLEN' => $getKeyFromFirstArgument,
'SUBSTR' => $getKeyFromFirstArgument,
'BITOP' => array($this, 'getKeyFromBitOp'),
'BITOP' => [$this, 'getKeyFromBitOp'],
'BITCOUNT' => $getKeyFromFirstArgument,
'BITFIELD' => $getKeyFromFirstArgument,
@@ -89,9 +87,9 @@ abstract class ClusterStrategy implements StrategyInterface
'LPOP' => $getKeyFromFirstArgument,
'RPOP' => $getKeyFromFirstArgument,
'RPOPLPUSH' => $getKeyFromAllArguments,
'BLPOP' => array($this, 'getKeyFromBlockingListCommands'),
'BRPOP' => array($this, 'getKeyFromBlockingListCommands'),
'BRPOPLPUSH' => array($this, 'getKeyFromBlockingListCommands'),
'BLPOP' => [$this, 'getKeyFromBlockingListCommands'],
'BRPOP' => [$this, 'getKeyFromBlockingListCommands'],
'BRPOPLPUSH' => [$this, 'getKeyFromBlockingListCommands'],
'LPUSH' => $getKeyFromFirstArgument,
'LPUSHX' => $getKeyFromFirstArgument,
'RPUSH' => $getKeyFromFirstArgument,
@@ -122,7 +120,7 @@ abstract class ClusterStrategy implements StrategyInterface
'ZCARD' => $getKeyFromFirstArgument,
'ZCOUNT' => $getKeyFromFirstArgument,
'ZINCRBY' => $getKeyFromFirstArgument,
'ZINTERSTORE' => array($this, 'getKeyFromZsetAggregationCommands'),
'ZINTERSTORE' => [$this, 'getKeyFromZsetAggregationCommands'],
'ZRANGE' => $getKeyFromFirstArgument,
'ZRANGEBYSCORE' => $getKeyFromFirstArgument,
'ZRANK' => $getKeyFromFirstArgument,
@@ -133,7 +131,7 @@ abstract class ClusterStrategy implements StrategyInterface
'ZREVRANGEBYSCORE' => $getKeyFromFirstArgument,
'ZREVRANK' => $getKeyFromFirstArgument,
'ZSCORE' => $getKeyFromFirstArgument,
'ZUNIONSTORE' => array($this, 'getKeyFromZsetAggregationCommands'),
'ZUNIONSTORE' => [$this, 'getKeyFromZsetAggregationCommands'],
'ZSCAN' => $getKeyFromFirstArgument,
'ZLEXCOUNT' => $getKeyFromFirstArgument,
'ZRANGEBYLEX' => $getKeyFromFirstArgument,
@@ -163,17 +161,25 @@ abstract class ClusterStrategy implements StrategyInterface
'PFMERGE' => $getKeyFromAllArguments,
/* scripting */
'EVAL' => array($this, 'getKeyFromScriptingCommands'),
'EVALSHA' => array($this, 'getKeyFromScriptingCommands'),
'EVAL' => [$this, 'getKeyFromScriptingCommands'],
'EVALSHA' => [$this, 'getKeyFromScriptingCommands'],
'EVAL_RO' => [$this, 'getKeyFromScriptingCommands'],
'EVALSHA_RO' => [$this, 'getKeyFromScriptingCommands'],
/* server */
'INFO' => [$this, 'getFakeKey'],
/* commands performing geospatial operations */
'GEOADD' => $getKeyFromFirstArgument,
'GEOHASH' => $getKeyFromFirstArgument,
'GEOPOS' => $getKeyFromFirstArgument,
'GEODIST' => $getKeyFromFirstArgument,
'GEORADIUS' => array($this, 'getKeyFromGeoradiusCommands'),
'GEORADIUSBYMEMBER' => array($this, 'getKeyFromGeoradiusCommands'),
);
'GEORADIUS' => [$this, 'getKeyFromGeoradiusCommands'],
'GEORADIUSBYMEMBER' => [$this, 'getKeyFromGeoradiusCommands'],
/* cluster */
'CLUSTER' => [$this, 'getFakeKey'],
];
}
/**
@@ -198,7 +204,7 @@ abstract class ClusterStrategy implements StrategyInterface
* @param string $commandID Command ID.
* @param mixed $callback A valid callable object, or NULL to unset the handler.
*
* @throws \InvalidArgumentException
* @throws InvalidArgumentException
*/
public function setCommandHandler($commandID, $callback = null)
{
@@ -211,7 +217,7 @@ abstract class ClusterStrategy implements StrategyInterface
}
if (!is_callable($callback)) {
throw new \InvalidArgumentException(
throw new InvalidArgumentException(
'The argument must be a callable object or NULL.'
);
}
@@ -219,6 +225,16 @@ abstract class ClusterStrategy implements StrategyInterface
$this->commands[$commandID] = $callback;
}
/**
* Get fake key for commands with no key argument.
*
* @return string
*/
protected function getFakeKey(): string
{
return 'key';
}
/**
* Extracts the key from the first argument of a command instance.
*
@@ -243,9 +259,11 @@ abstract class ClusterStrategy implements StrategyInterface
{
$arguments = $command->getArguments();
if ($this->checkSameSlotForKeys($arguments)) {
return $arguments[0];
if (!$this->checkSameSlotForKeys($arguments)) {
return null;
}
return $arguments[0];
}
/**
@@ -259,15 +277,17 @@ abstract class ClusterStrategy implements StrategyInterface
protected function getKeyFromInterleavedArguments(CommandInterface $command)
{
$arguments = $command->getArguments();
$keys = array();
$keys = [];
for ($i = 0; $i < count($arguments); $i += 2) {
$keys[] = $arguments[$i];
}
if ($this->checkSameSlotForKeys($keys)) {
return $arguments[0];
if (!$this->checkSameSlotForKeys($keys)) {
return null;
}
return $arguments[0];
}
/**
@@ -286,7 +306,7 @@ abstract class ClusterStrategy implements StrategyInterface
return $firstKey;
}
$keys = array($firstKey);
$keys = [$firstKey];
for ($i = 1; $i < $argc; ++$i) {
if (strtoupper($arguments[$i]) === 'STORE') {
@@ -294,9 +314,11 @@ abstract class ClusterStrategy implements StrategyInterface
}
}
if ($this->checkSameSlotForKeys($keys)) {
return $firstKey;
if (!$this->checkSameSlotForKeys($keys)) {
return null;
}
return $firstKey;
}
/**
@@ -310,9 +332,11 @@ abstract class ClusterStrategy implements StrategyInterface
{
$arguments = $command->getArguments();
if ($this->checkSameSlotForKeys(array_slice($arguments, 0, count($arguments) - 1))) {
return $arguments[0];
if (!$this->checkSameSlotForKeys(array_slice($arguments, 0, count($arguments) - 1))) {
return null;
}
return $arguments[0];
}
/**
@@ -326,9 +350,11 @@ abstract class ClusterStrategy implements StrategyInterface
{
$arguments = $command->getArguments();
if ($this->checkSameSlotForKeys(array_slice($arguments, 1, count($arguments)))) {
return $arguments[1];
if (!$this->checkSameSlotForKeys(array_slice($arguments, 1, count($arguments)))) {
return null;
}
return $arguments[1];
}
/**
@@ -345,7 +371,7 @@ abstract class ClusterStrategy implements StrategyInterface
$startIndex = $command->getId() === 'GEORADIUS' ? 5 : 4;
if ($argc > $startIndex) {
$keys = array($arguments[0]);
$keys = [$arguments[0]];
for ($i = $startIndex; $i < $argc; ++$i) {
$argument = strtoupper($arguments[$i]);
@@ -354,10 +380,8 @@ abstract class ClusterStrategy implements StrategyInterface
}
}
if ($this->checkSameSlotForKeys($keys)) {
return $arguments[0];
} else {
return;
if (!$this->checkSameSlotForKeys($keys)) {
return null;
}
}
@@ -374,11 +398,13 @@ abstract class ClusterStrategy implements StrategyInterface
protected function getKeyFromZsetAggregationCommands(CommandInterface $command)
{
$arguments = $command->getArguments();
$keys = array_merge(array($arguments[0]), array_slice($arguments, 2, $arguments[1]));
$keys = array_merge([$arguments[0]], array_slice($arguments, 2, $arguments[1]));
if ($this->checkSameSlotForKeys($keys)) {
return $arguments[0];
if (!$this->checkSameSlotForKeys($keys)) {
return null;
}
return $arguments[0];
}
/**
@@ -390,15 +416,15 @@ abstract class ClusterStrategy implements StrategyInterface
*/
protected function getKeyFromScriptingCommands(CommandInterface $command)
{
if ($command instanceof ScriptCommand) {
$keys = $command->getKeys();
} else {
$keys = array_slice($args = $command->getArguments(), 2, $args[1]);
$keys = $command instanceof ScriptCommand
? $command->getKeys()
: array_slice($args = $command->getArguments(), 2, $args[1]);
if (!$keys || !$this->checkSameSlotForKeys($keys)) {
return null;
}
if ($keys && $this->checkSameSlotForKeys($keys)) {
return $keys[0];
}
return $keys[0];
}
/**
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -16,8 +17,6 @@ use Predis\Cluster\Hash\HashGeneratorInterface;
/**
* A distributor implements the logic to automatically distribute keys among
* several nodes for client-side sharding.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
interface DistributorInterface
{
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -11,11 +12,11 @@
namespace Predis\Cluster\Distributor;
use Exception;
/**
* Exception class that identifies empty rings.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class EmptyRingException extends \Exception
class EmptyRingException extends Exception
{
}
+8 -9
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -17,21 +18,19 @@ use Predis\Cluster\Hash\HashGeneratorInterface;
* This class implements an hashring-based distributor that uses the same
* algorithm of memcache to distribute keys in a cluster using client-side
* sharding.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* @author Lorenzo Castelli <lcastelli@gmail.com>
*/
class HashRing implements DistributorInterface, HashGeneratorInterface
{
const DEFAULT_REPLICAS = 128;
const DEFAULT_WEIGHT = 100;
public const DEFAULT_REPLICAS = 128;
public const DEFAULT_WEIGHT = 100;
private $ring;
private $ringKeys;
private $ringKeysCount;
private $replicas;
private $nodeHashCallback;
private $nodes = array();
private $nodes = [];
/**
* @param int $replicas Number of replicas in the ring.
@@ -53,10 +52,10 @@ class HashRing implements DistributorInterface, HashGeneratorInterface
{
// In case of collisions in the hashes of the nodes, the node added
// last wins, thus the order in which nodes are added is significant.
$this->nodes[] = array(
$this->nodes[] = [
'object' => $node,
'weight' => (int) $weight ?: $this::DEFAULT_WEIGHT,
);
];
$this->reset();
}
@@ -131,7 +130,7 @@ class HashRing implements DistributorInterface, HashGeneratorInterface
throw new EmptyRingException('Cannot initialize an empty hashring.');
}
$this->ring = array();
$this->ring = [];
$totalWeight = $this->computeTotalWeight();
$nodesCount = count($this->nodes);
+3 -4
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -15,13 +16,11 @@ namespace Predis\Cluster\Distributor;
* This class implements an hashring-based distributor that uses the same
* algorithm of libketama to distribute keys in a cluster using client-side
* sharding.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* @author Lorenzo Castelli <lcastelli@gmail.com>
*/
class KetamaRing extends HashRing
{
const DEFAULT_REPLICAS = 160;
public const DEFAULT_REPLICAS = 160;
/**
* @param mixed $nodeHashCallback Callback returning a string used to calculate the hash of nodes.
+4 -5
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -13,12 +14,10 @@ namespace Predis\Cluster\Hash;
/**
* Hash generator implementing the CRC-CCITT-16 algorithm used by redis-cluster.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class CRC16 implements HashGeneratorInterface
{
private static $CCITT_16 = array(
private static $CCITT_16 = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
@@ -51,7 +50,7 @@ class CRC16 implements HashGeneratorInterface
0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0,
);
];
/**
* {@inheritdoc}
+2 -3
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -14,8 +15,6 @@ namespace Predis\Cluster\Hash;
/**
* An hash generator implements the logic used to calculate the hash of a key to
* distribute operations among Redis nodes.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
interface HashGeneratorInterface
{
+3 -5
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -16,13 +17,10 @@ use Predis\NotSupportedException;
/**
* Hash generator implementing the CRC-CCITT-16 algorithm used by redis-cluster.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
* @deprecated 2.1.2
*/
class PhpiredisCRC16 implements HashGeneratorInterface
{
/**
*
*/
public function __construct()
{
if (!function_exists('phpiredis_utils_crc16')) {
+40
View File
@@ -0,0 +1,40 @@
<?php
/*
* This file is part of the Predis package.
*
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Cluster;
/**
* Represents the gap between slot ranges.
*/
class NullSlotRange extends SlotRange
{
public function __construct(int $start, int $end)
{
parent::__construct($start, $end, '');
}
/**
* {@inheritDoc}
*/
public function toArray(): array
{
return [];
}
/**
* {@inheritDoc}
*/
public function count(): int
{
return 0;
}
}
+4 -5
View File
@@ -3,7 +3,8 @@
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <suppakilla@gmail.com>
* (c) 2009-2020 Daniele Alessandri
* (c) 2021-2025 Till Krüss
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
@@ -16,17 +17,15 @@ use Predis\Cluster\Distributor\HashRing;
/**
* Default cluster strategy used by Predis to handle client-side sharding.
*
* @author Daniele Alessandri <suppakilla@gmail.com>
*/
class PredisStrategy extends ClusterStrategy
{
protected $distributor;
/**
* @param DistributorInterface $distributor Optional distributor instance.
* @param DistributorInterface|null $distributor Optional distributor instance.
*/
public function __construct(DistributorInterface $distributor = null)
public function __construct(?DistributorInterface $distributor = null)
{
parent::__construct();

Some files were not shown because too many files have changed in this diff Show More