diff --git a/README.md b/README.md index a7b79b9..ba64947 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ Redis command | Description **HGETALL** *key* | Gets all the fields and values in a hash **HMSET** *key* *array\* | Sets each value in the corresponding field **HSET** *key* *field* *value* | Sets the string value of a hash field +**HSETNX** *key* *field* *value* | Sets field in the hash stored at key to value, only if field does not yet exist **LINDEX** *key* *index* | Returns the element at index *index* in the list stored at *key* **LLEN** *key* | Returns the length of the list stored at *key* **LPUSH** *key* *value* *[value ...]* | Pushs values at the head of a list diff --git a/src/M6Web/Component/RedisMock/RedisMock.php b/src/M6Web/Component/RedisMock/RedisMock.php index 4fa5718..4f9289f 100644 --- a/src/M6Web/Component/RedisMock/RedisMock.php +++ b/src/M6Web/Component/RedisMock/RedisMock.php @@ -548,6 +548,27 @@ public function hset($key, $field, $value) return $this->returnPipedInfo((int) $isNew); } + public function hsetnx($key, $field, $value) + { + $this->deleteOnTtlExpired($key); + + if (isset(self::$data[$key]) && !is_array(self::$data[$key])) { + return $this->returnPipedInfo(null); + } + + $isNew = !isset(self::$data[$key][$field]); + + if ($isNew) { + self::$data[$key][$field] = $value; + self::$dataTypes[$key] = 'hash'; + if (array_key_exists($key, self::$dataTtl)) { + unset(self::$dataTtl[$key]); + } + } + + return $this->returnPipedInfo((int) $isNew); + } + public function hmset($key, $pairs) { $this->deleteOnTtlExpired($key); diff --git a/tests/units/RedisMock.php b/tests/units/RedisMock.php index e5e7278..e60ddd5 100644 --- a/tests/units/RedisMock.php +++ b/tests/units/RedisMock.php @@ -1160,6 +1160,17 @@ public function testHSetHMSetHGetHDelHExistsHGetAll() 'raoul' => null, 'test1' => null, )); + sleep(2); + $this->assert + ->integer($redisMock->hsetnx('mykey', 'field', 'my value')) + ->isEqualTo(1) + ->integer($redisMock->hsetnx('mykey', 'field2', 'second value')) + ->isEqualTo(1) + ->integer($redisMock->hsetnx('mykey', 'field', 'override value')) + ->isEqualTo(0) + ->integer($redisMock->del('mykey')) + ->isEqualTo(2) + ; } public function testLLen()