├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── Dockerfile ├── LICENSE ├── README.md ├── composer.json ├── docker-compose.yml ├── docker-tests ├── docker-containers.sh ├── docker-tests.sh └── phpunit_docker.xml ├── docs └── JSON-COMMANDS.md ├── examples ├── commands.php └── usage.php ├── phpunit.xml ├── run-tests-docker.sh ├── src └── RedisJsonClient │ ├── Adapter │ ├── AdapterProvider.php │ ├── RedisClientAdapter.php │ └── RedisClientAdapterInterface.php │ ├── Client │ ├── ClientInterface.php │ ├── RedisJsonClient.php │ └── RedisJsonClientInterface.php │ ├── Command │ └── Traits │ │ ├── JsonCommandTrait.php │ │ └── JsonCommandTraitInterface.php │ ├── Connection │ └── ConnectionOptions.php │ ├── Encoder │ └── Traits │ │ ├── JsonEncoderTrait.php │ │ └── JsonEncoderTraitInterface.php │ ├── Enum │ ├── Connection.php │ ├── JsonCommands.php │ ├── Keys.php │ ├── Module.php │ ├── ResponseParser.php │ └── Version.php │ ├── Exception │ ├── ConnectionException.php │ ├── ConnectionOptionsException.php │ ├── InvalidRedisVersionException.php │ ├── RedisClientException.php │ ├── RedisJsonModuleNotInstalledException.php │ └── ResponseException.php │ ├── Factory │ ├── RedisJsonClientFactory.php │ └── RedisJsonClientFactoryInterface.php │ ├── Parser │ ├── ParserInterface.php │ └── Response │ │ ├── BaseJsonDecoderParser.php │ │ ├── DecodeArrayOfJson.php │ │ ├── DecodeFromJson.php │ │ ├── IntegerToBoolean.php │ │ └── OkToTrue.php │ └── Validator │ ├── RedisClientValidator.php │ └── RedisClientValidatorInterface.php └── tests ├── Integration ├── BaseTestIntegration.php └── Command │ ├── JsonArrayAppendCommandTest.php │ ├── JsonArrayIndexCommandTest.php │ ├── JsonArrayInsertCommandTest.php │ ├── JsonArrayLengthCommandTest.php │ ├── JsonArrayPopCommandTest.php │ ├── JsonArrayTrimCommandTest.php │ ├── JsonDelCommandTest.php │ ├── JsonGetAsRespCommandTest.php │ ├── JsonGetCommandTest.php │ ├── JsonIncrementNumByCommandTest.php │ ├── JsonMemoryUsageCommandTest.php │ ├── JsonMultiGetCommandTest.php │ ├── JsonMultiplyNumByCommandTest.php │ ├── JsonObjectKeysCommandTest.php │ ├── JsonObjectLengthCommandTest.php │ ├── JsonSetCommandTest.php │ ├── JsonStringAppendCommandTest.php │ ├── JsonStringLengthCommandTest.php │ └── JsonTypeCommandTest.php └── Unit ├── Adapter ├── AdapterProviderTest.php └── RedisClientAdapterTest.php ├── Client └── RedisJsonClientTest.php ├── Command ├── BaseTestJsonCommandTrait.php └── Traits │ ├── JsonArrayAppendCommandTest.php │ ├── JsonArrayIndexCommandTest.php │ ├── JsonArrayInsertCommandTest.php │ ├── JsonArrayLengthCommandTest.php │ ├── JsonArrayPopCommandTest.php │ ├── JsonArrayTrimCommandTest.php │ ├── JsonDeleteCommandTest.php │ ├── JsonForgetCommandTest.php │ ├── JsonGetAsRespCommandTest.php │ ├── JsonGetCommandTest.php │ ├── JsonIncrementNumByCommandTest.php │ ├── JsonMemoryUsageCommandTest.php │ ├── JsonMultiGetCommandTest.php │ ├── JsonMultiplyNumByCommandTest.php │ ├── JsonObjectKeysCommandTest.php │ ├── JsonObjectLengthCommandTest.php │ ├── JsonSetCommandTest.php │ ├── JsonStringAppendCommandTest.php │ ├── JsonStringLengthCommandTest.php │ └── JsonTypeCommandTest.php ├── Encoder └── Traits │ └── JsonEncoderTraitTest.php ├── Factory └── RedisJsonClientFactoryTest.php ├── Parser └── Response │ ├── DecodeArrayOfJsonTest.php │ ├── DecodeFromJsonTest.php │ ├── IntegerToBooleanTest.php │ └── OkToTrueTest.php └── Validator └── RedisClientValidatorTest.php /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /.idea/ 3 | /vendor/ 4 | composer.lock 5 | .phpunit.result.cache 6 | /docker-tests/.phpunit.result.cache -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: php 2 | 3 | cache: 4 | directories: 5 | - $HOME/.composer/cache/files 6 | 7 | php: 8 | - '7.2' 9 | 10 | services: 11 | - docker 12 | 13 | install: 14 | - printf "\n" | pecl install redis-5.0.1 15 | - composer self-update 16 | - composer clear-cache 17 | - composer install --prefer-dist 18 | 19 | before_install: 20 | - docker pull redislabs/rejson:1.0.4 21 | - docker run --name redislab-rejson -it -d -p 127.0.0.1:6379:6379 redislabs/rejson:1.0.4 22 | - docker ps -a 23 | 24 | before_script: 25 | - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter 26 | - chmod +x ./cc-test-reporter 27 | - ./cc-test-reporter before-build 28 | - mkdir -p build/coverage 29 | - mkdir -p build/logs 30 | 31 | script: 32 | - ./vendor/bin/phpunit 33 | 34 | after_script: 35 | - ./cc-test-reporter after-build --exit-code $TRAVIS_TEST_RESULT -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.4.0 - 2021-02-27 2 | 3 | - fixed wrong namespace for `Enum/Keys` 4 | 5 | ## 1.3.0 - 2020-01-24 6 | 7 | - removed `symplify/changelog-linker` changelog generator 8 | - changed Scrutinizer by CodeClimate 9 | 10 | ## 1.2.3 - 2020-01-24 11 | 12 | - fixed wrong namespace for `JsonCommandTraitInterface` 13 | 14 | ## 1.2.2 - 2019-12-01 15 | 16 | - added `symplify/changelog-linker` changelog generator 17 | 18 | ## 1.2.0/1 - 2019-11-26 19 | 20 | - fixed issues in travis config 21 | - removed deprecated setMethod in PhpUnit 22 | - added scrutinizer 23 | - added badgets to README.md 24 | 25 | ## 1.1.5 - 2019-11-23 26 | - fixed typo in header documentation 27 | - updated PhpUnit to version 8 28 | - add travis ci and changed redis database from 0 to 15 for integration tests 29 | 30 | ## 1.1.4 - 2019-11-14 31 | 32 | - fixed typo on header documentation 33 | - delete commented code 34 | 35 | ## 1.1.3 - 2019-11-11 36 | 37 | - removed invalid reference in phpunit.xml 38 | - small cleaning and refactoring 39 | - small changes in documentation 40 | 41 | ## 1.1.2 - 2019-11-10 42 | 43 | - restored previous ways to get redis info because of a bug 44 | 45 | ## 1.1.1 - 2019-11-10 46 | 47 | - fixed wrong namespaces 48 | 49 | ## 1.1.0 - 2019-11-09 50 | 51 | - fixed typos in current documentation 52 | - added php docker service and redisjson from redislab 53 | 54 | ## 1.0.1 - 2019-11-08 55 | 56 | - finished documentation and examples 57 | 58 | ## 1.0.0 - 2019-11-07 59 | 60 | - changed signature for Append String command and added some documents 61 | 62 | ## 0.1.x - 2019-11-07 63 | 64 | - first implementation 65 | - fixed typos in docs 66 | - fixed name package in composer.json -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM php:7.2-cli 2 | RUN pecl install redis-5.0.1 \ 3 | && pecl install xdebug-2.6.0 \ 4 | && docker-php-ext-enable redis xdebug 5 | 6 | RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer 7 | WORKDIR /app 8 | CMD ["/bin/bash", "-c", "sleep infinity"] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2019 Rafael Campoy 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 18 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 19 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Test Coverage](https://api.codeclimate.com/v1/badges/0139a26763ee4a0c3343/test_coverage)](https://codeclimate.com/github/averias/phpredis-json/test_coverage) 2 | [![Maintainability](https://api.codeclimate.com/v1/badges/0139a26763ee4a0c3343/maintainability)](https://codeclimate.com/github/averias/phpredis-json/maintainability) 3 | [![Build Status](https://travis-ci.org/averias/phpredis-json.svg?branch=master)](https://travis-ci.org/averias/phpredis-json) 4 | [![Packagist Version](https://img.shields.io/packagist/v/averias/phpredis-json.svg)](https://packagist.org/packages/averias/phpredis-json) 5 | [![GitHub](https://img.shields.io/github/license/averias/phpredis-json.svg)](https://github.com/averias/phpredis-json) 6 | 7 | # Phpredis-JSON 8 | RedisJson with the PHP Redis extension [phpredis](https://github.com/phpredis/phpredis). 9 | 10 | ## Intro 11 | Phpredis-JSON provides a full set of commands for [RedisJson Module](https://oss.redislabs.com/redisjson/). 12 | It's built on top of the `phpredis` and use it as Redis client, 13 | so you can also take advantage of some of the features included in `phpredis` as Redis client. 14 | 15 | ## Why? 16 | Although you can issue RedisJSON commands by using some PHP Redis clients which provides you the ability to send 17 | raw Redis commands, Phpredis-JSON: 18 | - avoids you the task of encoding your PHP data structures to JSON before sending them to Redis 19 | and decode the JSON responses back from Redis 20 | - it validates JSON encode/decode and throw a proper exception in case of failure 21 | - provides a set of commands as methods of the RedisJSON client 22 | 23 | ## Requirements 24 | - Redis server 4.0+ version (RedisJson Module is only available from Redis 4.0+) 25 | - RedisJson Module installed on Redis server as specified in [Building and loading RedisJSON Module](https://oss.redislabs.com/redisjson/#building-and-loading-the-module) 26 | - PHP 7.2+ with PHP Redis extension 5 installed 27 | 28 | ## Usage 29 | ```php 30 | '127.0.0.1', 42 | * 'port' => 6379, 43 | * 'timeout' => 0.0, // seconds 44 | * 'retryInterval' => 15 // milliseconds 45 | * 'readTimeout' => 2, // seconds 46 | * 'persistenceId' => null // string for persistent connections, null for no persistent ones 47 | * 'database' => 0 // Redis database index [0..15] 48 | * ] 49 | */ 50 | $defaultClient = $redisJsonClientFactory->createClient(); 51 | 52 | // creates a configured RedisJsonClient 53 | $client = $redisJsonClientFactory->createClient([ 54 | 'host' => '127.0.0.1', 55 | 'port' => 6390, 56 | 'timeout' => 2, 57 | 'database' => 15 58 | ]); 59 | 60 | // *** Redis JSON commands *** 61 | $result = $client->jsonSet('people', ["name" => "gafael", "age" => 12]); 62 | echo ($result === true ? 'true' : 'false') . PHP_EOL; // true 63 | 64 | $result = $client->jsonGet('people'); // $result = ["name":"gafael","age":12] 65 | echo json_encode($result) . PHP_EOL; // {"name":"gafael","age":12} 66 | 67 | $result = $client->jsonGet('people', '.name'); 68 | echo $result . PHP_EOL; // "gafael" 69 | 70 | $result = $client->jsonGet('people', '.age'); 71 | echo $result . PHP_EOL; // 12 72 | 73 | // "nonexistent" key does not exist, so a ResponseException is thrown 74 | try { 75 | $result = $client->jsonGet('nonexistent'); 76 | echo $result . PHP_EOL; 77 | } catch (ResponseException $e) { 78 | echo "key nonexistent does not exist" . PHP_EOL; 79 | } 80 | 81 | // *** you can also send RedisJSON command as raw commands using "RedisJsonClient::executeRawCommand" *** 82 | // you will send 83 | $result = $client->executeRawCommand(JsonCommands::SET, 'people', '.colors', '["blue", "green"]'); 84 | echo $result . PHP_EOL; // 'OK' 85 | 86 | // and receive JSON values 87 | $result = $client->executeRawCommand(JsonCommands::GET, 'people', '.'); 88 | echo $result . PHP_EOL; // {"name":"gafael","age":12,"colors":["blue","green"]} 89 | 90 | 91 | // *** you can also issue redis commands and use RedisJsonClient as "phpredis" client: 92 | echo $client->hset('hash-key', 'age', 34) . PHP_EOL; // 0 93 | echo $client->hget('hash-key', 'age') . PHP_EOL; // 34 94 | 95 | // $ret = [true,"val1",true,"val2"] 96 | $ret = $client->multi() 97 | ->set('key1', 'val1') 98 | ->get('key1') 99 | ->set('key2', 'val2') 100 | ->get('key2') 101 | ->exec(); 102 | 103 | echo json_encode($ret) . PHP_EOL; 104 | 105 | ``` 106 | 107 | ## Commands 108 | - **RedisJSON commands:** please take a look to the list of [phpredis-json commands](https://github.com/averias/phpredis-json/blob/master/docs/JSON-COMMANDS.md) 109 | - **Phpredis commands:** you can send Redis commands as specified in [phpredis documentation](https://github.com/phpredis/phpredis#table-of-contents) 110 | - **Raw commands:** you can send whatever you want to Redis by using `RedisJsonClient::executeRawCommand`: 111 | ```php 112 | // raw Redis JSON command 113 | $client->executeRawCommand(JsonCommands::GET, 'people', '.'); 114 | 115 | // raw Redis command 116 | $client->executeRawCommand('hget, 'hash-key', 'foo'); 117 | ``` 118 | 119 | ## Tests 120 | #### On a local Redis server 4.0+ with RedisJSON module and Redis extension 5 installed 121 | From console run the following command from the root directory of this project: 122 | 123 | `./vendor/bin/phpunit` 124 | 125 | if you don't have configured your local Redis server in 127.0.0.1:6379 you can set REDIS_TEST_SERVER and REDIS_TEST_PORT 126 | and REDIS_TEST_DATABASE in `./phpunit.xml` file with your local Redis host, port and database before running the above 127 | command. 128 | 129 | #### Docker 130 | Having Docker installed, run the following command in the root directory of this project: 131 | 132 | `bash run-tests-docker.sh` 133 | 134 | by running the above bash script, two docker services will be built, one with PHP 7.2 with xdebug and redis extensions 135 | enabled and another with the image of `redislab\rejson:1.0.4` (Redis server 5 with RedisJson module installed). 136 | Then the tests will run inside `phpredis-json` docker service container and finally both container will be stopped. 137 | 138 | ## Examples 139 | - [Usage](https://github.com/averias/phpredis-json/blob/master/examples/usage.php) 140 | - [Commands](https://github.com/averias/phpredis-json/blob/master/examples/commands.php) 141 | 142 | ## License 143 | Phpredis-Json code is distributed under MIT license, see [LICENSE](https://github.com/averias/phpredis-json/blob/master/LICENSE) 144 | file 145 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "averias/phpredis-json", 3 | "description": "A PHP client for RedisJSON module using phpredis extension", 4 | "homepage": "https://github.com/averias/phpredis-json", 5 | "keywords": [ 6 | "redis", 7 | "redisjson", 8 | "rejson", 9 | "php" 10 | ], 11 | "license": "MIT", 12 | "authors": [ 13 | { 14 | "name": "Rafael Campoy Villalta", 15 | "email": "rafa.campoy@gmail.com" 16 | } 17 | ], 18 | "require": { 19 | "php": "^7.2", 20 | "ext-redis": "^5.0.1", 21 | "ext-json": "*", 22 | "myclabs/php-enum": "^1.7" 23 | }, 24 | "require-dev": { 25 | "phpunit/phpunit": "^8.4", 26 | "squizlabs/php_codesniffer": "^3.5.0" 27 | }, 28 | "autoload": { 29 | "psr-4": { 30 | "Averias\\RedisJson\\": "src/RedisJsonClient" 31 | } 32 | }, 33 | "autoload-dev": { 34 | "psr-4": { 35 | "Averias\\RedisJson\\Tests\\": "tests" 36 | } 37 | }, 38 | "config": { 39 | "optimize-autoloader": true 40 | }, 41 | "scripts": { 42 | "manifest": [ 43 | "@composer validate" 44 | ], 45 | "autoload": [ 46 | "@composer dump-autoload --optimize" 47 | ], 48 | "run-tests": [ 49 | "@manifest", 50 | "@autoload", 51 | "vendor/bin/phpunit" 52 | ], 53 | "git-reset": [ 54 | "git reset --hard" 55 | ], 56 | "update-all": [ 57 | "@composer self-update --no-interaction", 58 | "@composer update --optimize-autoloader --no-interaction" 59 | ] 60 | } 61 | } -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3" 2 | 3 | services: 4 | php: 5 | container_name: phpredis-json 6 | build: 7 | dockerfile: Dockerfile 8 | context: . 9 | volumes: 10 | - .:/app 11 | redisjson: 12 | container_name: redislab-rejson 13 | image: redislabs/rejson:1.0.4 -------------------------------------------------------------------------------- /docker-tests/docker-containers.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | docker-compose up --build -d 4 | docker exec -i phpredis-json bash < ./docker-tests/docker-tests.sh 5 | docker stop redislab-rejson 6 | docker stop phpredis-json -------------------------------------------------------------------------------- /docker-tests/docker-tests.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | yel=$'\e[1;33m' 4 | blu=$'\e[1;34m' 5 | end=$'\e[0m' 6 | 7 | printf "\n${blu}*** Running test against Redis 4 docker service ***${end}\n\n" 8 | ./vendor/bin/phpunit --configuration ./docker-tests/phpunit_docker.xml 9 | -------------------------------------------------------------------------------- /docker-tests/phpunit_docker.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | ../tests/Integration/ 17 | 18 | 19 | ../tests/Unit 20 | 21 | 22 | 23 | 24 | ../src/ 25 | 26 | ../src/RedisJsonClient/Exception 27 | ../src/RedisJsonClient/Enum 28 | ../src/RedisJsonClient/Pipeline/Version 29 | ../src/ 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /docs/JSON-COMMANDS.md: -------------------------------------------------------------------------------- 1 | # Phpredis-JSON Commands 2 | Take a look at [command.php](https://github.com/averias/phpredis-json/blob/master/examples/commands.php) where you could 3 | find examples of the different commands. If you want to execute it you will need a Redis server 4.0+ in 127.0.0.1:6379 4 | with [RedisJSON module](https://oss.redislabs.com/redisjson/#building-and-loading-the-module) installed. 5 | 6 | You can also take a look at the tests, especially Integration tests. to get a better knowledge of how the different 7 | commands work. 8 | 9 | ## `Array Commands` 10 | 11 | ### `Array Append` 12 | It appends one or more items to the array specified in `path`. 13 | 14 | `jsonArrayAppend(string $key, string $path, ...$values);` 15 | 16 | **Returns:** The length of the new array (int). 17 | 18 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, no `values` are provided or we try to append 19 | item(s) in a no array. 20 | 21 | ### `Array Index` 22 | It returns the index of one `value` in the array specified in `path`. 23 | By providing `start` and `stop` params we get a slice from the original array: 24 | - if `start` or `stop` params are negative integers they will be counted from the end of the array so if its absolute 25 | value for both is greater than the length of the array, that means: (abs(start|stop) > len(array), they will be set to 0 26 | - if `stop` is positive and greater than the length of the array, it will be set to the value of the length of the 27 | array, stop = len(array) 28 | - if `start` is positive and greater than the length of the array, the result will be an empty array 29 | - if `start` > `stop` the result will be an empty array 30 | 31 | `jsonArrayIndex(string $key, string $value, string $path = '.', int $start = 0, int $stop = 0);` 32 | 33 | **Returns:** The index value or -1 if the index was not found or was out of range (int). 34 | 35 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try this command on no arrays. 36 | 37 | ### `Array Insert` 38 | It inserts one or more items to the array specified in `path` in the `index` position. 39 | 40 | `jsonArrayInsert(string $key, string $path, int $index, ...$values);` 41 | 42 | **Returns:** The length of the new array (int). 43 | 44 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to insert item(s) in a no array. 45 | 46 | ### `Array Length` 47 | 48 | `jsonArrayLength(string $key, string $path = '.');` 49 | 50 | **Returns:** The length of the array specified in `path`. 51 | 52 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to get the length from a no array. 53 | 54 | ### `Array Pop` 55 | It removes one element from the array specified in `path` in the `index` position. By default `index` = -1, meaning the 56 | last element in the array. Negative indexes start counting from the end of the array, positive ones from the beginning. 57 | 58 | `jsonArrayPop(string $key, string $path = '.', int $index = -1);` 59 | 60 | **Returns:** The element removed from the array. 61 | 62 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, array is empty or we try to remove item(s) in a 63 | no array. 64 | 65 | ### `Array Trim` 66 | It trims the array specified in `path` from the `start` to `end` positions. Both positions have to be specified: 67 | - if `start` or `stop` params are negative integers they will be counted from the end of the array so if its absolute 68 | value for both is greater than the length of the array, that means: (abs(start|stop) > len(array), they will be set to 0, 69 | which will avoid throwing any error 70 | - if `stop` is positive and greater than the length of the array, it will be set to the value of the length of the array, 71 | stop = len(array) 72 | - if `start` is positive and greater than the length of the array, the result will be an empty array 73 | - if `start` > `stop` the result will be an empty array 74 | - if `start` or `stop` is equal to -1 it will consider at the last position in the array, value of -2 is 75 | the second-to-last position and so on 76 | 77 | `jsonArrayTrim(string $key, int $start, int $stop, string $path = '.');` 78 | 79 | **Returns:** The length of the new array after trimming. 80 | 81 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to trim in a no array. 82 | 83 | ## `Object Commands` 84 | 85 | ### `Object Keys` 86 | It returns an array containing all the key names in an object specified in `path`. 87 | 88 | `jsonObjectKeys(string $key, string $path = '.');` 89 | 90 | **Returns:** The array of keys in the object. For empty objects, it returns an empty array. 91 | 92 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to get the keys for a no object. 93 | 94 | ### `Object Length` 95 | 96 | `jsonObjectLength(string $key, string $path = '.');` 97 | 98 | **Returns:** Number of keys in an object specified in `path` (int). For empty objects, instead of returning 0, 99 | it throws an exception. 100 | 101 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, the object is empty or we try to get the keys for 102 | a no object. 103 | 104 | ## `String Commands` 105 | 106 | ### `String Append` 107 | It appends a `value` string to the existing string value in `path`. 108 | 109 | `jsonStringAppend(string $key, string $value, string $path = '.');` 110 | 111 | **Returns:** New length of the string. 112 | 113 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to append to a no string. 114 | 115 | ### `String Length` 116 | 117 | `jsonStringLength(string $key, string $path = '.');` 118 | 119 | **Returns:** Length of the string stored in `path`. 120 | 121 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist or we try to get the length from a no string. 122 | 123 | ## `General Commands` 124 | 125 | ### `Delete` 126 | It deletes the value stored in `path`. If `key` or `path` doesn't exist, this command doesn't throw an exception. 127 | If `path` is root (= '.'), `key` is deleted. 128 | 129 | `jsonDelete(string $key, string $path = '.');` 130 | 131 | **Returns:** True, otherwise false. 132 | 133 | ### `Get` 134 | It returns the value stored in `paths`. More than one path can be specified in this command, by providing and array of 135 | key names. This command doesn't provide some of the features includes in [JSON.GET command in ReJson](https://oss.redislabs.com/redisjson/commands/#jsonget), 136 | like IDENT, NEWLINE, etc. The reason is that `phpredis-json` was created with the intent to return PHP data structures 137 | instead of JSON strings, so it doesn't make sense to include params to render the JSON string. Anyway if you still 138 | want to get values as rendered JSON string, you can use `RedisJsonClient::executeRawCommand('JSON.GET', ...$params)` 139 | where you can include the `$params` as specified in the link above. 140 | 141 | 142 | `jsonGet(string $key, string ...$paths);` 143 | 144 | **Returns:** If more than 2 `path(s)` are specified, it returns an array whose `key` is the `path` (with dot prefix, 145 | like '.colors') and the value the data stored in that `path`, otherwise, by providing just one `path`, returns the value 146 | stored in that path. 147 | 148 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist. 149 | 150 | ### `Get As RESP (Redis Serialization Protocol)` 151 | It returns the [Redis Serialization Protocol (RESP)](https://redis.io/topics/protocol) of a value stored in `path`. 152 | See [JSON.RESP](https://oss.redislabs.com/redisjson/commands/#jsonresp) for more info. 153 | 154 | `jsonGetAsResp(string $key, string $path = '.');` 155 | 156 | **Returns:** An array with the RESP of the data stored in the `path` 157 | 158 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist. 159 | 160 | ### `Increment Num By` 161 | It increments the value stored in `path` by a `number` (int or float). 162 | 163 | `jsonIncrementNumBy(string $key, $number, string $path = '.');` 164 | 165 | **Returns:** The result of the arithmetic operation (int or float). 166 | 167 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, we try to increment by a number which cannot be 168 | cast to int or float or we try to increment a NO int|float value stored in `path`. 169 | 170 | ### `Multiply Num By` 171 | It multiplies the value stored in `path` by a `number` (int or float). 172 | 173 | `jsonMultiplyNumBy(string $key, $number, string $path = '.');` 174 | 175 | **Returns:** The result of the arithmetic operation (int or float). 176 | 177 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, we try to multiply by a number which cannot be 178 | cast to int or float or we try to multiply a NO int|float value stored in `path`. 179 | 180 | ### `Memory Usage` 181 | It returns the memory used for the value stored in `path`. 182 | 183 | `jsonMemoryUsage(string $key, string $path = '.');` 184 | 185 | **Returns:** Bytes of memory used (int). 186 | 187 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist. 188 | 189 | ### `MultiGet` 190 | It returns the values stored in `path` for each `key` provided in the `$key` array param. 191 | 192 | `jsonMultiGet(array $keys, string $path = '.');` 193 | 194 | **Returns:** An array where the first element contains the data of `path` for the first key provided, the second element 195 | contains the data of `path` for the second `key` provided and so on. If a `key` doesn't exists it will return NULL in 196 | the position of the array. If `path` does not exist, it still returns an array where all the values are NULL. 197 | 198 | **Exceptions:** NO exceptions are thrown when `key` or `path` does not exist. 199 | 200 | ### `Set` 201 | It sets/updates a value in `path` and `key`. For a complete description of this command please visit 202 | [JSON.SET in RedisJson Documentation](https://oss.redislabs.com/redisjson/commands/#jsonset). 203 | 204 | `jsonSet(string $key, $value, string $path = '.', ?string $keyOptions = null);` 205 | 206 | **Returns:** True if the command was successfully executed. 207 | 208 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist, `path` is not roo ('.'') for new `keys` or the 209 | specified `NX` or `XX` conditions (if any) were not met. 210 | 211 | ### `Type` 212 | 213 | `jsonType(string $key, string $path = '.');` 214 | 215 | **Returns:** It returns the data type of the value stored in `path` (string). You can find the following data types: 216 | - string 217 | - integer 218 | - number 219 | - object 220 | - array 221 | - boolean 222 | 223 | **Exceptions:** `ResponseException` if `key` or `path` doesn't exist. 224 | -------------------------------------------------------------------------------- /examples/commands.php: -------------------------------------------------------------------------------- 1 | 5 | * @copyright 2019 Rafael Campoy 6 | * @license MIT 7 | * @link https://github.com/averias/phpredis-json 8 | * 9 | * Copyright and license information, is included in 10 | * the LICENSE file that is distributed with this source code. 11 | */ 12 | 13 | namespace Examples; 14 | 15 | require(dirname(__DIR__) . '/vendor/autoload.php'); 16 | 17 | use Averias\RedisJson\Client\RedisJsonClient; 18 | use Averias\RedisJson\Factory\RedisJsonClientFactory; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | /** @var RedisJsonClientFactory $redisJsonClientFactory */ 22 | $redisJsonClientFactory = new RedisJsonClientFactory(); 23 | 24 | /** @var RedisJsonClient $defaultClient */ 25 | $client = $redisJsonClientFactory->createClient([ 26 | 'database' => 15 27 | ]); 28 | 29 | // create a constant for the key name 30 | const OBJECT_KEY = 'test-object'; 31 | const SECONDARY = 'secondary-test-object'; 32 | const COLORS_KEY = '.colors'; 33 | 34 | /** 35 | * store default data 36 | * [ 37 | * 'name' => 'Peter', 38 | * 'age' => 38, 39 | * 'height' => 1.79, 40 | * 'location' => [ 41 | * 'address' => 'Pub Street, 39', 42 | * 'city' => 'Limerick', 43 | * 'country' => 'Ireland' 44 | * ], 45 | * 'colors' => ['white', 'black'], 46 | * 'license' => true 47 | * ]; 48 | */ 49 | 50 | 51 | $client->jsonSet(OBJECT_KEY, BaseTestIntegration::$defaultData); 52 | 53 | echo sprintf("*** Added object to '%s' key: %s", OBJECT_KEY, PHP_EOL); 54 | echo json_encode($client->jsonGet(OBJECT_KEY)) . PHP_EOL . PHP_EOL; 55 | 56 | // append to array 57 | $result = $client->jsonArrayAppend(OBJECT_KEY, COLORS_KEY, 'blue', 'white'); 58 | echo sprintf("*** Appended colors 'blue' and 'white' to '.colors' path %s", PHP_EOL); 59 | echo sprintf("array after appending: %s %s", json_encode($client->jsonGet(OBJECT_KEY, COLORS_KEY), true), PHP_EOL); 60 | echo sprintf("new length of the array: %d %s", $result, PHP_EOL . PHP_EOL); 61 | 62 | // insert into array 63 | $result = $client->jsonArrayInsert(OBJECT_KEY, COLORS_KEY, 3, 'green'); 64 | echo sprintf("*** Inserted color 'green' into '.colors' path in position (index) 3 %s", PHP_EOL); 65 | echo sprintf("array after inserting: %s %s", json_encode($client->jsonGet(OBJECT_KEY, COLORS_KEY), true), PHP_EOL); 66 | echo sprintf("new length of the array: %d %s", $result, PHP_EOL . PHP_EOL); 67 | 68 | // get the index of one element in a array 69 | $result = $client->jsonArrayIndex(OBJECT_KEY, 'white', COLORS_KEY); 70 | echo sprintf("*** Index of color 'white' (duplicated) when searching from the beginning %s", PHP_EOL); 71 | echo sprintf("index of 'white' color : %d %s", $result, PHP_EOL . PHP_EOL); 72 | $result = $client->jsonArrayIndex(OBJECT_KEY, 'white', COLORS_KEY, -3); 73 | echo sprintf("*** Index of color 'white' (duplicated) when searching from the end %s", PHP_EOL); 74 | echo sprintf("index of 'white' color : %d %s", $result, PHP_EOL . PHP_EOL); 75 | 76 | // remove element from array 77 | $result = $client->jsonArrayPop(OBJECT_KEY, COLORS_KEY); 78 | echo sprintf("*** Removed last element in '.colors' path %s", PHP_EOL); 79 | echo sprintf("removed element: %s %s", $result, PHP_EOL . PHP_EOL); 80 | $result = $client->jsonArrayPop(OBJECT_KEY, COLORS_KEY, 2); 81 | echo sprintf("*** Removed element in index 2 in '.colors' path %s", PHP_EOL); 82 | echo sprintf("removed element: %s %s", $result, PHP_EOL); 83 | 84 | // length of the array 85 | $result = $client->jsonArrayLength(OBJECT_KEY, COLORS_KEY); 86 | echo sprintf("new length of the array after popping it: %s %s", $result, PHP_EOL); 87 | echo sprintf("array after popping: %s %s", json_encode($client->jsonGet(OBJECT_KEY, COLORS_KEY), true), PHP_EOL . PHP_EOL); 88 | 89 | // trim array 90 | $result = $client->jsonArrayTrim(OBJECT_KEY, 1, 2, COLORS_KEY); 91 | echo sprintf("*** Trim array in '.colors' path from index 1 to 2 %s", PHP_EOL); 92 | echo sprintf("new length of the array after trimming: %s %s", $result, PHP_EOL); 93 | echo sprintf("array after trimming: %s %s", json_encode($client->jsonGet(OBJECT_KEY, COLORS_KEY), true), PHP_EOL . PHP_EOL); 94 | 95 | // get keys of a object as array 96 | $result = $client->jsonObjectKeys(OBJECT_KEY); // by default path = '.' (root path) 97 | echo sprintf("*** Get array of keys for the whole object ('.' path) %s", PHP_EOL); 98 | echo sprintf("array of keys for the root object: %s %s", json_encode($result, true), PHP_EOL . PHP_EOL); 99 | $result = $client->jsonObjectKeys(OBJECT_KEY, '.location'); 100 | echo sprintf("*** Get array of keys for '.location' object %s", PHP_EOL); 101 | echo sprintf("array of keys for the object in '.location' path: %s %s", json_encode($result, true), PHP_EOL . PHP_EOL); 102 | 103 | // object length 104 | $result = $client->jsonObjectLength(OBJECT_KEY); // by default path = '.' (root path) 105 | echo sprintf("*** Number keys for the whole object ('.' path) %s", PHP_EOL); 106 | echo sprintf("key length for the root object: %s %s", $result, PHP_EOL . PHP_EOL); 107 | $result = $client->jsonObjectLength(OBJECT_KEY, '.location'); 108 | echo sprintf("*** Number keys for '.location' object %s", PHP_EOL); 109 | echo sprintf("key length for the object in '.location' path: %s %s", $result, PHP_EOL . PHP_EOL); 110 | 111 | // append string 112 | echo sprintf("*** Appended string ' Newman' to '.name' path %s", PHP_EOL); 113 | echo sprintf("current value of '.name' path: %s %s", $client->jsonGet(OBJECT_KEY, '.name'), PHP_EOL); 114 | $result = $client->jsonStringAppend(OBJECT_KEY, ' Newman', '.name'); 115 | echo sprintf( 116 | "Value of '.name' path after appending string ' Newman': %s %s", 117 | $client->jsonGet(OBJECT_KEY, '.name'), 118 | PHP_EOL 119 | ); 120 | echo sprintf("new string length of '.name' path: %s %s", $result, PHP_EOL . PHP_EOL); 121 | 122 | // string length 123 | echo sprintf("*** String length of '.location.city' path %s", PHP_EOL); 124 | echo sprintf("value in '.location.city' path: %s %s", $client->jsonGet(OBJECT_KEY, '.location.city'), PHP_EOL); 125 | $result = $client->jsonStringLength(OBJECT_KEY, '.location.city'); 126 | echo sprintf("length of '.location.city': %s %s", $result, PHP_EOL . PHP_EOL); 127 | 128 | // delete 129 | $client->jsonSet(OBJECT_KEY, "I'm afraid I'm gonna be deleted :(", '.toBeDeleted'); 130 | echo sprintf("*** Added value to path '.toBeDeleted' to %s key: %s", OBJECT_KEY, PHP_EOL); 131 | echo json_encode($client->jsonGet(OBJECT_KEY), true) . PHP_EOL; 132 | $client->jsonDelete(OBJECT_KEY, '.toBeDeleted'); 133 | echo sprintf("*** Deleted value in path '.toBeDeleted': %s", PHP_EOL); 134 | echo json_encode($client->jsonGet(OBJECT_KEY), true) . PHP_EOL; 135 | 136 | // get Redis Serialization Protocol (ESP) 137 | echo sprintf("*** RESP of data stored in root path for %s key: %s", OBJECT_KEY, PHP_EOL); 138 | echo json_encode($client->jsonGetAsResp(OBJECT_KEY), true) . PHP_EOL . PHP_EOL; 139 | 140 | // Get from 2 paths 141 | echo sprintf("*** Getting data from paths '.colors' and '.location' for %s key: %s", OBJECT_KEY, PHP_EOL); 142 | echo json_encode($client->jsonGet(OBJECT_KEY, COLORS_KEY, '.location'), true) . PHP_EOL . PHP_EOL; 143 | 144 | // increment by integer 145 | echo sprintf("*** Incremented by 2 the value stored in path '.age' for %s key: %s", OBJECT_KEY, PHP_EOL); 146 | echo sprintf("previous '.age': %d%s", $client->jsonGet(OBJECT_KEY, '.age'), PHP_EOL); 147 | $result = $client->jsonIncrementNumBy(OBJECT_KEY, 2, '.age'); 148 | echo sprintf("updated '.age': %d%s", $result, PHP_EOL . PHP_EOL); 149 | 150 | // increment by float 151 | echo sprintf("*** Incremented by 0.03 the value stored in path '.height' for %s key: %s", OBJECT_KEY, PHP_EOL); 152 | echo sprintf("previous '.height': %.2f%s", $client->jsonGet(OBJECT_KEY, '.height'), PHP_EOL); 153 | $result = $client->jsonIncrementNumBy(OBJECT_KEY, 0.03, '.height'); 154 | echo sprintf("updated '.height': %.2f%s", $result, PHP_EOL . PHP_EOL); 155 | 156 | // multiply by integer 157 | echo sprintf("*** Multiplied by 2 the value stored in path '.age' for %s key: %s", OBJECT_KEY, PHP_EOL); 158 | echo sprintf("previous '.age': %d%s", $client->jsonGet(OBJECT_KEY, '.age'), PHP_EOL); 159 | $result = $client->jsonMultiplyNumBy(OBJECT_KEY, 2, '.age'); 160 | echo sprintf("updated '.age': %d%s", $result, PHP_EOL . PHP_EOL); 161 | 162 | // multiply by float 163 | echo sprintf("*** Multiplied by 1.03 the value stored in path '.height' for %s key: %s", OBJECT_KEY, PHP_EOL); 164 | echo sprintf("previous '.height': %.4f%s", $client->jsonGet(OBJECT_KEY, '.height'), PHP_EOL); 165 | $result = $client->jsonMultiplyNumBy(OBJECT_KEY, 1.03, '.height'); 166 | echo sprintf("updated '.height': %.4f%s", $result, PHP_EOL . PHP_EOL); 167 | 168 | // memory usage 169 | echo sprintf("*** Memory used by data stored in path '.' for %s key: %s", OBJECT_KEY, PHP_EOL); 170 | echo sprintf("memory (bytes): %d%s", $client->jsonMemoryUsage(OBJECT_KEY), PHP_EOL); 171 | $result = json_encode($client->jsonGet(OBJECT_KEY)); 172 | echo sprintf("data (array shown as json): %s%s", $result, PHP_EOL . PHP_EOL); 173 | 174 | // multi get 175 | echo sprintf("*** Setting new key '%s' with original default data %s", SECONDARY, PHP_EOL); 176 | $client->jsonSet(SECONDARY, BaseTestIntegration::$defaultData); 177 | echo sprintf( 178 | "*** Getting '.color' path value for 3 keys: '%s', '%s' and '%s' (non-existent key) %s", 179 | SECONDARY, 180 | OBJECT_KEY, 181 | 'nonexistent', 182 | PHP_EOL 183 | ); 184 | $result = $client->jsonMultiGet([OBJECT_KEY, SECONDARY, 'nonexistent'], COLORS_KEY); 185 | echo sprintf("'.colors' in '%s' key: %s%s", OBJECT_KEY, json_encode($result[0]), PHP_EOL); 186 | echo sprintf("'.colors' in '%s' key: %s%s", SECONDARY, json_encode($result[1]), PHP_EOL); 187 | echo sprintf("'.colors' in '%s' key: %s%s", 'nonexistent', json_encode($result[2]), PHP_EOL . PHP_EOL); 188 | 189 | // type 190 | echo sprintf("*** Data type for the different paths in key '%s' %s", OBJECT_KEY, PHP_EOL); 191 | echo sprintf("type for '.name' path: %s%s", $client->jsonType(OBJECT_KEY, '.name'), PHP_EOL); 192 | echo sprintf("type for '.age' path: %s%s", $client->jsonType(OBJECT_KEY, '.age'), PHP_EOL); 193 | echo sprintf("type for '.height' path: %s%s", $client->jsonType(OBJECT_KEY, '.height'), PHP_EOL); 194 | echo sprintf("type for '.location' path: %s%s", $client->jsonType(OBJECT_KEY, '.location'), PHP_EOL); 195 | echo sprintf("type for '.colors' path: %s%s", $client->jsonType(OBJECT_KEY, COLORS_KEY), PHP_EOL); 196 | echo sprintf("type for '.license' path: %s%s", $client->jsonType(OBJECT_KEY, '.license'), PHP_EOL . PHP_EOL); 197 | -------------------------------------------------------------------------------- /examples/usage.php: -------------------------------------------------------------------------------- 1 | 5 | * @copyright 2019 Rafael Campoy 6 | * @license MIT 7 | * @link https://github.com/averias/phpredis-json 8 | * 9 | * Copyright and license information, is included in 10 | * the LICENSE file that is distributed with this source code. 11 | */ 12 | 13 | namespace Examples; 14 | 15 | require(dirname(__DIR__) . '/vendor/autoload.php'); 16 | 17 | use Averias\RedisJson\Client\RedisJsonClient; 18 | use Averias\RedisJson\Enum\JsonCommands; 19 | use Averias\RedisJson\Exception\ResponseException; 20 | use Averias\RedisJson\Factory\RedisJsonClientFactory; 21 | 22 | // instantiate factory 23 | $redisJsonClientFactory = new RedisJsonClientFactory(); 24 | 25 | /** 26 | * creates a client with default connection params: 27 | * [ 28 | * 'host' => '127.0.0.1', 29 | * 'port' => 6379, 30 | * 'timeout' => 0.0, // seconds 31 | * 'retryInterval' => 15 // milliseconds 32 | * 'readTimeout' => 2, // seconds 33 | * 'persistenceId' => null // string for persistent connections, null for no persistent ones 34 | * 'database' => 0 // Redis database index [0..15] 35 | * ] 36 | */ 37 | 38 | /** @var RedisJsonClient $client */ 39 | $client = $redisJsonClientFactory->createClient(); 40 | 41 | // creates a configured client 42 | $client = $redisJsonClientFactory->createClient([ 43 | 'host' => '127.0.0.1', 44 | 'port' => 6379, 45 | 'timeout' => 2, 46 | 'database' => 15 47 | ]); 48 | 49 | /** 50 | * creates a RedisJsonClient with default connection params: 51 | * [ 52 | * 'host' => '127.0.0.1', 53 | * 'port' => 6379, 54 | * 'timeout' => 0.0, // seconds 55 | * 'retryInterval' => 15 // milliseconds 56 | * 'readTimeout' => 2, // seconds 57 | * 'persistenceId' => null // string for persistent connections, null for no persistent ones 58 | * 'database' => 0 // Redis database index [0..15] 59 | * ] 60 | */ 61 | 62 | // json commands 63 | $result = $client->jsonSet('people', ["name" => "gafael", "age" => 12]); 64 | echo ($result === true ? 'true' : 'false') . PHP_EOL; // true 65 | 66 | $result = $client->jsonGet('people'); // $result = ["name":"gafael","age":12] 67 | echo json_encode($result) . PHP_EOL; // {"name":"gafael","age":12} 68 | 69 | $result = $client->jsonGet('people', '.name'); 70 | echo $result . PHP_EOL; // "gafael" 71 | 72 | $result = $client->jsonGet('people', '.age'); 73 | echo $result . PHP_EOL; // 12 74 | 75 | // "nonexistent" key does not exists, so a ResponseException is thrown 76 | try { 77 | $result = $client->jsonGet('nonexistent'); 78 | echo $result . PHP_EOL; 79 | } catch (ResponseException $e) { 80 | echo "key nonexistent does not exist" . PHP_EOL; 81 | } 82 | 83 | // you can also send RedisJSON command as raw commands using "executeRawCommand", you will send a receive JSON values 84 | $result = $client->executeRawCommand(JsonCommands::SET, 'people', '.colors', '["blue", "green"]'); 85 | echo $result . PHP_EOL; // 'OK' 86 | 87 | $result = $client->executeRawCommand(JsonCommands::GET, 'people', '.'); 88 | echo $result . PHP_EOL; // {"name":"gafael","age":12,"colors":["blue","green"]} 89 | 90 | 91 | // you can also issue redis commands and use RedisJsonClient as "phpredis" client: 92 | echo $client->hset('hash-key', 'age', 34) . PHP_EOL; // 0 93 | echo $client->hget('hash-key', 'age') . PHP_EOL; // 34 94 | 95 | // $ret = [true,"val1",true,"val2"] 96 | $ret = $client->multi() 97 | ->set('key1', 'val1') 98 | ->get('key1') 99 | ->set('key2', 'val2') 100 | ->get('key2') 101 | ->exec(); 102 | 103 | echo json_encode($ret) . PHP_EOL; 104 | -------------------------------------------------------------------------------- /phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 14 | 15 | 16 | ./tests/Integration/ 17 | 18 | 19 | ./tests/Unit 20 | 21 | 22 | 23 | 24 | ./src/ 25 | 26 | ./src/RedisJsonClient/Exception 27 | ./src/RedisJsonClient/Enum 28 | ./src/ 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /run-tests-docker.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | bash ./docker-tests/docker-containers.sh 4 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Adapter/AdapterProvider.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Adapter; 16 | 17 | use Averias\RedisJson\Exception\InvalidRedisVersionException; 18 | use Averias\RedisJson\Exception\RedisJsonModuleNotInstalledException; 19 | use Averias\RedisJson\Exception\ResponseException; 20 | use Averias\RedisJson\Connection\ConnectionOptions; 21 | use Averias\RedisJson\Exception\ConnectionException; 22 | use Averias\RedisJson\Validator\RedisClientValidatorInterface; 23 | use Redis; 24 | 25 | class AdapterProvider 26 | { 27 | /** @var RedisClientValidatorInterface */ 28 | protected $validator; 29 | 30 | public function __construct(RedisClientValidatorInterface $validator) 31 | { 32 | $this->validator = $validator; 33 | } 34 | 35 | /** 36 | * @param array|null $config 37 | * @return RedisClientAdapterInterface 38 | * @throws ConnectionException 39 | * @throws InvalidRedisVersionException 40 | * @throws RedisJsonModuleNotInstalledException 41 | * @throws ResponseException 42 | */ 43 | public function get(array $config = []): RedisClientAdapterInterface 44 | { 45 | $redisClient = $this->getRedisClient($config); 46 | 47 | $redisInfo = $redisClient->executeCommandByName('INFO', []); 48 | $redisServerVersion = $redisInfo['redis_version']; 49 | if (!$this->validator->isValidRedisVersion($redisServerVersion)) { 50 | throw new InvalidRedisVersionException( 51 | sprintf('invalid redis server version %s, expected 4.0+.', $redisServerVersion) 52 | ); 53 | } 54 | 55 | $moduleS = $redisClient->executeRawCommand('MODULE', 'list'); 56 | if (!$this->validator->isRedisJsonModuleInstalled($moduleS)) { 57 | throw new RedisJsonModuleNotInstalledException('RedisJson module not installed in Redis server.'); 58 | } 59 | 60 | return $redisClient; 61 | } 62 | 63 | /** 64 | * @param array $config 65 | * @return RedisClientAdapterInterface 66 | * @throws ConnectionException 67 | */ 68 | protected function getRedisClient(array $config = []): RedisClientAdapterInterface 69 | { 70 | $connectionOptions = new ConnectionOptions($config); 71 | return new RedisClientAdapter(new Redis(), $connectionOptions); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Adapter/RedisClientAdapter.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Adapter; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\ResponseParser; 19 | use Averias\RedisJson\Exception\ResponseException; 20 | use Averias\RedisJson\Connection\ConnectionOptions; 21 | use Averias\RedisJson\Exception\ConnectionException; 22 | use Redis; 23 | use Exception; 24 | 25 | class RedisClientAdapter implements RedisClientAdapterInterface 26 | { 27 | /** @var Redis */ 28 | protected $redis; 29 | 30 | /** @var ConnectionOptions */ 31 | protected $connectionOptions; 32 | 33 | /** 34 | * @param Redis $redis 35 | * @param ConnectionOptions $connectionOptions 36 | * @throws ConnectionException 37 | */ 38 | public function __construct(Redis $redis, ConnectionOptions $connectionOptions) 39 | { 40 | $this->redis = $redis; 41 | $this->connectionOptions = $connectionOptions; 42 | $this->setConnection(); 43 | } 44 | 45 | /** 46 | * @param string $command 47 | * @param array $keys 48 | * @param array $params 49 | * @return mixed 50 | * @throws ResponseException 51 | */ 52 | public function executeJsonCommand(string $command, array $keys, array $params) 53 | { 54 | $response = $this->executeRawCommand($command, ...$params); 55 | 56 | if ($response === false) { 57 | $error = $this->redis->getLastError() ?? JsonCommands::EXCEPTION_MESSAGES[$command] ?? 'unknown'; 58 | throw new ResponseException( 59 | sprintf("something was wrong when executing %s command, possible reasons: %s", $command, $error) 60 | ); 61 | } 62 | 63 | return $this->parseResponse($command, $response); 64 | } 65 | 66 | /** 67 | * @param string $commandName 68 | * @param mixed ...$arguments 69 | * @return mixed 70 | * @throws ResponseException 71 | */ 72 | public function executeRawCommand(string $commandName, ...$arguments) 73 | { 74 | try { 75 | $this->checkConnection(); 76 | return $this->redis->rawCommand($commandName, ...$arguments); 77 | } catch (Exception $e) { 78 | throw new ResponseException( 79 | sprintf( 80 | 'the following error happened when executing the command "%s" with param "%s": %s', 81 | $commandName, 82 | implode(' ', $arguments), 83 | $e->getMessage() 84 | ) 85 | ); 86 | } 87 | } 88 | 89 | /** 90 | * @param string $methodName 91 | * @param array $arguments 92 | * @return mixed 93 | * @throws ResponseException 94 | */ 95 | public function executeCommandByName(string $methodName, array $arguments = []) 96 | { 97 | try { 98 | $this->checkConnection(); 99 | return call_user_func_array([$this->redis, $methodName], $arguments); 100 | } catch (Exception $e) { 101 | throw new ResponseException( 102 | sprintf( 103 | 'the following error happened when executing command "%s" with param "%s": %s', 104 | $methodName, 105 | implode(' ', $arguments), 106 | $e->getMessage() 107 | ) 108 | ); 109 | } 110 | } 111 | 112 | /** 113 | * @throws ConnectionException 114 | */ 115 | protected function setConnection(): void 116 | { 117 | if (!$this->connect()) { 118 | throw new ConnectionException( 119 | sprintf("connection to Redis server failed, reason: %s", $this->redis->getLastError()) 120 | ); 121 | } 122 | 123 | if ($this->connectionOptions->getDatabase() != 0) { 124 | $this->redis->select($this->connectionOptions->getDatabase()); 125 | } 126 | 127 | $this->redis->setOption(Redis::OPT_REPLY_LITERAL, 1); 128 | } 129 | 130 | /** 131 | * @return bool 132 | */ 133 | protected function connect(): bool 134 | { 135 | $connectionValues = $this->connectionOptions->getConnectionValues(); 136 | if ($this->connectionOptions->isPersistent()) { 137 | return $this->redis->pconnect(...$connectionValues); 138 | } 139 | 140 | return $this->redis->connect(...$connectionValues); 141 | } 142 | 143 | /** 144 | * @throws ConnectionException 145 | */ 146 | protected function checkConnection(): void 147 | { 148 | if (!$this->redis->isConnected()) { 149 | $this->setConnection(); 150 | } 151 | } 152 | 153 | protected function parseResponse(string $command, $response) 154 | { 155 | $responseParsers = ResponseParser::RESPONSE_PARSER; 156 | if (isset($responseParsers[$command])) { 157 | $className = $responseParsers[$command]; 158 | $parser = new $className(); 159 | return $parser->parse($response); 160 | } 161 | 162 | return $response; 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Adapter/RedisClientAdapterInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Adapter; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | 19 | interface RedisClientAdapterInterface 20 | { 21 | /** 22 | * @param string $command 23 | * @param array $keys 24 | * @param array $params 25 | * @return mixed 26 | * @throws ResponseException 27 | */ 28 | public function executeJsonCommand(string $command, array $keys, array $params); 29 | 30 | /** 31 | * @param string $methodName 32 | * @param array $arguments 33 | * @return mixed 34 | * @throws ResponseException 35 | */ 36 | public function executeCommandByName(string $methodName, array $arguments); 37 | 38 | /** 39 | * @param string $commandName 40 | * @param array $arguments 41 | * @return mixed 42 | */ 43 | public function executeRawCommand(string $commandName, ...$arguments); 44 | } 45 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Client/ClientInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Client; 16 | 17 | interface ClientInterface 18 | { 19 | public function executeRawCommand(string $commandName, ...$arguments); 20 | } 21 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Client/RedisJsonClient.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Client; 16 | 17 | use Averias\RedisJson\Adapter\RedisClientAdapterInterface; 18 | use Averias\RedisJson\Command\Traits\JsonCommandTrait; 19 | use Averias\RedisJson\Exception\ResponseException; 20 | 21 | class RedisJsonClient implements RedisJsonClientInterface 22 | { 23 | use JsonCommandTrait; 24 | 25 | /** @var RedisClientAdapterInterface */ 26 | private $redisClientAdapter; 27 | 28 | public function __construct(RedisClientAdapterInterface $redisClientAdapter) 29 | { 30 | $this->redisClientAdapter = $redisClientAdapter; 31 | } 32 | 33 | /** 34 | * @param string $commandName 35 | * @param array $arguments 36 | * @return mixed 37 | */ 38 | public function executeRawCommand(string $commandName, ...$arguments) 39 | { 40 | return $this->redisClientAdapter->executeRawCommand($commandName, ...$arguments); 41 | } 42 | 43 | /** 44 | * @param string $name 45 | * @param array $arguments 46 | * @return mixed 47 | * @throws ResponseException 48 | */ 49 | public function __call(string $name, array $arguments) 50 | { 51 | return $this->redisClientAdapter->executeCommandByName($name, $arguments); 52 | } 53 | 54 | /** 55 | * @param string $command 56 | * @param array $keys 57 | * @param array $params 58 | * @return mixed 59 | * @throws ResponseException 60 | */ 61 | protected function executeJsonCommand(string $command, array $keys, array $params = []) 62 | { 63 | return $this->redisClientAdapter->executeJsonCommand($command, $keys, $params); 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Client/RedisJsonClientInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Client; 16 | 17 | use Averias\RedisJson\Command\Traits\JsonCommandTraitInterface; 18 | use Averias\RedisJson\Encoder\Traits\JsonEncoderTraitInterface; 19 | 20 | interface RedisJsonClientInterface extends ClientInterface, JsonCommandTraitInterface, JsonEncoderTraitInterface 21 | { 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Command/Traits/JsonCommandTraitInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Command\Traits; 16 | 17 | interface JsonCommandTraitInterface 18 | { 19 | public function jsonDelete(string $key, string $path = '.'); 20 | 21 | public function jsonGet(string $key, string ...$paths); 22 | 23 | public function jsonMultiGet(array $keys, string $path = '.'); 24 | 25 | public function jsonSet(string $key, $value, string $path = '.', ?string $keyOptions = null); 26 | 27 | public function jsonType(string $key, string $path = '.'); 28 | 29 | public function jsonIncrementNumBy(string $key, $number, string $path = '.'); 30 | 31 | public function jsonMultiplyNumBy(string $key, $number, string $path = '.'); 32 | 33 | public function jsonStringAppend(string $key, string $value, string $path = '.'); 34 | 35 | public function jsonStringLength(string $key, string $path = '.'); 36 | 37 | public function jsonArrayAppend(string $key, string $path, ...$values); 38 | 39 | public function jsonArrayIndex(string $key, string $value, string $path = '.', int $start = 0, int $stop = 0); 40 | 41 | public function jsonArrayInsert(string $key, string $path, int $index, ...$values); 42 | 43 | public function jsonArrayLength(string $key, string $path = '.'); 44 | 45 | public function jsonArrayPop(string $key, string $path = '.', int $index = -1); 46 | 47 | public function jsonArrayTrim(string $key, int $start, int $stop, string $path = '.'); 48 | 49 | public function jsonObjectKeys(string $key, string $path = '.'); 50 | 51 | public function jsonObjectLength(string $key, string $path = '.'); 52 | 53 | public function jsonMemoryUsage(string $key, string $path = '.'); 54 | 55 | public function jsonForget(string $key, string $path = '.'); 56 | 57 | public function jsonGetAsResp(string $key, string $path = '.'); 58 | } 59 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Connection/ConnectionOptions.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | declare(strict_types=1); 16 | 17 | namespace Averias\RedisJson\Connection; 18 | 19 | use Averias\RedisJson\Enum\Connection; 20 | use Averias\RedisJson\Exception\ConnectionOptionsException; 21 | 22 | class ConnectionOptions 23 | { 24 | /** @var string */ 25 | private $host; 26 | 27 | /** @var int */ 28 | private $port; 29 | 30 | /** @var float */ 31 | private $timeout; 32 | 33 | /** @var int */ 34 | private $retryInterval; 35 | 36 | /** @var float */ 37 | private $readTimeout; 38 | 39 | /** @var string */ 40 | private $persistentId; 41 | 42 | /** @var int */ 43 | private $database; 44 | 45 | /** 46 | * @param array $config 47 | */ 48 | public function __construct(array $config = []) 49 | { 50 | $host = $config[Connection::HOST] ?? Connection::DEFAULT[Connection::HOST]; 51 | $this->setHost($host); 52 | 53 | $port = $config[Connection::PORT] ?? Connection::DEFAULT[Connection::PORT]; 54 | $this->setPort($port); 55 | 56 | $timeout = $config[Connection::TIMEOUT] ?? Connection::DEFAULT[Connection::TIMEOUT]; 57 | $this->setTimeout($timeout); 58 | 59 | $retryInterval = $config[Connection::RETRY_INTERVAL] ?? Connection::DEFAULT[Connection::RETRY_INTERVAL]; 60 | $this->setRetryInterval($retryInterval); 61 | 62 | $readTimeout = $config[Connection::READ_TIMEOUT] ?? Connection::DEFAULT[Connection::READ_TIMEOUT]; 63 | $this->setReadTimeout($readTimeout); 64 | 65 | $persistent = $config[Connection::PERSISTENCE_ID] ?? Connection::DEFAULT[Connection::PERSISTENCE_ID]; 66 | $this->setPersistentId($persistent); 67 | 68 | $database = $config[Connection::DATABASE] ?? Connection::DEFAULT[Connection::DATABASE]; 69 | $this->setDatabase($database); 70 | } 71 | 72 | /** 73 | * @return string 74 | */ 75 | public function getHost(): string 76 | { 77 | return $this->host; 78 | } 79 | 80 | /** 81 | * @param string $host 82 | * @return ConnectionOptions 83 | */ 84 | public function setHost(string $host): ConnectionOptions 85 | { 86 | $this->host = $host; 87 | return $this; 88 | } 89 | 90 | /** 91 | * @return int 92 | */ 93 | public function getPort(): int 94 | { 95 | return $this->port; 96 | } 97 | 98 | /** 99 | * @param int $port 100 | * @return ConnectionOptions 101 | */ 102 | public function setPort(int $port): ConnectionOptions 103 | { 104 | $this->port = $port; 105 | return $this; 106 | } 107 | 108 | /** 109 | * @return float in seconds 110 | */ 111 | public function getTimeout(): float 112 | { 113 | return $this->timeout; 114 | } 115 | 116 | /** 117 | * @param float $timeout in seconds 118 | * @return ConnectionOptions 119 | */ 120 | public function setTimeout(float $timeout): ConnectionOptions 121 | { 122 | $this->timeout = $timeout; 123 | return $this; 124 | } 125 | 126 | /** 127 | * @return int in milliseconds 128 | */ 129 | public function getRetryInterval(): int 130 | { 131 | return $this->retryInterval; 132 | } 133 | 134 | /** 135 | * @param int $retryInterval in milliseconds 136 | * @return ConnectionOptions 137 | */ 138 | public function setRetryInterval(int $retryInterval): ConnectionOptions 139 | { 140 | $this->retryInterval = $retryInterval; 141 | return $this; 142 | } 143 | 144 | /** 145 | * @return float in seconds 146 | */ 147 | public function getReadTimeout(): float 148 | { 149 | return $this->readTimeout; 150 | } 151 | 152 | /** 153 | * @param float $readTimeout in seconds 154 | * @return ConnectionOptions 155 | */ 156 | public function setReadTimeout(float $readTimeout): ConnectionOptions 157 | { 158 | $this->readTimeout = $readTimeout; 159 | return $this; 160 | } 161 | 162 | /** 163 | * @return bool 164 | */ 165 | public function isPersistent(): bool 166 | { 167 | return !is_null($this->persistentId); 168 | } 169 | 170 | /** 171 | * @return int Redis database index [0..15] 172 | */ 173 | public function getDatabase(): int 174 | { 175 | return $this->database; 176 | } 177 | 178 | /** 179 | * @param int $database Redis database index [0..15] 180 | * @return ConnectionOptions 181 | */ 182 | public function setDatabase(int $database): ConnectionOptions 183 | { 184 | if ($database < 0 || $database > 15) { 185 | throw new ConnectionOptionsException( 186 | sprintf("redis database value out of range, expected: 0-15, assigned: %d", $database) 187 | ); 188 | } 189 | $this->database = $database; 190 | return $this; 191 | } 192 | 193 | /** 194 | * @return string|null identity for the requested persistent connection or null for non persistent connection 195 | */ 196 | public function getPersistentId(): ?string 197 | { 198 | return $this->persistentId; 199 | } 200 | 201 | /** 202 | * @param string|null $persistentId identity for the persistent connection or null for non persistent connection 203 | * @return ConnectionOptions 204 | */ 205 | public function setPersistentId(?string $persistentId): ConnectionOptions 206 | { 207 | $this->persistentId = $persistentId; 208 | return $this; 209 | } 210 | 211 | public function getConnectionValues(): array 212 | { 213 | return [ 214 | $this->getHost(), 215 | $this->getPort(), 216 | $this->getTimeout(), 217 | $this->getPersistentId(), 218 | $this->getRetryInterval(), 219 | $this->getReadTimeout() 220 | ]; 221 | } 222 | } 223 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Encoder/Traits/JsonEncoderTrait.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Encoder\Traits; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | 19 | trait JsonEncoderTrait 20 | { 21 | /** 22 | * @param $value 23 | * @return string 24 | * @throws ResponseException 25 | */ 26 | public function encode($value): string 27 | { 28 | // @TODO: when update to PHP 7.3+ wrap it with a try...catch for capturing \JsonException 29 | // as explained here https://ayesh.me/Upgrade-PHP-7.3#json-exceptions 30 | $jsonEncodedValue = json_encode($value); 31 | if (false === $jsonEncodedValue || json_last_error() !== JSON_ERROR_NONE) { 32 | throw new ResponseException( 33 | sprintf('value could not be json-encoded properly, reason: %s', json_last_error_msg()) 34 | ); 35 | } 36 | 37 | return $jsonEncodedValue; 38 | } 39 | 40 | /** 41 | * @param string $json 42 | * @return mixed 43 | * @throws ResponseException 44 | */ 45 | public function decode(string $json) 46 | { 47 | // @TODO: when update to PHP 7.3+ wrap it with a try...catch for capturing \JsonException 48 | // as explained here https://ayesh.me/Upgrade-PHP-7.3#json-exceptions 49 | $decodedValue = json_decode($json, true); 50 | if (json_last_error() !== JSON_ERROR_NONE) { 51 | throw new ResponseException( 52 | sprintf('"%s" could not be json-decoded properly, reason: %s', $json, json_last_error_msg()) 53 | ); 54 | } 55 | 56 | return $decodedValue; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Encoder/Traits/JsonEncoderTraitInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Encoder\Traits; 16 | 17 | interface JsonEncoderTraitInterface 18 | { 19 | public function encode($value): string; 20 | public function decode(string $json); 21 | } 22 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/Connection.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use MyCLabs\Enum\Enum; 18 | 19 | class Connection extends Enum 20 | { 21 | const HOST = 'host'; 22 | const PORT = 'port'; 23 | const TIMEOUT = 'timeout'; 24 | const RETRY_INTERVAL = 'retryInterval'; 25 | const READ_TIMEOUT = 'readTimeout'; 26 | const PERSISTENCE_ID = 'persistenceId'; 27 | const DATABASE = 'database'; 28 | 29 | const DEFAULT = [ 30 | self::HOST => '127.0.0.1', 31 | self::PORT => 6379, 32 | self::TIMEOUT => 0.0, 33 | self::RETRY_INTERVAL => 0, 34 | self::READ_TIMEOUT => 0, 35 | self::PERSISTENCE_ID => null, 36 | self::DATABASE => 0 37 | ]; 38 | } 39 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/JsonCommands.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use MyCLabs\Enum\Enum; 18 | 19 | class JsonCommands extends Enum 20 | { 21 | /** Commands */ 22 | const DELETE = 'JSON.DEL'; 23 | const GET = 'JSON.GET'; 24 | const SET = 'JSON.SET'; 25 | const MULTI_GET = 'JSON.MGET'; 26 | const TYPE = 'JSON.TYPE'; 27 | const INCREMENT_NUM_BY = 'JSON.NUMINCRBY'; 28 | const MULTIPLY_NUM_BY = 'JSON.NUMMULTBY'; 29 | const APPEND_STRING = 'JSON.STRAPPEND'; 30 | const STRING_LENGTH = 'JSON.STRLEN'; 31 | const ARRAY_APPEND = 'JSON.ARRAPPEND'; 32 | const ARRAY_INDEX = 'JSON.ARRINDEX'; 33 | const ARRAY_INSERT = 'JSON.ARRINSERT'; 34 | const ARRAY_LENGTH = 'JSON.ARRLEN'; 35 | const ARRAY_POP = 'JSON.ARRPOP'; 36 | const ARRAY_TRIM = 'JSON.ARRTRIM'; 37 | const OBJECT_KEYS = 'JSON.OBJKEYS'; 38 | const OBJECT_LENGTH = 'JSON.OBJLEN'; 39 | const MEMORY_USAGE = 'JSON.DEBUG'; 40 | const GET_AS_RESP = 'JSON.RESP'; 41 | 42 | /** Messages */ 43 | const DEFAULT_MESSAGE = 'key or path does not exist'; 44 | const EXCEPTION_MESSAGES = [ 45 | self::DELETE => 'JSON.DEL', 46 | self::GET => self::DEFAULT_MESSAGE, 47 | self::SET => 'NX or NX conditions were not met, no root path for new keys, ...', 48 | self::MULTI_GET => 'JSON.MGET', 49 | self::TYPE => self::DEFAULT_MESSAGE, 50 | self::INCREMENT_NUM_BY => self::DEFAULT_MESSAGE . ', increment a no number value, ...', 51 | self::MULTIPLY_NUM_BY => self::DEFAULT_MESSAGE . ', multiply a no number value, ...', 52 | self::APPEND_STRING => self::DEFAULT_MESSAGE . ', append to no string value, ...', 53 | self::STRING_LENGTH => self::DEFAULT_MESSAGE . ', length of no string value, ...', 54 | self::ARRAY_APPEND => self::DEFAULT_MESSAGE . ', append to no array, ...', 55 | self::ARRAY_INDEX => self::DEFAULT_MESSAGE . ', index on no array, ...', 56 | self::ARRAY_INSERT => self::DEFAULT_MESSAGE . ', insertion on no array, ...', 57 | self::ARRAY_LENGTH => self::DEFAULT_MESSAGE . ', length of no array, ...', 58 | self::ARRAY_POP => self::DEFAULT_MESSAGE . ', empty array, no array, ...', 59 | self::ARRAY_TRIM => self::DEFAULT_MESSAGE . ', trimming no array, ...', 60 | self::OBJECT_KEYS => self::DEFAULT_MESSAGE . ', no JSON object, ...', 61 | self::OBJECT_LENGTH => self::DEFAULT_MESSAGE . ', empty object, no object, ...', 62 | self::MEMORY_USAGE => self::DEFAULT_MESSAGE, 63 | self::GET_AS_RESP => self::DEFAULT_MESSAGE 64 | ]; 65 | } 66 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/Keys.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use MyCLabs\Enum\Enum; 18 | 19 | class Keys extends Enum 20 | { 21 | const DEFAULT_KEY = 'test-key'; 22 | const EXTENDED_KEY = 'extended-test-key'; 23 | const KEY_TO_EMPTY = 'key-to-empty'; 24 | } 25 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/Module.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use MyCLabs\Enum\Enum; 18 | 19 | class Module extends Enum 20 | { 21 | const REDIS_JSON_MODULE_NAME = 'ReJSON'; 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/ResponseParser.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use Averias\RedisJson\Parser\Response\DecodeArrayOfJson; 18 | use Averias\RedisJson\Parser\Response\DecodeFromJson; 19 | use Averias\RedisJson\Parser\Response\IntegerToBoolean; 20 | use Averias\RedisJson\Parser\Response\OkToTrue; 21 | use MyCLabs\Enum\Enum; 22 | 23 | class ResponseParser extends Enum 24 | { 25 | const RESPONSE_PARSER = [ 26 | JsonCommands::DELETE => IntegerToBoolean::class, 27 | JsonCommands::GET => DecodeFromJson::class, 28 | JsonCommands::MULTI_GET => DecodeArrayOfJson::class, 29 | JsonCommands::INCREMENT_NUM_BY => DecodeFromJson::class, 30 | JsonCommands::MULTIPLY_NUM_BY => DecodeFromJson::class, 31 | JsonCommands::ARRAY_POP => DecodeFromJson::class, 32 | JsonCommands::SET => OkToTrue::class 33 | ]; 34 | } 35 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Enum/Version.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Enum; 16 | 17 | use MyCLabs\Enum\Enum; 18 | 19 | class Version extends Enum 20 | { 21 | const REDIS_JSON_CLIENT_4X0 = '4.0'; 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/ConnectionException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use Exception; 18 | 19 | class ConnectionException extends Exception 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/ConnectionOptionsException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use InvalidArgumentException; 18 | 19 | class ConnectionOptionsException extends InvalidArgumentException 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/InvalidRedisVersionException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use Exception; 18 | 19 | class InvalidRedisVersionException extends Exception 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/RedisClientException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use Exception; 18 | 19 | class RedisClientException extends Exception 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/RedisJsonModuleNotInstalledException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use Exception; 18 | 19 | class RedisJsonModuleNotInstalledException extends Exception 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Exception/ResponseException.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Exception; 16 | 17 | use Exception; 18 | 19 | class ResponseException extends Exception 20 | { 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Factory/RedisJsonClientFactory.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Factory; 16 | 17 | use Averias\RedisJson\Adapter\AdapterProvider; 18 | use Averias\RedisJson\Client\RedisJsonClient; 19 | use Averias\RedisJson\Client\RedisJsonClientInterface; 20 | use Averias\RedisJson\Exception\RedisClientException; 21 | use Averias\RedisJson\Validator\RedisClientValidator; 22 | use Exception; 23 | 24 | class RedisJsonClientFactory implements RedisJsonClientFactoryInterface 25 | { 26 | /** @var AdapterProvider */ 27 | protected $adapterProvider; 28 | 29 | public function __construct() 30 | { 31 | $this->adapterProvider = new AdapterProvider(new RedisClientValidator()); 32 | } 33 | 34 | /** 35 | * @param array|null $config 36 | * @return RedisJsonClientInterface 37 | * @throws RedisClientException 38 | */ 39 | public function createClient(array $config = []): RedisJsonClientInterface 40 | { 41 | try { 42 | $adapter = $this->adapterProvider->get($config); 43 | } catch (Exception $e) { 44 | throw new RedisClientException($e->getMessage()); 45 | } 46 | 47 | return new RedisJsonClient($adapter); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Factory/RedisJsonClientFactoryInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Factory; 16 | 17 | use Averias\RedisJson\Client\RedisJsonClientInterface; 18 | 19 | interface RedisJsonClientFactoryInterface 20 | { 21 | public function createClient(array $config): RedisJsonClientInterface; 22 | } 23 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/ParserInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser; 16 | 17 | interface ParserInterface 18 | { 19 | public function parse($response); 20 | } 21 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/Response/BaseJsonDecoderParser.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser\Response; 16 | 17 | use Averias\RedisJson\Encoder\Traits\JsonEncoderTrait; 18 | use Averias\RedisJson\Exception\ResponseException; 19 | 20 | class BaseJsonDecoderParser 21 | { 22 | use JsonEncoderTrait; 23 | 24 | /** 25 | * @param string|bool $response 26 | * @return mixed 27 | * @throws ResponseException 28 | */ 29 | public function decodeIfNotFalse($response) 30 | { 31 | if ($response === false) { 32 | return null; 33 | } 34 | 35 | return $this->decode($response); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/Response/DecodeArrayOfJson.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\ParserInterface; 19 | 20 | class DecodeArrayOfJson extends BaseJsonDecoderParser implements ParserInterface 21 | { 22 | /** 23 | * @param array $response 24 | * @return array 25 | * @throws ResponseException 26 | */ 27 | public function parse($response) 28 | { 29 | if (!is_array($response)) { 30 | throw new ResponseException(sprintf("expected array response but got '%s'", gettype($response))); 31 | } 32 | 33 | $decodedResult = []; 34 | foreach ($response as $value) { 35 | $decodedResult[] = $this->decodeIfNotFalse($value); 36 | } 37 | 38 | return $decodedResult; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/Response/DecodeFromJson.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\ParserInterface; 19 | 20 | class DecodeFromJson extends BaseJsonDecoderParser implements ParserInterface 21 | { 22 | /** 23 | * @param string|bool $response 24 | * @return mixed 25 | * @throws ResponseException 26 | */ 27 | public function parse($response) 28 | { 29 | return $this->decodeIfNotFalse($response); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/Response/IntegerToBoolean.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\ParserInterface; 19 | 20 | class IntegerToBoolean implements ParserInterface 21 | { 22 | /** 23 | * @param int $response 24 | * @return bool 25 | * @throws ResponseException 26 | */ 27 | public function parse($response) 28 | { 29 | if (!is_int($response)) { 30 | throw new ResponseException(sprintf("expected integer response but got '%s'", gettype($response))); 31 | } 32 | 33 | return $response === 1 ? true : false; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Parser/Response/OkToTrue.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\ParserInterface; 19 | 20 | class OkToTrue implements ParserInterface 21 | { 22 | /** 23 | * @param $response 24 | * @return bool 25 | * @throws ResponseException 26 | */ 27 | public function parse($response) 28 | { 29 | if (!is_string($response)) { 30 | throw new ResponseException(sprintf("expected string response but got '%s'", gettype($response))); 31 | } 32 | 33 | if ($response !== 'OK') { 34 | throw new ResponseException(sprintf("expected 'OK' string response but got '%s'", $response)); 35 | } 36 | 37 | return true; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Validator/RedisClientValidator.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Validator; 16 | 17 | use Averias\RedisJson\Enum\Module; 18 | use Averias\RedisJson\Enum\Version; 19 | 20 | class RedisClientValidator implements RedisClientValidatorInterface 21 | { 22 | /** 23 | * @param string $version 24 | * @return bool 25 | */ 26 | public function isValidRedisVersion(string $version): bool 27 | { 28 | $version .= '.0'; 29 | return (float) $version >= (float) Version::REDIS_JSON_CLIENT_4X0; 30 | } 31 | 32 | /** 33 | * @param array $moduleListCommandResponse 34 | * @return bool 35 | */ 36 | public function isRedisJsonModuleInstalled(array $moduleListCommandResponse): bool 37 | { 38 | foreach ($moduleListCommandResponse as $group) { 39 | if (in_array(Module::REDIS_JSON_MODULE_NAME, $group)) { 40 | return true; 41 | } 42 | } 43 | 44 | return false; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/RedisJsonClient/Validator/RedisClientValidatorInterface.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Validator; 16 | 17 | interface RedisClientValidatorInterface 18 | { 19 | /** 20 | * @param string $version 21 | * @return bool 22 | */ 23 | public function isValidRedisVersion(string $version): bool; 24 | 25 | /** 26 | * @param array $moduleListCommandResponse 27 | * @return bool 28 | */ 29 | public function isRedisJsonModuleInstalled(array $moduleListCommandResponse): bool; 30 | } 31 | -------------------------------------------------------------------------------- /tests/Integration/BaseTestIntegration.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration; 16 | 17 | use Averias\RedisJson\Client\RedisJsonClientInterface; 18 | use Averias\RedisJson\Exception\RedisClientException; 19 | use Averias\RedisJson\Factory\RedisJsonClientFactory; 20 | use Averias\RedisJson\Enum\Connection; 21 | use Averias\RedisJson\Enum\Keys; 22 | use PHPUnit\Framework\TestCase; 23 | 24 | class BaseTestIntegration extends TestCase 25 | { 26 | public static $defaultData = [ 27 | 'name' => 'Peter', 28 | 'age' => 38, 29 | 'height' => 1.79, 30 | 'location' => [ 31 | 'address' => 'Pub Street, 39', 32 | 'city' => 'Limerick', 33 | 'country' => 'Ireland' 34 | ], 35 | 'colors' => ['white', 'black'], 36 | 'license' => true 37 | ]; 38 | 39 | /** @var RedisJsonClientInterface */ 40 | protected static $reJsonClient; 41 | 42 | /** 43 | * @throws RedisClientException 44 | */ 45 | public static function setUpBeforeClass(): void 46 | { 47 | static::$reJsonClient = self::getReJsonClient(); 48 | static::storeData(Keys::DEFAULT_KEY, static::$defaultData); 49 | } 50 | 51 | public static function tearDownAfterClass(): void 52 | { 53 | if (static::$reJsonClient) { 54 | static::$reJsonClient->select(REDIS_TEST_DATABASE); 55 | static::$reJsonClient->flushDb(); 56 | } 57 | } 58 | 59 | protected static function getReJsonClientConfig(): array 60 | { 61 | return [ 62 | Connection::HOST => REDIS_TEST_SERVER, 63 | Connection::PORT => (int) REDIS_TEST_PORT, 64 | Connection::TIMEOUT => 2, 65 | Connection::DATABASE => (int) REDIS_TEST_DATABASE 66 | ]; 67 | } 68 | 69 | /** 70 | * @return RedisJsonClientInterface 71 | * @throws RedisClientException 72 | */ 73 | protected static function getReJsonClient(): RedisJsonClientInterface 74 | { 75 | $config = static::getReJsonClientConfig(); 76 | $factory = new RedisJsonClientFactory(); 77 | 78 | return $factory->createClient($config); 79 | } 80 | 81 | protected static function storeData(string $key, array $data) 82 | { 83 | static::$reJsonClient->jsonSet($key, $data); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayAppendCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayAppendCommandTest extends BaseTestIntegration 22 | { 23 | /** 24 | * @dataProvider getValuesForAdding 25 | * @param $value 26 | */ 27 | public function testAppendValuesToArray($value) 28 | { 29 | $previousValues = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 30 | $arraySize = static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.colors', $value); 31 | 32 | $previousValues[] = $value; 33 | 34 | $this->assertEquals(count($previousValues), $arraySize); 35 | 36 | $storedArray = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 37 | 38 | $this->assertSame($previousValues, $storedArray); 39 | } 40 | 41 | public function testAppendMultipleValuesToArray() 42 | { 43 | $previousValues = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 44 | 45 | $multipleValues = ['multiple1', 'multiple2', 'multiple3']; 46 | $arraySize = static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.colors', ...$multipleValues); 47 | 48 | $previousValues = array_merge($previousValues, $multipleValues); 49 | 50 | $this->assertEquals(count($previousValues), $arraySize); 51 | 52 | $storedArray = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 53 | 54 | $this->assertSame($previousValues, $storedArray); 55 | } 56 | 57 | public function testAppendToIntegerException() 58 | { 59 | $this->expectException(ResponseException::class); 60 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.age', 'orange'); 61 | } 62 | 63 | public function testAppendToFloatException() 64 | { 65 | $this->expectException(ResponseException::class); 66 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.height', 'orange'); 67 | } 68 | 69 | public function testAppendToObjectException() 70 | { 71 | $this->expectException(ResponseException::class); 72 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.location', 'orange'); 73 | } 74 | 75 | public function testAppendToBooleanException() 76 | { 77 | $this->expectException(ResponseException::class); 78 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.license', 'orange'); 79 | } 80 | 81 | public function testAppendToStringException() 82 | { 83 | $this->expectException(ResponseException::class); 84 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.name', 'orange'); 85 | } 86 | 87 | public function testNonExistentKeyException() 88 | { 89 | $this->expectException(ResponseException::class); 90 | static::$reJsonClient->jsonArrayAppend('nonexistent', '.colors', 'orange'); 91 | } 92 | 93 | public function testNonExistentPathException() 94 | { 95 | $this->expectException(ResponseException::class); 96 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.nonexistent', 'orange'); 97 | } 98 | 99 | public function getValuesForAdding() 100 | { 101 | return [ 102 | ['green'], 103 | [23], 104 | [17.5], 105 | ['48'], 106 | ['18.5'], 107 | [['pink', 'grey']], 108 | [true], 109 | ["false"], 110 | [ 111 | [ 112 | 'key1' => 'value1', 113 | 'key2' => false, 114 | 'key3' => 18, 115 | 'key4' => 11.2, 116 | 'key5' => ['array-value1', 'array-value2'] 117 | ] 118 | ] 119 | ]; 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayIndexCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayIndexCommandTest extends BaseTestIntegration 22 | { 23 | public static function setUpBeforeClass(): void 24 | { 25 | parent::setUpBeforeClass(); 26 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.colors', ...static::getArrayColors()); 27 | } 28 | 29 | /** 30 | * @dataProvider getStoredColorIndexes 31 | * @param string $colorValue 32 | * @param int $colorIndex 33 | */ 34 | public function testArrayIndex(string $colorValue, int $colorIndex) 35 | { 36 | $whiteColorIndex = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, $colorValue, '.colors'); 37 | $this->assertEquals($colorIndex, $whiteColorIndex); 38 | } 39 | 40 | public function testArrayIndexSlice() 41 | { 42 | $secondWhiteColorIndex = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'white', '.colors', 1); 43 | $this->assertEquals(8, $secondWhiteColorIndex); 44 | 45 | $secondBlackColorIndex = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'black', '.colors', 2); 46 | $this->assertEquals(7, $secondBlackColorIndex); 47 | 48 | $secondBlackColorIndex = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'black', '.colors', 6, -1); 49 | $this->assertEquals(7, $secondBlackColorIndex); 50 | } 51 | 52 | public function testNotFoundValue() 53 | { 54 | $nonExistentColor = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'orange', '.colors'); 55 | $this->assertEquals(-1, $nonExistentColor); 56 | 57 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', 3); 58 | $this->assertEquals(-1, $colorNotFound); 59 | } 60 | 61 | public function testOutOfRange() 62 | { 63 | // out of ranges in slice are ignored and the original array is considered 64 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', 0, -15); 65 | $this->assertEquals(-1, $colorNotFound); 66 | 67 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', 12, 15); 68 | $this->assertEquals(-1, $colorNotFound); 69 | } 70 | 71 | public function testIndexForIntegerException() 72 | { 73 | $this->expectException(ResponseException::class); 74 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, '3', '.age'); 75 | } 76 | 77 | public function testIndexForFloatException() 78 | { 79 | $this->expectException(ResponseException::class); 80 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, '1.7', '.height'); 81 | } 82 | 83 | public function testIndexForObjectException() 84 | { 85 | $this->expectException(ResponseException::class); 86 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'country', '.location'); 87 | } 88 | 89 | public function testIndexForBooleanException() 90 | { 91 | $this->expectException(ResponseException::class); 92 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'true', '.license'); 93 | } 94 | 95 | public function testIndexForStringException() 96 | { 97 | $this->expectException(ResponseException::class); 98 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 't', '.name'); 99 | } 100 | 101 | public function testNonExistentKeyException() 102 | { 103 | $this->expectException(ResponseException::class); 104 | static::$reJsonClient->jsonArrayIndex('nonexistent', 'green', '.colors'); 105 | } 106 | 107 | public function testNonExistentPathException() 108 | { 109 | $this->expectException(ResponseException::class); 110 | static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.nonexistent'); 111 | } 112 | 113 | public function testInverseRange() 114 | { 115 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', 15, -15); 116 | $this->assertEquals(-1, $colorNotFound); 117 | } 118 | 119 | public function testNegativeIndexes() 120 | { 121 | // The slice of the array where the search is made is just the array with only the first element in the array, 122 | // since -9 = means the position 0 in the array and -8 means the position 1 in the array, so 'green' color, 123 | // which is in the position 2 is not found 124 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', -9, -8); 125 | $this->assertEquals(-1, $colorNotFound); 126 | 127 | // in this assertion 'green' color is found since the range contains the first 3 values in the array, since -6 128 | // means position 3 in the array counting from the end of the array 129 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', -9, -6); 130 | $this->assertEquals(2, $colorNotFound); 131 | 132 | // color is not found since the search is made on an empty array, since -15 value set start and stop to 0 133 | $colorNotFound = static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors', -15, -15); 134 | $this->assertEquals(-1, $colorNotFound); 135 | } 136 | 137 | public static function getArrayColors() 138 | { 139 | return ['green', 'yellow', 'red', 'purple', 'cyan', 'black', 'white']; 140 | } 141 | 142 | public function getStoredColorIndexes() 143 | { 144 | return[ 145 | ['white', 0], 146 | ['black', 1], 147 | ['green', 2], 148 | ['yellow', 3], 149 | ['red', 4], 150 | ['purple', 5], 151 | ['cyan', 6] 152 | ]; 153 | } 154 | } 155 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayInsertCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayInsertCommandTest extends BaseTestIntegration 22 | { 23 | public function testInsertAtTheBeginning() 24 | { 25 | $arraySize = static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.colors', 0, 'green', 'yellow'); 26 | $this->assertEquals(4, $arraySize); 27 | $this->assertEquals(0, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors')); 28 | $this->assertEquals(1, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'yellow', '.colors')); 29 | $this->assertEquals(2, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'white', '.colors')); 30 | $this->assertEquals(3, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'black', '.colors')); 31 | } 32 | 33 | public function testInsertInTheMiddle() 34 | { 35 | $arraySize = static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.colors', 2, 'red', 'blue'); 36 | $this->assertEquals(6, $arraySize); 37 | $this->assertEquals(0, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors')); 38 | $this->assertEquals(1, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'yellow', '.colors')); 39 | $this->assertEquals(2, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'red', '.colors')); 40 | $this->assertEquals(3, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'blue', '.colors')); 41 | $this->assertEquals(4, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'white', '.colors')); 42 | $this->assertEquals(5, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'black', '.colors')); 43 | } 44 | 45 | public function testInsertAtTheEnd() 46 | { 47 | $arraySize = static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.colors', -2, 'cyan', 'orange'); 48 | $this->assertEquals(8, $arraySize); 49 | $this->assertEquals(0, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'green', '.colors')); 50 | $this->assertEquals(1, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'yellow', '.colors')); 51 | $this->assertEquals(2, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'red', '.colors')); 52 | $this->assertEquals(3, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'blue', '.colors')); 53 | $this->assertEquals(4, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'cyan', '.colors')); 54 | $this->assertEquals(5, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'orange', '.colors')); 55 | $this->assertEquals(6, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'white', '.colors')); 56 | $this->assertEquals(7, static::$reJsonClient->jsonArrayIndex(Keys::DEFAULT_KEY, 'black', '.colors')); 57 | } 58 | 59 | public function testInsertInIntegerException() 60 | { 61 | $this->expectException(ResponseException::class); 62 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.age', 0, 'orange'); 63 | } 64 | 65 | public function testInsertInFloatException() 66 | { 67 | $this->expectException(ResponseException::class); 68 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.height', 0, 'orange'); 69 | } 70 | 71 | public function testInsertInObjectException() 72 | { 73 | $this->expectException(ResponseException::class); 74 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.location', 0, 'orange'); 75 | } 76 | 77 | public function testInsertInBooleanException() 78 | { 79 | $this->expectException(ResponseException::class); 80 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.license', 0, 'orange'); 81 | } 82 | 83 | public function testInsertInStringException() 84 | { 85 | $this->expectException(ResponseException::class); 86 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.name', 0, 'orange'); 87 | } 88 | 89 | public function testNonExistentKeyException() 90 | { 91 | $this->expectException(ResponseException::class); 92 | static::$reJsonClient->jsonArrayInsert('nonexistent', '.colors', 0, 'purple'); 93 | } 94 | 95 | public function testNonExistentPathException() 96 | { 97 | $this->expectException(ResponseException::class); 98 | static::$reJsonClient->jsonArrayInsert(Keys::DEFAULT_KEY, '.nonexistent', 0, 'purple'); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayLengthCommandTest extends BaseTestIntegration 22 | { 23 | public function testArrayLength() 24 | { 25 | $arrayLength = static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors'); 26 | $this->assertEquals(2, $arrayLength); 27 | } 28 | 29 | public function testLengthOfIntegerException() 30 | { 31 | $this->expectException(ResponseException::class); 32 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.age'); 33 | } 34 | 35 | public function testLengthOfFloatException() 36 | { 37 | $this->expectException(ResponseException::class); 38 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.height'); 39 | } 40 | 41 | public function testLengthOfObjectException() 42 | { 43 | $this->expectException(ResponseException::class); 44 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.location'); 45 | } 46 | 47 | public function testLengthOfBooleanException() 48 | { 49 | $this->expectException(ResponseException::class); 50 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.license'); 51 | } 52 | 53 | public function testLengthOfStringException() 54 | { 55 | $this->expectException(ResponseException::class); 56 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.name'); 57 | } 58 | 59 | public function testLengthOfEmptyArray() 60 | { 61 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors'); 62 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors'); 63 | $arrayLength = static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors'); 64 | $this->assertEquals(0, $arrayLength); 65 | } 66 | 67 | public function testNonExistentKeyReturnsException() 68 | { 69 | $this->expectException(ResponseException::class); 70 | static::$reJsonClient->jsonArrayLength('nonexistent', '.colors'); 71 | } 72 | 73 | public function testNonExistentPathException() 74 | { 75 | $this->expectException(ResponseException::class); 76 | static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.nonexistent'); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayPopCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayPopCommandTest extends BaseTestIntegration 22 | { 23 | public static function setUpBeforeClass(): void 24 | { 25 | parent::setUpBeforeClass(); 26 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.colors', ...static::getArrayColors()); 27 | } 28 | 29 | public function testArrayPop() 30 | { 31 | $this->assertEquals(['cyan', 'pink'], static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors')); 32 | $this->assertEquals(4, static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors')); 33 | } 34 | 35 | public function testArrayShift() 36 | { 37 | $this->assertEquals('white', static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors', 0)); 38 | $this->assertEquals(3, static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors')); 39 | } 40 | 41 | public function testArrayExtractFromTheMiddle() 42 | { 43 | $this->assertEquals('yellow', static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors', 1)); 44 | $this->assertEquals(2, static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors')); 45 | } 46 | 47 | public function testOutOfRange() 48 | { 49 | $this->assertEquals('purple', static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors', 10)); 50 | $this->assertEquals(1, static::$reJsonClient->jsonArrayLength(Keys::DEFAULT_KEY, '.colors')); 51 | } 52 | 53 | public function testPopFromIntegerException() 54 | { 55 | $this->expectException(ResponseException::class); 56 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.age'); 57 | } 58 | 59 | public function testPopFromFloatException() 60 | { 61 | $this->expectException(ResponseException::class); 62 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.height'); 63 | } 64 | 65 | public function testPopFromObjectException() 66 | { 67 | $this->expectException(ResponseException::class); 68 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.location'); 69 | } 70 | 71 | public function testPopFromBooleanException() 72 | { 73 | $this->expectException(ResponseException::class); 74 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.license'); 75 | } 76 | 77 | public function testPopFromStringException() 78 | { 79 | $this->expectException(ResponseException::class); 80 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.name'); 81 | } 82 | 83 | public function testNonExistentKeyException() 84 | { 85 | $this->expectException(ResponseException::class); 86 | static::$reJsonClient->jsonArrayPop('nonexistent', '.colors'); 87 | } 88 | 89 | public function testNonExistentPathException() 90 | { 91 | $this->expectException(ResponseException::class); 92 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.nonexistent'); 93 | } 94 | 95 | public function testEmptyArrayPopException() 96 | { 97 | $this->expectException(ResponseException::class); 98 | $this->assertEquals('black', static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors')); 99 | static::$reJsonClient->jsonArrayPop(Keys::DEFAULT_KEY, '.colors'); 100 | } 101 | 102 | public static function getArrayColors() 103 | { 104 | return ['yellow', 'purple', ['cyan', 'pink']]; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonArrayTrimCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonArrayTrimCommandTest extends BaseTestIntegration 22 | { 23 | public static function setUpBeforeClass(): void 24 | { 25 | parent::setUpBeforeClass(); 26 | static::$reJsonClient->jsonArrayAppend(Keys::DEFAULT_KEY, '.colors', ...static::getArrayColors()); 27 | } 28 | 29 | public function testArrayTrimAtTheBeginning() 30 | { 31 | $this->assertEquals(8, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 7, '.colors')); 32 | $this->assertNotContains('navy', static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 33 | } 34 | 35 | public function testArrayTrimInTheMiddle() 36 | { 37 | $this->assertEquals(6, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 1, 6, '.colors')); 38 | 39 | $colorsArray = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 40 | $this->assertNotContains('white', $colorsArray); 41 | $this->assertNotContains('orange', $colorsArray); 42 | } 43 | 44 | public function testArrayTrimAtTheEnd() 45 | { 46 | $this->assertEquals(5, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 4, '.colors')); 47 | 48 | $this->assertNotContains('cyan', static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 49 | } 50 | 51 | public function testArrayTrimForNegativeIndexes() 52 | { 53 | // since the current length of the array is 5, start = -5 means position 0 in the array and stop = 7, means 54 | // last position in the array, the result array is equal to the original 55 | $currentArray = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'); 56 | $newArraySize = static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, -5, 7, '.colors'); 57 | $this->assertEquals(5, $newArraySize); 58 | 59 | $this->assertEquals($currentArray, static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 60 | 61 | // similar as above assertion, stop = -1 means last position in the array 62 | $this->assertEquals(5, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, -5, -1, '.colors')); 63 | 64 | $this->assertEquals($currentArray, static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 65 | 66 | // stop = -2 means second-to-last position in the array, so the last element in the array is trimmed 67 | $this->assertEquals(4, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, -5, -2, '.colors')); 68 | 69 | $this->assertNotContains('purple', static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 70 | 71 | // the array has length = 4, start = -3 is the 2nd position in the array so 1st element is trimmed 72 | $this->assertEquals(3, static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, -3, -1, '.colors')); 73 | 74 | $this->assertNotContains('black', static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors')); 75 | } 76 | 77 | public function testTrimIntegerException() 78 | { 79 | $this->expectException(ResponseException::class); 80 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 20, '.age'); 81 | } 82 | 83 | public function testTrimFloatException() 84 | { 85 | $this->expectException(ResponseException::class); 86 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 20, '.height'); 87 | } 88 | 89 | public function testTrimObjectException() 90 | { 91 | $this->expectException(ResponseException::class); 92 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 20, '.location'); 93 | } 94 | 95 | public function testTrimBooleanException() 96 | { 97 | $this->expectException(ResponseException::class); 98 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 20, '.license'); 99 | } 100 | 101 | public function testTrimStringException() 102 | { 103 | $this->expectException(ResponseException::class); 104 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 20, '.name'); 105 | } 106 | 107 | public function testNonExistentKeyException() 108 | { 109 | $this->expectException(ResponseException::class); 110 | static::$reJsonClient->jsonArrayTrim('nonexistent', 0, 10, '.colors'); 111 | } 112 | 113 | public function testNonExistentPathException() 114 | { 115 | $this->expectException(ResponseException::class); 116 | static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 0, 10, '.nonexistent'); 117 | } 118 | 119 | public function testArrayTrimAnEmptyArray() 120 | { 121 | // an empty array is trimmed if start > array length or start > stop 122 | $newArraySize = static::$reJsonClient->jsonArrayTrim(Keys::DEFAULT_KEY, 4, 1, '.colors'); 123 | $this->assertEquals(0, $newArraySize); 124 | } 125 | 126 | public static function getArrayColors() 127 | { 128 | return ['green', 'yellow', 'red', 'purple', 'cyan', 'orange', 'navy']; 129 | } 130 | } 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonDelCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonDelCommandTest extends BaseTestIntegration 22 | { 23 | public function testPartialDeletion() 24 | { 25 | $this->assertTrue(static::$reJsonClient->jsonDelete(Keys::DEFAULT_KEY, '.location')); 26 | 27 | $storedData = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY); 28 | $this->assertFalse(isset($storedData['location'])); 29 | } 30 | 31 | public function testFullDeletion() 32 | { 33 | $this->assertTrue(static::$reJsonClient->jsonDelete(Keys::DEFAULT_KEY)); 34 | 35 | // after deleting the complete object, key doesn't exist in Redis any more and a exception is thrown 36 | $this->expectException(ResponseException::class); 37 | static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY); 38 | } 39 | 40 | public function testNonExistentKeyReturnsFalse() 41 | { 42 | $this->assertFalse(static::$reJsonClient->jsonDelete('nonexistent')); 43 | } 44 | 45 | public function testNonExistentPathReturnsFalse() 46 | { 47 | $this->assertFalse(static::$reJsonClient->jsonDelete(Keys::DEFAULT_KEY, '.nonexistent')); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonGetAsRespCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonGetAsRespCommandTest extends BaseTestIntegration 22 | { 23 | public function testJsonObjectIsRepresentedAsRESPArrays() 24 | { 25 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY); 26 | $this->assertEquals('{', $response[0]); 27 | 28 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.location'); 29 | $this->assertEquals('{', $response[0]); 30 | } 31 | 32 | public function testStringPathIsRepresentedAsRESPString() 33 | { 34 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.name'); 35 | $this->assertEquals('Peter', $response); 36 | } 37 | 38 | public function testIntegerPathIsRepresentedAsRESPInteger() 39 | { 40 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.age'); 41 | $this->assertEquals(38, $response); 42 | } 43 | 44 | public function testFloatPathIsRepresentedAsRESPString() 45 | { 46 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.height'); 47 | $this->assertEquals('1.79', $response); 48 | } 49 | 50 | public function testArrayPathIsRepresentedAsRESPArray() 51 | { 52 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.colors'); 53 | $this->assertEquals('[', $response[0]); 54 | $this->assertEquals('white', $response[1]); 55 | $this->assertEquals('black', $response[2]); 56 | } 57 | 58 | public function testBooleanPathIsRepresentedAsRESPString() 59 | { 60 | $response = static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.license'); 61 | $this->assertEquals('true', $response); 62 | } 63 | 64 | public function testNonExistentKeyReturnsException() 65 | { 66 | $this->expectException(ResponseException::class); 67 | static::$reJsonClient->jsonGetAsResp('nonexistent'); 68 | } 69 | 70 | public function testNonExistentPathException() 71 | { 72 | $this->expectException(ResponseException::class); 73 | static::$reJsonClient->jsonGetAsResp(Keys::DEFAULT_KEY, '.nonexistent'); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonGetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonGetCommandTest extends BaseTestIntegration 22 | { 23 | public function testGetFullData() 24 | { 25 | $this->assertSame(static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY), static::$defaultData); 26 | } 27 | 28 | public function testGetOnePathNoRoot() 29 | { 30 | $this->assertSame(static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.colors'), static::$defaultData['colors']); 31 | } 32 | 33 | public function testMultiplePaths() 34 | { 35 | $multipleStoredPath = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.name', '.location'); 36 | 37 | $this->assertSame($multipleStoredPath['.name'], static::$defaultData['name']); 38 | $this->assertSame($multipleStoredPath['.location'], static::$defaultData['location']); 39 | } 40 | 41 | public function testNonExistentKeyReturnsException() 42 | { 43 | $this->expectException(ResponseException::class); 44 | static::$reJsonClient->jsonGet('nonexistent'); 45 | } 46 | 47 | public function testNonExistentPathException() 48 | { 49 | $this->expectException(ResponseException::class); 50 | static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.nonexistent'); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonIncrementNumByCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonIncrementNumByCommandTest extends BaseTestIntegration 22 | { 23 | protected static $data = [ 24 | 'integerVal' => 38, 25 | 'floatVal' => 1.79, 26 | 'integerValAsString' => '56', 27 | 'floatValAsString' => '34.7', 28 | 'stringValStartingByInteger' => '3abc', 29 | 'stringValStartingByFloat' => '3.2abc' 30 | ]; 31 | 32 | public static function setUpBeforeClass(): void 33 | { 34 | static::$reJsonClient = self::getReJsonClient(); 35 | static::storeData(Keys::DEFAULT_KEY, self::$data); 36 | } 37 | 38 | public function testIncrementInteger() 39 | { 40 | $this->assertEquals(40, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.integerVal')); 41 | $this->assertEquals(42.7, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2.7, '.integerVal')); 42 | } 43 | 44 | public function testIncrementFloat() 45 | { 46 | $this->assertEquals(2.89, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 1.1, '.floatVal')); 47 | $this->assertEquals(3.89, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 1, '.floatVal')); 48 | } 49 | 50 | public function testIncrementByIntegerString() 51 | { 52 | $this->assertEquals(4.89, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, '1', '.floatVal')); 53 | } 54 | 55 | public function testIncrementByFloatString() 56 | { 57 | $this->assertEquals(44.0, static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, '1.3', '.integerVal')); 58 | } 59 | 60 | public function testIncrementByInvalidNumberAsStringException() 61 | { 62 | $this->expectException(ResponseException::class); 63 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, '1a', '.floatVal'); 64 | } 65 | 66 | public function testIncrementIntegerAsStringException() 67 | { 68 | $this->expectException(ResponseException::class); 69 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.integerValAsString'); 70 | } 71 | 72 | public function testIncrementFloatAsStringException() 73 | { 74 | $this->expectException(ResponseException::class); 75 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.floatValAsString'); 76 | } 77 | 78 | public function testIncrementStringStartingByIntegerException() 79 | { 80 | $this->expectException(ResponseException::class); 81 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.stringValStartingByInteger'); 82 | } 83 | 84 | public function testIncrementFloatStartingByFloatException() 85 | { 86 | $this->expectException(ResponseException::class); 87 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.stringValStartingByFloat'); 88 | } 89 | 90 | public function testNonExistentKeyException() 91 | { 92 | $this->expectException(ResponseException::class); 93 | static::$reJsonClient->jsonIncrementNumBy('nonexistent', 2); 94 | } 95 | 96 | public function testNonExistentPathException() 97 | { 98 | $this->expectException(ResponseException::class); 99 | static::$reJsonClient->jsonIncrementNumBy(Keys::DEFAULT_KEY, 2, '.nonexistent'); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonMemoryUsageCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonMemoryUsageCommandTest extends BaseTestIntegration 22 | { 23 | public function testResponseIsAPositiveInteger() 24 | { 25 | $response = static::$reJsonClient->jsonMemoryUsage(Keys::DEFAULT_KEY); 26 | $this->assertIsInt($response); 27 | $this->assertGreaterThan(0, $response); 28 | } 29 | 30 | public function testNonExistentKeyReturnException() 31 | { 32 | $this->expectException(ResponseException::class); 33 | static::$reJsonClient->jsonMemoryUsage('nonexistent'); 34 | } 35 | 36 | public function testNonExistentPathException() 37 | { 38 | $this->expectException(ResponseException::class); 39 | static::$reJsonClient->jsonMemoryUsage(Keys::DEFAULT_KEY, '.nonexistent'); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonMultiGetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Enum\Keys; 18 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 19 | 20 | class JsonMultiGetCommandTest extends BaseTestIntegration 21 | { 22 | protected static $data; 23 | 24 | public static function setUpBeforeClass(): void 25 | { 26 | parent::setUpBeforeClass(); 27 | 28 | static::$data = static::$defaultData; 29 | static::$data['email'] = 'some@example.com'; 30 | 31 | static::storeData(Keys::EXTENDED_KEY, static::$data); 32 | } 33 | 34 | public function testPartialMultiGet() 35 | { 36 | $result = static::$reJsonClient->jsonMultiGet([Keys::DEFAULT_KEY, Keys::EXTENDED_KEY], '.location'); 37 | $this->assertSame($result[0], $result[1]); 38 | } 39 | 40 | public function testFullMultiGet() 41 | { 42 | $result = static::$reJsonClient->jsonMultiGet([Keys::DEFAULT_KEY, Keys::EXTENDED_KEY]); 43 | $defaultResult = $result[0]; 44 | $extendedResult = $result[1]; 45 | 46 | $this->assertNotEquals($extendedResult, $defaultResult); 47 | $this->assertArrayNotHasKey('email', $defaultResult); 48 | $this->assertArrayHasKey('email', $extendedResult); 49 | 50 | unset($extendedResult['email']); 51 | 52 | $this->assertEquals($extendedResult, $defaultResult); 53 | } 54 | 55 | public function testMultiGetWithOnlyOneKey() 56 | { 57 | $result = static::$reJsonClient->jsonMultiGet([Keys::DEFAULT_KEY]); 58 | $this->assertSame($result[0], static::$defaultData); 59 | } 60 | 61 | public function testMultiGetWithNoKeys() 62 | { 63 | $result = static::$reJsonClient->jsonMultiGet([], '.location'); 64 | $this->assertEmpty($result); 65 | 66 | $result = static::$reJsonClient->jsonMultiGet([]); 67 | $this->assertEmpty($result); 68 | } 69 | 70 | public function testNonExistentKeys() 71 | { 72 | $result = static::$reJsonClient->jsonMultiGet([Keys::DEFAULT_KEY, 'nonexistent']); 73 | 74 | $this->assertSame(static::$defaultData, $result[0]); 75 | $this->assertNull($result[1]); 76 | } 77 | 78 | public function testNonExistentPath() 79 | { 80 | $result = static::$reJsonClient->jsonMultiGet([Keys::DEFAULT_KEY, Keys::EXTENDED_KEY], '.nonexistent'); 81 | 82 | $this->assertNull($result[0]); 83 | $this->assertNull($result[1]); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonMultiplyNumByCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonMultiplyNumByCommandTest extends BaseTestIntegration 22 | { 23 | protected static $data = [ 24 | 'integerVal' => 38, 25 | 'floatVal' => 1.79, 26 | 'integerValAsString' => '56', 27 | 'floatValAsString' => '34.7', 28 | 'stringValStartingByInteger' => '3abc', 29 | 'stringValStartingByFloat' => '3abc' 30 | ]; 31 | 32 | public static function setUpBeforeClass(): void 33 | { 34 | static::$reJsonClient = self::getReJsonClient(); 35 | static::storeData(Keys::DEFAULT_KEY, self::$data); 36 | } 37 | 38 | public function testMultiplyInteger() 39 | { 40 | $this->assertEquals(76, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.integerVal')); 41 | $this->assertEquals(190, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2.5, '.integerVal')); 42 | } 43 | 44 | public function testMultiplyFloat() 45 | { 46 | $this->assertEquals(1.969, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 1.1, '.floatVal')); 47 | $this->assertEquals(3.938, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.floatVal')); 48 | } 49 | 50 | public function testMultiplyByIntegerString() 51 | { 52 | $this->assertEquals(7.876, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, '2', '.floatVal')); 53 | } 54 | 55 | public function testIncrementByFloatString() 56 | { 57 | $this->assertEquals(285.0, static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, '1.5', '.integerVal')); 58 | } 59 | 60 | public function testMultiplyByInvalidNumberAsStringException() 61 | { 62 | $this->expectException(ResponseException::class); 63 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, '1a', '.floatVal'); 64 | } 65 | 66 | public function testMultiplyIntegerAsStringException() 67 | { 68 | $this->expectException(ResponseException::class); 69 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.integerValAsString'); 70 | } 71 | 72 | public function testMultiplyFloatAsStringException() 73 | { 74 | $this->expectException(ResponseException::class); 75 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.floatValAsString'); 76 | } 77 | 78 | public function testMultiplyStringStartingByIntegerException() 79 | { 80 | $this->expectException(ResponseException::class); 81 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.stringValStartingByInteger'); 82 | } 83 | 84 | public function testMultiplyFloatStartingByFloatException() 85 | { 86 | $this->expectException(ResponseException::class); 87 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.stringValStartingByFloat'); 88 | } 89 | 90 | public function testNonExistentKeyException() 91 | { 92 | $this->expectException(ResponseException::class); 93 | static::$reJsonClient->jsonMultiplyNumBy('nonexistent', 2); 94 | } 95 | 96 | public function testNonExistentPathException() 97 | { 98 | $this->expectException(ResponseException::class); 99 | static::$reJsonClient->jsonMultiplyNumBy(Keys::DEFAULT_KEY, 2, '.nonexistent'); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonObjectKeysCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonObjectKeysCommandTest extends BaseTestIntegration 22 | { 23 | public function testKeysInDefaultDataObject() 24 | { 25 | $expectedKeys = array_keys(static::$defaultData); 26 | $storedKeys = static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY); 27 | $this->assertSame($expectedKeys, $storedKeys); 28 | 29 | $expectedKeys = array_keys(static::$defaultData['location']); 30 | $storedKeys = static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.location'); 31 | $this->assertSame($expectedKeys, $storedKeys); 32 | } 33 | 34 | public function testKeysInArrayPathException() 35 | { 36 | $this->expectException(ResponseException::class); 37 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.colors'); 38 | } 39 | 40 | public function testKeysInStringPathException() 41 | { 42 | $this->expectException(ResponseException::class); 43 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.name'); 44 | } 45 | 46 | public function testKeysInIntegerPathException() 47 | { 48 | $this->expectException(ResponseException::class); 49 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.age'); 50 | } 51 | 52 | public function testKeysInFloatPathException() 53 | { 54 | $this->expectException(ResponseException::class); 55 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.height'); 56 | } 57 | 58 | public function testKeysInBooleanPathException() 59 | { 60 | $this->expectException(ResponseException::class); 61 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.license'); 62 | } 63 | 64 | public function testNonExistentKeyReturnsException() 65 | { 66 | $this->expectException(ResponseException::class); 67 | static::$reJsonClient->jsonObjectKeys('nonexistent'); 68 | } 69 | 70 | public function testNonExistentPathReturnsException() 71 | { 72 | $this->expectException(ResponseException::class); 73 | static::$reJsonClient->jsonObjectKeys(Keys::DEFAULT_KEY, '.nonexistent'); 74 | } 75 | 76 | public function testEmptyObjectReturnsEmptyArrayKeys() 77 | { 78 | static::$reJsonClient->jsonSet(Keys::KEY_TO_EMPTY, ['foo' => 'bar']); 79 | static::$reJsonClient->jsonDelete(Keys::KEY_TO_EMPTY, 'foo'); 80 | $this->assertEmpty(static::$reJsonClient->jsonObjectKeys(Keys::KEY_TO_EMPTY)); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonObjectLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonObjectLengthCommandTest extends BaseTestIntegration 22 | { 23 | public function testKeysLengthInDefaultDataObject() 24 | { 25 | $expectedKeysLength = count(array_keys(static::$defaultData)); 26 | $storedKeysLength = static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY); 27 | $this->assertSame($expectedKeysLength, $storedKeysLength); 28 | 29 | $expectedKeysLength = count(array_keys(static::$defaultData['location'])); 30 | $storedKeysLength = static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.location'); 31 | $this->assertSame($expectedKeysLength, $storedKeysLength); 32 | } 33 | 34 | public function testKeysLengthInArrayPathException() 35 | { 36 | $this->expectException(ResponseException::class); 37 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.colors'); 38 | } 39 | 40 | public function testKeysLengthInStringPathException() 41 | { 42 | $this->expectException(ResponseException::class); 43 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.name'); 44 | } 45 | 46 | public function testKeysLengthInIntegerPathException() 47 | { 48 | $this->expectException(ResponseException::class); 49 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.age'); 50 | } 51 | 52 | public function testKeysLengthInFloatPathException() 53 | { 54 | $this->expectException(ResponseException::class); 55 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.height'); 56 | } 57 | 58 | public function testKeysLengthInBooleanPathException() 59 | { 60 | $this->expectException(ResponseException::class); 61 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.license'); 62 | } 63 | 64 | public function testNonExistentKeyReturnsException() 65 | { 66 | $this->expectException(ResponseException::class); 67 | static::$reJsonClient->jsonObjectLength('nonexistent'); 68 | } 69 | 70 | public function testNonExistentPathException() 71 | { 72 | $this->expectException(ResponseException::class); 73 | static::$reJsonClient->jsonObjectLength(Keys::DEFAULT_KEY, '.nonexistent'); 74 | } 75 | 76 | public function testEmptyObjectException() 77 | { 78 | static::$reJsonClient->jsonSet(Keys::KEY_TO_EMPTY, ['foo' => 'bar']); 79 | static::$reJsonClient->jsonDelete(Keys::KEY_TO_EMPTY, 'foo'); 80 | $this->expectException(ResponseException::class); 81 | static::$reJsonClient->jsonObjectLength('empty-key'); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonSetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonSetCommandTest extends BaseTestIntegration 22 | { 23 | public static function setUpBeforeClass(): void 24 | { 25 | static::$reJsonClient = self::getReJsonClient(); 26 | } 27 | 28 | public function testInsertionsWithPHPStructures() 29 | { 30 | $this->assertTrue( 31 | static::$reJsonClient->jsonSet( 32 | Keys::DEFAULT_KEY, 33 | ['name' => "Peter", 'age' => 34, 'height' => 1.79] 34 | ) 35 | ); 36 | $this->assertTrue( 37 | static::$reJsonClient->jsonSet( 38 | Keys::DEFAULT_KEY, 39 | ['address' => 'Pub Street, 39', 'city' => 'Dublin', 'country' => 'Ireland'], 40 | '.location' 41 | ) 42 | ); 43 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, ['white', 'black'], '.colors')); 44 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, true, '.license')); 45 | } 46 | 47 | public function testUpdates() 48 | { 49 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, '37', '.age')); 50 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, 38, '.age')); 51 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, '1.73', '.height')); 52 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, 1.79, '.height')); 53 | $this->assertTrue(static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, 'Limerick', '.location.city')); 54 | } 55 | 56 | public function testUpdateExistingPathWithNXException() 57 | { 58 | // with NX option set we cannot update an existing path ('age' already exists) 59 | $this->expectException(ResponseException::class); 60 | static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, '98', '.age', 'NX'); 61 | } 62 | 63 | public function testUpdateNonExistingPathWithXXException() 64 | { 65 | // with XX option set we only can update an existing path ('state' does not exist) 66 | $this->expectException(ResponseException::class); 67 | static::$reJsonClient->jsonSet(Keys::DEFAULT_KEY, 'Leinster', '.location.state', 'XX'); 68 | } 69 | 70 | public function testFinalStoreData() 71 | { 72 | $this->assertSame(static::$defaultData, static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY)); 73 | } 74 | 75 | public function testSettingNewKeyInNoRootPathException() 76 | { 77 | $this->expectException(ResponseException::class); 78 | static::$reJsonClient->jsonSet('where-is-my-key', ['name' => "Eva", 'age' => 43], '.somefield'); 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonStringAppendCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonStringAppendCommandTest extends BaseTestIntegration 22 | { 23 | public function testAppendString() 24 | { 25 | $length = static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, ' Newman', '.name'); 26 | $this->assertEquals(strlen('Peter Newman'), $length); 27 | 28 | $result = static::$reJsonClient->jsonGet(Keys::DEFAULT_KEY, '.name'); 29 | $this->assertEquals('Peter Newman', $result, true); 30 | } 31 | 32 | public function testAppendStringOnNumberPathException() 33 | { 34 | $this->expectException(ResponseException::class); 35 | static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, 'years', '.age'); 36 | } 37 | 38 | public function testAppendStringOnObjectPathException() 39 | { 40 | $this->expectException(ResponseException::class); 41 | static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, 'years', '.location'); 42 | } 43 | 44 | public function testAppendStringOnArrayPathException() 45 | { 46 | $this->expectException(ResponseException::class); 47 | static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, 'years', '.colors'); 48 | } 49 | 50 | public function testAppendStringOnBooleanPathException() 51 | { 52 | $this->expectException(ResponseException::class); 53 | static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, 'years', '.license'); 54 | } 55 | 56 | public function testNonExistentKeyException() 57 | { 58 | $this->expectException(ResponseException::class); 59 | static::$reJsonClient->jsonStringAppend('nonexistent', 'abc'); 60 | } 61 | 62 | public function testNonExistentPathException() 63 | { 64 | $this->expectException(ResponseException::class); 65 | static::$reJsonClient->jsonStringAppend(Keys::DEFAULT_KEY, 'abc', '.nonexistent'); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonStringLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonStringLengthCommandTest extends BaseTestIntegration 22 | { 23 | /** 24 | * @dataProvider getStringPathsProvider 25 | * @param string $path 26 | * @param int $length 27 | */ 28 | public function testStringPathLength(string $path, int $length) 29 | { 30 | $result = static::$reJsonClient->jsonStringLength(Keys::DEFAULT_KEY, $path); 31 | $this->assertEquals($length, $result); 32 | } 33 | 34 | /** 35 | * @dataProvider getNonStringPathsProvider 36 | * @param string $path 37 | */ 38 | public function testPathTypeIsNotStringException(string $path) 39 | { 40 | $this->expectException(ResponseException::class); 41 | static::$reJsonClient->jsonStringLength(Keys::DEFAULT_KEY, $path); 42 | } 43 | 44 | /** 45 | * a nonexistent key return NULL 46 | */ 47 | public function testNonExistentKeyReturnsException() 48 | { 49 | $this->expectException(ResponseException::class); 50 | static::$reJsonClient->jsonStringLength('nonexistent'); 51 | } 52 | 53 | /** 54 | * a nonexistent path throws an exception 55 | */ 56 | public function testNonExistentPathException() 57 | { 58 | $this->expectException(ResponseException::class); 59 | static::$reJsonClient->jsonStringLength(Keys::DEFAULT_KEY, '.nonexistent'); 60 | } 61 | 62 | public function getStringPathsProvider() 63 | { 64 | return [ 65 | ['.name', 5], 66 | ['.location.address', 14], 67 | ['.location.city', 8], 68 | ['.location.country', 7] 69 | ]; 70 | } 71 | 72 | public function getNonStringPathsProvider() 73 | { 74 | return [ 75 | ['.age'], 76 | ['.height'], 77 | ['.colors'], 78 | ['.license'], 79 | ['.'] 80 | ]; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /tests/Integration/Command/JsonTypeCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Integration\Command; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Integration\BaseTestIntegration; 20 | 21 | class JsonTypeCommandTest extends BaseTestIntegration 22 | { 23 | /** 24 | * @dataProvider getTypesDataProvider 25 | * @param string $path 26 | * @param string $expectedType 27 | */ 28 | public function testType(string $path, string $expectedType) 29 | { 30 | $type = static::$reJsonClient->jsonType(Keys::DEFAULT_KEY, $path); 31 | $this->assertSame($expectedType, $type); 32 | } 33 | 34 | public function testNonExistentKeyException() 35 | { 36 | $this->expectException(ResponseException::class); 37 | static::$reJsonClient->jsonType('nonexistent'); 38 | } 39 | 40 | public function testNonExistentPathException() 41 | { 42 | $this->expectException(ResponseException::class); 43 | static::$reJsonClient->jsonType(Keys::DEFAULT_KEY, '.nonexistent'); 44 | } 45 | 46 | public function getTypesDataProvider() 47 | { 48 | return [ 49 | ['.', 'object'], 50 | ['.name', 'string'], 51 | ['.age', 'integer'], 52 | ['.height', 'number'], 53 | ['.location', 'object'], 54 | ['.colors', 'array'], 55 | ['.license', 'boolean'] 56 | ]; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /tests/Unit/Adapter/AdapterProviderTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Adapter; 16 | 17 | use Averias\RedisJson\Adapter\AdapterProvider; 18 | use Averias\RedisJson\Adapter\RedisClientAdapterInterface; 19 | use Averias\RedisJson\Enum\Module; 20 | use Averias\RedisJson\Enum\Version; 21 | use Averias\RedisJson\Exception\InvalidRedisVersionException; 22 | use Averias\RedisJson\Exception\RedisJsonModuleNotInstalledException; 23 | use Averias\RedisJson\Adapter\RedisClientAdapter; 24 | use Averias\RedisJson\Validator\RedisClientValidator; 25 | use PHPUnit\Framework\MockObject\MockObject; 26 | use PHPUnit\Framework\TestCase; 27 | 28 | class AdapterProviderTest extends TestCase 29 | { 30 | /** 31 | * @dataProvider getDataProviderForRedisClientConfigurationExceptions 32 | * @param array $info 33 | * @param array $moduleList 34 | * @param string $exception 35 | * @param string $exceptionMessage 36 | */ 37 | public function testRedisClientConfigurationExceptions( 38 | array $info, 39 | array $moduleList, 40 | string $exception, 41 | string $exceptionMessage 42 | ) { 43 | $this->expectException($exception); 44 | $this->expectExceptionMessage($exceptionMessage); 45 | 46 | $providerMock = $this->getMockBuilder(AdapterProvider::class) 47 | ->setConstructorArgs([new RedisClientValidator()]) 48 | ->onlyMethods(['getRedisClient']) 49 | ->getMock(); 50 | $providerMock->method('getRedisClient') 51 | ->willReturn($this->getRedisClientMock($info, $moduleList)); 52 | $providerMock->get(); 53 | } 54 | 55 | public function testGetRedisClientAdapterInterface() 56 | { 57 | $providerMock = $this->getMockBuilder(AdapterProvider::class) 58 | ->setConstructorArgs([new RedisClientValidator()]) 59 | ->onlyMethods(['getRedisClient']) 60 | ->getMock(); 61 | $providerMock->method('getRedisClient') 62 | ->willReturn( 63 | $this->getRedisClientMock( 64 | ['redis_version' => Version::REDIS_JSON_CLIENT_4X0], 65 | [[Module::REDIS_JSON_MODULE_NAME]] 66 | ) 67 | ); 68 | $adapter = $providerMock->get(); 69 | $this->assertInstanceOf(RedisClientAdapterInterface::class, $adapter); 70 | } 71 | 72 | protected function getRedisClientMock(array $info, array $moduleList): MockObject 73 | { 74 | $redisClientMock = $this->getMockBuilder(RedisClientAdapter::class) 75 | ->disableOriginalConstructor() 76 | ->onlyMethods(['executeCommandByName', 'executeRawCommand']) 77 | ->getMock(); 78 | 79 | $redisClientMock->method('executeCommandByName') 80 | ->with('INFO') 81 | ->willReturn($info); 82 | $redisClientMock->method('executeRawCommand') 83 | ->with('MODULE', 'list') 84 | ->willReturn($moduleList); 85 | 86 | return $redisClientMock; 87 | } 88 | 89 | public function getDataProviderForRedisClientConfigurationExceptions(): array 90 | { 91 | return [ 92 | [ 93 | ['redis_version' => '3.2'], 94 | [['foo', 'bar'], ['zoo', 'bad']], 95 | InvalidRedisVersionException::class, 96 | 'invalid redis server version 3.2, expected 4.0+.' 97 | ], 98 | [ 99 | ['redis_version' => '4.3'], 100 | [['foo', 'bar'], ['zoo', 'bad']], 101 | RedisJsonModuleNotInstalledException::class, 102 | 'RedisJson module not installed in Redis server.' 103 | ] 104 | ]; 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /tests/Unit/Client/RedisJsonClientTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Client; 16 | 17 | use Averias\RedisJson\Adapter\RedisClientAdapterInterface; 18 | use Averias\RedisJson\Client\RedisJsonClient; 19 | use Averias\RedisJson\Enum\JsonCommands; 20 | use PHPUnit\Framework\MockObject\MockObject; 21 | use PHPUnit\Framework\MockObject\Rule\InvokedCount; 22 | use PHPUnit\Framework\TestCase; 23 | 24 | class RedisJsonClientTest extends TestCase 25 | { 26 | public function testExecuteRawCommand(): void 27 | { 28 | $mock = $this->getAdapterMock($this->once(), $this->never()); 29 | $client = new RedisJsonClient($mock); 30 | $result = $client->executeRawCommand(JsonCommands::DELETE, 'key', 'path'); 31 | $this->assertTrue($result); 32 | } 33 | 34 | public function testExecuteCommandByName(): void 35 | { 36 | $mock = $this->getAdapterMock($this->never(), $this->once()); 37 | $client = new RedisJsonClient($mock); 38 | $result = $client->hget('hash-test', 'hash-field'); 39 | $this->assertTrue($result); 40 | } 41 | 42 | protected function getAdapterMock(InvokedCount $rawCommandExpects, InvokedCount $commandByNameExpects): MockObject 43 | { 44 | $mock = $this->getMockBuilder(RedisClientAdapterInterface::class) 45 | ->disableOriginalConstructor() 46 | ->onlyMethods(['executeJsonCommand', 'executeCommandByName', 'executeRawCommand']) 47 | ->getMock(); 48 | $mock->expects($rawCommandExpects) 49 | ->method('executeRawCommand') 50 | ->with(JsonCommands::DELETE, 'key', 'path') 51 | ->willReturn(true); 52 | $mock->expects($commandByNameExpects) 53 | ->method('executeCommandByName') 54 | ->with('hget', ['hash-test', 'hash-field']) 55 | ->willReturn(true); 56 | 57 | return $mock; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /tests/Unit/Command/BaseTestJsonCommandTrait.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command; 16 | 17 | use Averias\RedisJson\Client\RedisJsonClient; 18 | use Averias\RedisJson\Client\RedisJsonClientInterface; 19 | use Averias\RedisJson\Adapter\RedisClientAdapter; 20 | use PHPUnit\Framework\MockObject\MockObject; 21 | use PHPUnit\Framework\TestCase; 22 | 23 | class BaseTestJsonCommandTrait extends TestCase 24 | { 25 | public function getRedisJsonClient($returnValue, array $arguments): RedisJsonClientInterface 26 | { 27 | return new RedisJsonClient($this->getRedisClientAdapterMock($returnValue, $arguments)); 28 | } 29 | 30 | public function getRedisClientAdapterMock($returnValue, array $arguments): MockObject 31 | { 32 | $mock = $this->getMockBuilder(RedisClientAdapter::class)->disableOriginalConstructor()->getMock(); 33 | $mock->expects($this->any()) 34 | ->method('executeJsonCommand') 35 | ->with(...$arguments) 36 | ->willReturn($returnValue); 37 | 38 | return $mock; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayAppendCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Exception\ResponseException; 19 | use Averias\RedisJson\Enum\Keys; 20 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 21 | 22 | class JsonArrayAppendCommandTest extends BaseTestJsonCommandTrait 23 | { 24 | /** 25 | * @dataProvider getJsonArrayAppendDataProvider 26 | * @param array $arguments 27 | * @param int $returnedValue 28 | * @param string $key 29 | * @param string $path 30 | * @param array $values 31 | */ 32 | public function testJsonArrayAppend( 33 | array $arguments, 34 | int $returnedValue, 35 | string $key, 36 | string $path, 37 | array $values 38 | ): void { 39 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 40 | $result = $mock->jsonArrayAppend($key, $path, ...$values); 41 | $this->assertEquals($returnedValue, $result); 42 | } 43 | 44 | public function testJsonArrayAppendException(): void 45 | { 46 | $this->expectException(ResponseException::class); 47 | $this->expectExceptionMessage('you need to provide at least one value to append in JSON.ARRAPPEND command'); 48 | $mock = $this->getRedisJsonClient( 49 | 1, 50 | [JsonCommands::ARRAY_APPEND, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.']] 51 | ); 52 | $mock->jsonArrayAppend(Keys::DEFAULT_KEY, '.', ...[]); 53 | } 54 | 55 | public function getJsonArrayAppendDataProvider(): array 56 | { 57 | return [ 58 | [ 59 | [JsonCommands::ARRAY_APPEND, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', '"value1"', '14.3']], 60 | 3, 61 | Keys::DEFAULT_KEY, 62 | '.', 63 | ['value1', 14.3] 64 | ], 65 | [ 66 | [JsonCommands::ARRAY_APPEND, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', '{"name":"foo"}', 'true']], 67 | 6, 68 | Keys::DEFAULT_KEY, 69 | '.', 70 | [["name" => "foo"], true] 71 | ] 72 | ]; 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayIndexCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonArrayIndexCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | public function testJsonArrayIndex(): void 24 | { 25 | $mock = $this->getRedisJsonClient( 26 | 3, 27 | [JsonCommands::ARRAY_INDEX, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', '"value"', 0, 0]] 28 | ); 29 | $result = $mock->jsonArrayIndex(Keys::DEFAULT_KEY, 'value', '.'); 30 | $this->assertEquals(3, $result); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayInsertCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Exception\ResponseException; 19 | use Averias\RedisJson\Enum\Keys; 20 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 21 | 22 | class JsonArrayInsertCommandTest extends BaseTestJsonCommandTrait 23 | { 24 | /** 25 | * @dataProvider getJsonArrayInsertDataProvider 26 | * @param array $arguments 27 | * @param int $returnedValue 28 | * @param string $key 29 | * @param string $path 30 | * @param int $index 31 | * @param array $values 32 | */ 33 | public function testJsonInsertAppend( 34 | array $arguments, 35 | int $returnedValue, 36 | string $key, 37 | string $path, 38 | int $index, 39 | array $values 40 | ): void { 41 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 42 | $result = $mock->jsonArrayInsert($key, $path, $index, ...$values); 43 | $this->assertEquals($returnedValue, $result); 44 | } 45 | 46 | public function testJsonArrayInsertException(): void 47 | { 48 | $this->expectException(ResponseException::class); 49 | $this->expectExceptionMessage('you need to provide at least one value to insert in JSON.ARRINSERT command'); 50 | $mock = $this->getRedisJsonClient( 51 | 5, 52 | [JsonCommands::ARRAY_INSERT, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', 1]] 53 | ); 54 | $mock->jsonArrayInsert(Keys::DEFAULT_KEY, '.', 1, ...[]); 55 | } 56 | 57 | public function getJsonArrayInsertDataProvider(): array 58 | { 59 | return [ 60 | [ 61 | [JsonCommands::ARRAY_INSERT, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', 3, '"value1"', '14.3']], 62 | 5, 63 | Keys::DEFAULT_KEY, 64 | '.', 65 | 3, 66 | ['value1', 14.3] 67 | ], 68 | [ 69 | [JsonCommands::ARRAY_INSERT, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', 2, '{"name":"foo"}', 'true']], 70 | 4, 71 | Keys::DEFAULT_KEY, 72 | '.', 73 | 2, 74 | [["name" => "foo"], true] 75 | ] 76 | ]; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonArrayLengthCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonArrayLengthDataProvider 25 | * @param int|null $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonArrayLength(?int $returnedValue, string $key, string $path): void 30 | { 31 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::ARRAY_LENGTH, [$key], [$key, $path]]); 32 | $result = $mock->jsonArrayLength($key, $path); 33 | $this->assertEquals($returnedValue, $result); 34 | } 35 | 36 | public function getJsonArrayLengthDataProvider(): array 37 | { 38 | return [ 39 | [5, Keys::DEFAULT_KEY, '.path'], 40 | [null, Keys::DEFAULT_KEY, '.path'] 41 | ]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayPopCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonArrayPopCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonArrayPopDataProvider 25 | * @param array $arguments 26 | * @param int $returnedValue 27 | * @param string $key 28 | * @param string $path 29 | * @param bool $resultValue 30 | */ 31 | public function testJsonArrayPop( 32 | array $arguments, 33 | $returnedValue, 34 | string $key, 35 | string $path, 36 | $resultValue 37 | ): void { 38 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 39 | $result = $mock->jsonArrayPop($key, $path); 40 | $this->assertEquals($resultValue, $result); 41 | } 42 | 43 | public function getJsonArrayPopDataProvider(): array 44 | { 45 | return [ 46 | [ 47 | [JsonCommands::ARRAY_POP, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', -1]], 48 | '{"name":"foo"}', 49 | Keys::DEFAULT_KEY, 50 | '.', 51 | '{"name":"foo"}' 52 | ], 53 | [ 54 | [JsonCommands::ARRAY_POP, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', -1]], 55 | null, 56 | Keys::DEFAULT_KEY, 57 | '.', 58 | null 59 | ] 60 | ]; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonArrayTrimCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonArrayTrimCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonArrayTrimDataProvider 25 | * @param int|null $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | * @param int $start 29 | * @param int $stop 30 | */ 31 | public function testJsonArrayTrim(?int $returnedValue, string $key, string $path, int $start, int $stop): void 32 | { 33 | $mock = $this->getRedisJsonClient( 34 | $returnedValue, 35 | [JsonCommands::ARRAY_TRIM, [$key], [$key, $path, $start, $stop]] 36 | ); 37 | $result = $mock->jsonArrayTrim($key, $start, $stop, $path); 38 | $this->assertEquals($returnedValue, $result); 39 | } 40 | 41 | public function getJsonArrayTrimDataProvider(): array 42 | { 43 | return [ 44 | [3, Keys::DEFAULT_KEY, '.path', 1, 3], 45 | [0, Keys::DEFAULT_KEY, '.path', 3, 1] 46 | ]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonDeleteCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonDeleteCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonDeleteDataProvider 25 | * @param int $returnedValue 26 | * @param bool $resultValue 27 | */ 28 | public function testJsonDelete(?int $returnedValue, bool $resultValue) 29 | { 30 | $arguments = [JsonCommands::DELETE, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.']]; 31 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 32 | $result = $mock->jsonDelete(Keys::DEFAULT_KEY, '.'); 33 | $this->assertEquals($resultValue, $result); 34 | } 35 | 36 | public function getJsonDeleteDataProvider(): array 37 | { 38 | return [ 39 | [0, false], 40 | [1, true], 41 | [null, false] 42 | ]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonForgetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonForgetCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonForgetDataProvider 25 | * @param int $returnedValue 26 | * @param bool $resultValue 27 | */ 28 | public function testJsonForget(?int $returnedValue, bool $resultValue) 29 | { 30 | $arguments = [JsonCommands::DELETE, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.']]; 31 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 32 | $result = $mock->jsonForget(Keys::DEFAULT_KEY, '.'); 33 | $this->assertEquals($resultValue, $result); 34 | } 35 | 36 | public function getJsonForgetDataProvider(): array 37 | { 38 | return [ 39 | [0, false], 40 | [1, true], 41 | [null, false] 42 | ]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonGetAsRespCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonGetAsRespCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonGetAsRespDataProvider 25 | * @param mixed $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonGetAsResp($returnedValue, string $key, string $path): void 30 | { 31 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::GET_AS_RESP, [$key], [$key, $path]]); 32 | $result = $mock->jsonGetAsResp($key, $path); 33 | $this->assertEquals($returnedValue, $result); 34 | } 35 | 36 | public function getJsonGetAsRespDataProvider(): array 37 | { 38 | return [ 39 | [['[', 'value1', 23, ']'], Keys::DEFAULT_KEY, '.'], 40 | ['Peter', Keys::DEFAULT_KEY, '.'], 41 | [56, Keys::DEFAULT_KEY, '.'], 42 | [null, Keys::DEFAULT_KEY, '.'] 43 | ]; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonGetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonGetCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonGetDataProvider 25 | * @param array $arguments 26 | * @param int $returnedValue 27 | * @param string $key 28 | * @param array $paths 29 | * @param bool $resultValue 30 | */ 31 | public function testJsonGet(array $arguments, $returnedValue, string $key, array $paths, $resultValue): void 32 | { 33 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 34 | $result = $mock->jsonGet($key, ...$paths); 35 | $this->assertEquals($resultValue, $result); 36 | } 37 | 38 | public function getJsonGetDataProvider(): array 39 | { 40 | $value = '{"name":"foo"}'; 41 | return [ 42 | [ 43 | [JsonCommands::GET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1']], 44 | '{".path1":' . $value . '}', 45 | Keys::DEFAULT_KEY, 46 | ['.path1'], 47 | '{".path1":' . $value . '}' 48 | ], 49 | [ 50 | [JsonCommands::GET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1', '.path2']], 51 | '{".path1":' . $value . ',".path2":' . $value . '}', 52 | Keys::DEFAULT_KEY, 53 | ['.path1', '.path2'], 54 | '{".path1":' . $value . ',".path2":' . $value . '}' 55 | ], 56 | [ 57 | [JsonCommands::GET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.']], 58 | '{".":' . $value . '}', 59 | Keys::DEFAULT_KEY, 60 | [], 61 | '{".":' . $value . '}' 62 | ], 63 | [ 64 | [JsonCommands::GET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.']], 65 | null, 66 | Keys::DEFAULT_KEY, 67 | [], 68 | null 69 | ] 70 | ]; 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonIncrementNumByCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonIncrementNumByCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonIncrementNumByDataProvider 25 | * @param int $returnedValue 26 | * @param string $key 27 | * @param $number 28 | * @param string $path 29 | * @param bool $resultValue 30 | */ 31 | public function testJsonIncrementNumBy($returnedValue, string $key, $number, string $path, $resultValue) 32 | { 33 | $arguments = [JsonCommands::INCREMENT_NUM_BY, [$key], [$key, $path, $number]]; 34 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 35 | $result = $mock->jsonIncrementNumBy($key, $number, $path); 36 | $this->assertEquals($resultValue, $result); 37 | } 38 | 39 | public function getJsonIncrementNumByDataProvider(): array 40 | { 41 | return [ 42 | ['20', Keys::DEFAULT_KEY, 10, '.', 20], 43 | ['11.79', Keys::DEFAULT_KEY, 10, '.', 11.79] 44 | ]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonMemoryUsageCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonMemoryUsageCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonMemoryUsageDataProvider 25 | * @param int|null $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonMemoryUsage(?int $returnedValue, string $key, string $path): void 30 | { 31 | $arguments = [JsonCommands::MEMORY_USAGE, [$key], ['MEMORY', $key, $path]]; 32 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 33 | $result = $mock->jsonMemoryUsage($key, $path); 34 | $this->assertEquals($returnedValue, $result); 35 | } 36 | 37 | public function getJsonMemoryUsageDataProvider(): array 38 | { 39 | return [ 40 | [7, Keys::DEFAULT_KEY, '.'], 41 | [null, Keys::DEFAULT_KEY, '.path'] 42 | ]; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonMultiGetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 19 | 20 | class JsonMultiGetCommandTest extends BaseTestJsonCommandTrait 21 | { 22 | /** 23 | * @dataProvider getJsonMultiGetDataProvider 24 | * @param int $returnedValue 25 | * @param array $keys 26 | * @param string $path 27 | * @param bool $resultValue 28 | */ 29 | public function testJsonMultiGet($returnedValue, array $keys, string $path, $resultValue): void 30 | { 31 | $arguments = [JsonCommands::MULTI_GET, $keys, array_merge($keys, [$path])]; 32 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 33 | $result = $mock->jsonMultiGet($keys, $path); 34 | $this->assertEquals($resultValue, $result); 35 | } 36 | 37 | public function getJsonMultiGetDataProvider(): array 38 | { 39 | $value = '{"name":"foo"}'; 40 | return [ 41 | [ 42 | [$value, $value], 43 | ['test-key1', 'test-key2'], 44 | '.path1', 45 | [$value, $value] 46 | ], 47 | [ 48 | [$value, null], 49 | ['test-key1', 'nonexistent-key'], 50 | '.path1', 51 | [$value, null] 52 | ], 53 | [ 54 | [$value], 55 | ['test-key1'], 56 | '.path1', 57 | [$value] 58 | ], 59 | [ 60 | [], 61 | [], 62 | '.', 63 | [] 64 | ] 65 | ]; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonMultiplyNumByCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonMultiplyNumByCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonMultiplyNumByDataProvider 25 | * @param int $returnedValue 26 | * @param string $key 27 | * @param $number 28 | * @param string $path 29 | * @param bool $resultValue 30 | */ 31 | public function testJsonMultiplyNumBy($returnedValue, string $key, $number, string $path, $resultValue): void 32 | { 33 | $arguments = [JsonCommands::MULTIPLY_NUM_BY, [$key], [$key, $path, $number]]; 34 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 35 | $result = $mock->jsonMultiplyNumBy($key, $number, $path); 36 | $this->assertEquals($resultValue, $result); 37 | } 38 | 39 | public function getJsonMultiplyNumByDataProvider(): array 40 | { 41 | return [ 42 | ['200', Keys::DEFAULT_KEY, 10, '.', 200], 43 | ['10.79', Keys::DEFAULT_KEY, 10, '.', 10.79] 44 | ]; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonObjectKeysCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonObjectKeysCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonObjectKeysDataProvider 25 | * @param array $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonObjectKeys(?array $returnedValue, string $key, string $path): void 30 | { 31 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::OBJECT_KEYS, [$key], [$key, $path]]); 32 | $result = $mock->jsonObjectKeys($key, $path); 33 | $this->assertEquals($returnedValue, $result); 34 | } 35 | 36 | public function getJsonObjectKeysDataProvider(): array 37 | { 38 | return [ 39 | [['key1', 'key2'], Keys::DEFAULT_KEY, '.'], 40 | [null, Keys::DEFAULT_KEY, '.path'] 41 | ]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonObjectLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonObjectLengthCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonObjectLengthDataProvider 25 | * @param int|null $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonObjectLength(?int $returnedValue, string $key, string $path): void 30 | { 31 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::OBJECT_LENGTH, [$key], [$key, $path]]); 32 | $result = $mock->jsonObjectLength($key, $path); 33 | $this->assertEquals($returnedValue, $result); 34 | } 35 | 36 | public function getJsonObjectLengthDataProvider(): array 37 | { 38 | return [ 39 | [7, Keys::DEFAULT_KEY, '.'], 40 | [null, Keys::DEFAULT_KEY, '.path'] 41 | ]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonSetCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonSetCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonSetDataProvider 25 | * @param array $arguments 26 | * @param bool|null $returnedValue 27 | * @param string $key 28 | * @param $value 29 | * @param string $path 30 | * @param string|null $keyOptions 31 | * @param bool $resultValue 32 | */ 33 | public function testJsonSet( 34 | array $arguments, 35 | ?bool $returnedValue, 36 | string $key, 37 | $value, 38 | string $path, 39 | ?string $keyOptions, 40 | ?bool $resultValue 41 | ): void { 42 | $mock = $this->getRedisJsonClient($returnedValue, $arguments); 43 | $result = $mock->jsonSet($key, $value, $path, $keyOptions); 44 | $this->assertEquals($resultValue, $result); 45 | } 46 | 47 | public function getJsonSetDataProvider(): array 48 | { 49 | $value = ["name" => "foo"]; 50 | return [ 51 | [ 52 | [JsonCommands::SET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1', '{"name":"foo"}']], 53 | true, 54 | Keys::DEFAULT_KEY, 55 | $value, 56 | '.path1', 57 | null, 58 | true 59 | ], 60 | [ 61 | [JsonCommands::SET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1', '{"name":"foo"}', 'NX']], 62 | null, 63 | Keys::DEFAULT_KEY, 64 | $value, 65 | '.path1', 66 | 'NX', 67 | null 68 | ], 69 | [ 70 | [JsonCommands::SET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1', '{"name":"foo"}', 'XX']], 71 | null, 72 | Keys::DEFAULT_KEY, 73 | $value, 74 | '.path1', 75 | 'XX', 76 | null 77 | ], 78 | [ 79 | [JsonCommands::SET, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.path1', '{"name":"foo"}']], 80 | null, 81 | Keys::DEFAULT_KEY, 82 | $value, 83 | '.path1', 84 | 'AX', 85 | null 86 | ] 87 | ]; 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonStringAppendCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonStringAppendCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | public function testJsonStringAppend(): void 24 | { 25 | $mock = $this->getRedisJsonClient( 26 | 8, 27 | [JsonCommands::APPEND_STRING, [Keys::DEFAULT_KEY], [Keys::DEFAULT_KEY, '.', json_encode(' days')]] 28 | ); 29 | $result = $mock->jsonStringAppend(Keys::DEFAULT_KEY, ' days', '.'); 30 | $this->assertEquals(8, $result); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonStringLengthCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonStringLengthCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonStringLengthDataProvider 25 | * @param int|null $returnedValue 26 | * @param string $key 27 | * @param string $path 28 | */ 29 | public function testJsonStringLength(?int $returnedValue, string $key, string $path): void 30 | { 31 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::STRING_LENGTH, [$key], [$key, $path]]); 32 | $result = $mock->jsonStringLength($key, $path); 33 | $this->assertEquals($returnedValue, $result); 34 | } 35 | 36 | public function getJsonStringLengthDataProvider(): array 37 | { 38 | return [ 39 | [10, Keys::DEFAULT_KEY, '.path'], 40 | [null, Keys::DEFAULT_KEY, '.path'] 41 | ]; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Unit/Command/Traits/JsonTypeCommandTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Command\Traits; 16 | 17 | use Averias\RedisJson\Enum\JsonCommands; 18 | use Averias\RedisJson\Enum\Keys; 19 | use Averias\RedisJson\Tests\Unit\Command\BaseTestJsonCommandTrait; 20 | 21 | class JsonTypeCommandTest extends BaseTestJsonCommandTrait 22 | { 23 | /** 24 | * @dataProvider getJsonTypeDataProvider 25 | * @param string $returnedValue 26 | */ 27 | public function testJsonType(?string $returnedValue): void 28 | { 29 | $params = [Keys::DEFAULT_KEY, '.']; 30 | $mock = $this->getRedisJsonClient($returnedValue, [JsonCommands::TYPE, [Keys::DEFAULT_KEY], $params]); 31 | $result = $mock->jsonType(...$params); 32 | $this->assertEquals($returnedValue, $result); 33 | } 34 | 35 | public function getJsonTypeDataProvider(): array 36 | { 37 | return [ 38 | ['object'], 39 | ['string'], 40 | ['integer'], 41 | ['number'], 42 | ['object'], 43 | ['array'], 44 | ['boolean'], 45 | [null] 46 | ]; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /tests/Unit/Encoder/Traits/JsonEncoderTraitTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Encoder\Traits; 16 | 17 | use Averias\RedisJson\Encoder\Traits\JsonEncoderTrait; 18 | use Averias\RedisJson\Exception\ResponseException; 19 | use PHPUnit\Framework\TestCase; 20 | 21 | class JsonEncoderTraitTest extends TestCase 22 | { 23 | /** 24 | * @dataProvider getEncoderDataProvider 25 | * @param $phpData 26 | * @param string $jsonData 27 | */ 28 | public function testEncode($phpData, string $jsonData) 29 | { 30 | $mock = $this->getMockForTrait(JsonEncoderTrait::class); 31 | $encoded = $mock->encode($phpData); 32 | $this->assertSame($jsonData, $encoded); 33 | } 34 | 35 | public function testEncodeException() 36 | { 37 | $this->expectException(ResponseException::class); 38 | $mock = $this->getMockForTrait(JsonEncoderTrait::class); 39 | $mock->encode($this->getAssociativeArrayWithDepth(513)); 40 | } 41 | 42 | /** 43 | * @dataProvider getEncoderDataProvider 44 | * @param $phpData 45 | * @param string $jsonData 46 | */ 47 | public function testDecode($phpData, string $jsonData) 48 | { 49 | $mock = $this->getMockForTrait(JsonEncoderTrait::class); 50 | $decoded = $mock->decode($jsonData); 51 | $this->assertSame($phpData, $decoded); 52 | } 53 | 54 | public function testDecodeException() 55 | { 56 | $this->expectException(ResponseException::class); 57 | $mock = $this->getMockForTrait(JsonEncoderTrait::class); 58 | $mock->decode('{"key1":"value1","key2":false,"key3:18,"key4":11.2,"key5":["array-value1","array-value2"]}'); 59 | } 60 | 61 | public function getEncoderDataProvider() 62 | { 63 | return [ 64 | [ 65 | [ 66 | 'key1' => 'value1', 67 | 'key2' => false, 68 | 'key3' => 18, 69 | 'key4' => 11.2, 70 | 'key5' => ['array-value1', 'array-value2'] 71 | ], 72 | '{"key1":"value1","key2":false,"key3":18,"key4":11.2,"key5":["array-value1","array-value2"]}' 73 | ] 74 | ]; 75 | } 76 | 77 | protected function getAssociativeArrayWithDepth(int $depth) 78 | { 79 | $leaf = ['name' => 'foo', 'age' => $depth]; 80 | $parent = []; 81 | for ($i = 1; $i < $depth; $i++) { 82 | $parent = [ 83 | 'name' => 'foo', 84 | 'age' => $depth - $i, 85 | 'children' => $leaf 86 | ]; 87 | $leaf = $parent; 88 | } 89 | 90 | return $parent; 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /tests/Unit/Factory/RedisJsonClientFactoryTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Factory; 16 | 17 | use Averias\RedisJson\Client\RedisJsonClientInterface; 18 | use Averias\RedisJson\Exception\RedisClientException; 19 | use Averias\RedisJson\Factory\RedisJsonClientFactory; 20 | use Averias\RedisJson\Enum\Connection; 21 | use PHPUnit\Framework\TestCase; 22 | 23 | class RedisJsonClientFactoryTest extends TestCase 24 | { 25 | public function testCreateClientException() 26 | { 27 | $this->expectException(RedisClientException::class); 28 | $factory = new RedisJsonClientFactory(); 29 | $factory->createClient([ 30 | 'database' => 62 31 | ]); 32 | } 33 | 34 | public function testCreateClient() 35 | { 36 | $factory = new RedisJsonClientFactory(); 37 | $client = $factory->createClient([ 38 | Connection::HOST => REDIS_TEST_SERVER, 39 | Connection::PORT => (int) REDIS_TEST_PORT, 40 | Connection::TIMEOUT => 2 41 | ]); 42 | 43 | $this->assertInstanceOf(RedisJsonClientInterface::class, $client); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /tests/Unit/Parser/Response/DecodeArrayOfJsonTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\Response\DecodeArrayOfJson; 19 | use PHPUnit\Framework\TestCase; 20 | 21 | class DecodeArrayOfJsonTest extends TestCase 22 | { 23 | public function testResponseIsNotArrayException():void 24 | { 25 | $this->expectException(ResponseException::class); 26 | $parser = new DecodeArrayOfJson(); 27 | $parser->parse('foo'); 28 | } 29 | 30 | 31 | /** 32 | * @dataProvider getDecodeJsonDataProvider 33 | * @param array $response 34 | */ 35 | public function testDecodeArray(array $response) 36 | { 37 | $parser = new DecodeArrayOfJson(); 38 | $result = $parser->parse($response); 39 | $decoded = array_map( 40 | function ($item) { 41 | return json_decode($item, true); 42 | }, 43 | $response 44 | ); 45 | $this->assertSame($decoded, $result); 46 | } 47 | 48 | public function getDecodeJsonDataProvider() 49 | { 50 | return [ 51 | [['{"key1":"value1","key2":false,"key3":18,"key5":["array-value1","array-value2"]}', '18', 'true']], 52 | [['1.79', '"Sara"']], 53 | [['true', 'false']] 54 | ]; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /tests/Unit/Parser/Response/DecodeFromJsonTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Parser\Response; 16 | 17 | use Averias\RedisJson\Parser\Response\DecodeFromJson; 18 | use PHPUnit\Framework\TestCase; 19 | 20 | class DecodeFromJsonTest extends TestCase 21 | { 22 | public function testNoDecodeIfFalse() 23 | { 24 | $parser = new DecodeFromJson(); 25 | $result = $parser->parse(false); 26 | $this->assertNull($result); 27 | } 28 | 29 | /** 30 | * @dataProvider getDecodeJsonDataProvider 31 | * @param string $response 32 | */ 33 | public function testDecode(string $response) 34 | { 35 | $parser = new DecodeFromJson(); 36 | $result = $parser->parse($response); 37 | $this->assertSame(json_decode($response, true), $result); 38 | } 39 | 40 | public function getDecodeJsonDataProvider() 41 | { 42 | return [ 43 | ['{"key1":"value1","key2":false,"key3":18,"key4":11.2,"key5":["array-value1","array-value2"]}'], 44 | ['1.79'], 45 | ['34'], 46 | ['"Peter"'], 47 | ["false"] 48 | ]; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /tests/Unit/Parser/Response/IntegerToBooleanTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\Response\IntegerToBoolean; 19 | use PHPUnit\Framework\TestCase; 20 | 21 | class IntegerToBooleanTest extends TestCase 22 | { 23 | public function testResponseIsNotIntegerException():void 24 | { 25 | $this->expectException(ResponseException::class); 26 | $parser = new IntegerToBoolean(); 27 | $parser->parse('foo'); 28 | } 29 | 30 | /** 31 | * @dataProvider getDataProvider 32 | * @param int $response 33 | * @param bool $expected 34 | */ 35 | public function testParse(int $response, bool $expected): void 36 | { 37 | $parser = new IntegerToBoolean(); 38 | $result = $parser->parse($response); 39 | $this->assertSame($expected, $result); 40 | } 41 | 42 | public function getDataProvider(): array 43 | { 44 | return [ 45 | [1, true], 46 | [0, false] 47 | ]; 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /tests/Unit/Parser/Response/OkToTrueTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Parser\Response; 16 | 17 | use Averias\RedisJson\Exception\ResponseException; 18 | use Averias\RedisJson\Parser\Response\OkToTrue; 19 | use PHPUnit\Framework\TestCase; 20 | 21 | class OkToTrueTest extends TestCase 22 | { 23 | public function testResponseIsNotStringException():void 24 | { 25 | $this->expectException(ResponseException::class); 26 | $parser = new OkToTrue(); 27 | $parser->parse(false); 28 | } 29 | 30 | public function testResponseIsNotStringOKException():void 31 | { 32 | $this->expectException(ResponseException::class); 33 | $parser = new OkToTrue(); 34 | $parser->parse('KO'); 35 | } 36 | 37 | public function testParse(): void 38 | { 39 | $parser = new OkToTrue(); 40 | $result = $parser->parse('OK'); 41 | $this->assertTrue($result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /tests/Unit/Validator/RedisClientValidatorTest.php: -------------------------------------------------------------------------------- 1 | 7 | * @copyright 2019 Rafael Campoy 8 | * @license MIT 9 | * @link https://github.com/averias/phpredis-json 10 | * 11 | * Copyright and license information, is included in 12 | * the LICENSE file that is distributed with this source code. 13 | */ 14 | 15 | namespace Averias\RedisJson\Tests\Unit\Validator; 16 | 17 | use Averias\RedisJson\Enum\Module; 18 | use Averias\RedisJson\Validator\RedisClientValidator; 19 | use PHPUnit\Framework\TestCase; 20 | 21 | class RedisClientValidatorTest extends TestCase 22 | { 23 | /** 24 | * @dataProvider getValidRedisVersionDataProvider 25 | * @param string $version 26 | */ 27 | public function testIsValidRedisVersion(string $version) 28 | { 29 | $validator = new RedisClientValidator(); 30 | $result = $validator->isValidRedisVersion($version); 31 | $this->assertTrue($result); 32 | } 33 | 34 | /** 35 | * @dataProvider getInvalidRedisVersionDataProvider 36 | * @param string $version 37 | */ 38 | public function testIsNotValidRedisVersion(string $version) 39 | { 40 | $validator = new RedisClientValidator(); 41 | $result = $validator->isValidRedisVersion($version); 42 | $this->assertFalse($result); 43 | } 44 | 45 | public function testIsRedisJsonModuleInstalled() 46 | { 47 | $validator = new RedisClientValidator(); 48 | $result = $validator->isRedisJsonModuleInstalled([['foo', 'bar'], [Module::REDIS_JSON_MODULE_NAME]]); 49 | $this->assertTrue($result); 50 | } 51 | 52 | public function testIsNotRedisJsonModuleInstalled() 53 | { 54 | $validator = new RedisClientValidator(); 55 | $result = $validator->isRedisJsonModuleInstalled([['foo', 'bar'], ['ReJSONNotInstalled']]); 56 | $this->assertFalse($result); 57 | } 58 | 59 | public function getValidRedisVersionDataProvider() 60 | { 61 | return [ 62 | ['4.0'], 63 | ['5.0'], 64 | ['4.0.14'], 65 | ['5.0.6'], 66 | ['4'], 67 | ['5'] 68 | ]; 69 | } 70 | 71 | public function getInvalidRedisVersionDataProvider() 72 | { 73 | return [ 74 | ['3.2'], 75 | ['2.8'] 76 | ]; 77 | } 78 | } 79 | --------------------------------------------------------------------------------