Skip to content

Commit

Permalink
Introducing ability to specify a namespace for redis storage (#10)
Browse files Browse the repository at this point in the history
  • Loading branch information
smithandre authored and pierredup committed Jan 14, 2019
1 parent e98ae83 commit ada332c
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 4 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -369,7 +369,7 @@ To enable toggler inside symfony, register the bundle

$bundles = array(
...
new Toggler\Symfony\TogglerBundle(),
new SolidWorx\Toggler\Symfony\TogglerBundle(),
...
);
```
Expand Down
17 changes: 14 additions & 3 deletions src/Storage/RedisStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,39 @@ class RedisStorage implements PersistenStorageInterface
*/
private $redis;

public function __construct($redis)
/**
* @var string
*/
private $namespace;

public function __construct($redis, ?string $namespace = null)
{
if (!$redis instanceof \Redis && !$redis instanceof \RedisArray && !$redis instanceof \RedisCluster && !$redis instanceof \Predis\Client) {
throw new \InvalidArgumentException(sprintf('%s() expects parameter 1 to be Redis, RedisArray, RedisCluster or Predis\Client, %s given', __METHOD__, is_object($redis) ? get_class($redis) : gettype($redis)));
}

$this->redis = $redis;
$this->namespace = $namespace;
}

/**
* {@inheritdoc}
*/
public function get(string $key)
{
return $this->redis->get($key);
return $this->redis->get($this->generateKey($key));
}

/**
* {@inheritdoc}
*/
public function set(string $key, bool $value)
{
return $this->redis->set($key, $value);
return $this->redis->set($this->generateKey($key), $value);
}

private function generateKey(string $key): string
{
return $this->namespace ? "{$this->namespace}:$key" : $key;
}
}
30 changes: 30 additions & 0 deletions tests/Storage/RedisStorageTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,4 +59,34 @@ public function testSet()

$storage->set('foobar', false);
}

public function testGetWithNamespace()
{
$namespace = 'fooNamespace';
$this->redis->expects($this->at(0))
->method('get')
->with($namespace.':foobar')
->willReturn(true);

$this->redis->expects($this->at(1))
->method('get')
->with($namespace.':baz');

$storage = new RedisStorage($this->redis, $namespace);

$this->assertTrue($storage->get('foobar'));
$this->assertNull($storage->get('baz'));
}

public function testSetWithNamespace()
{
$namespace = 'fooNamespace';
$this->redis->expects($this->at(0))
->method('set')
->with($namespace.':foobar', false);

$storage = new RedisStorage($this->redis, $namespace);

$storage->set('foobar', false);
}
}

0 comments on commit ada332c

Please sign in to comment.