Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Fix a bug where the Redis adapter returns an int for hasItem() #147

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/Storage/Adapter/Redis.php
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ protected function internalHasItem(& $normalizedKey)
{
$redis = $this->getRedisResource();
try {
return $redis->exists($this->namespacePrefix . $normalizedKey);
return (bool)$redis->exists($this->namespacePrefix . $normalizedKey);
} catch (RedisResourceException $e) {
throw new Exception\RuntimeException($redis->getLastError(), $e->getCode(), $e);
}
Expand Down
48 changes: 48 additions & 0 deletions test/Storage/Adapter/RedisTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@

namespace ZendTest\Cache\Storage\Adapter;

use PHPUnit_Framework_MockObject_MockObject;
use Zend\Cache;
use Redis as RedisResource;
use Zend\Cache\Storage\Adapter\Redis;
use Zend\Cache\Storage\Adapter\RedisOptions;
use Zend\Cache\Storage\Adapter\RedisResourceManager;

/**
* @covers Zend\Cache\Storage\Adapter\Redis<extended>
Expand Down Expand Up @@ -337,4 +341,48 @@ public function testTouchItem()
$this->assertTrue($this->_storage->touchItem($key));
$this->assertEquals($ttl, ceil($this->_storage->getMetadata($key)['ttl']));
}

public function testHasItemReturnsFalseIfRedisExistsReturnsZero()
{
$redis = $this->mockInitializedRedisResource();
$redis->method('exists')->willReturn(0);
$adapter = $this->createAdapterFromResource($redis);

$hasItem = $adapter->hasItem('does-not-exist');

$this->assertFalse($hasItem);
}

public function testHasItemReturnsTrueIfRedisExistsReturnsNonZeroInt()
{
$redis = $this->mockInitializedRedisResource();
$redis->method('exists')->willReturn(23);
$adapter = $this->createAdapterFromResource($redis);

$hasItem = $adapter->hasItem('does-not-exist');

$this->assertTrue($hasItem);
}

/**
* @return Redis
*/
private function createAdapterFromResource(RedisResource $redis)
{
$resourceManager = new RedisResourceManager();
$resourceId = 'my-resource';
$resourceManager->setResource($resourceId, $redis);
$options = new RedisOptions(['resource_manager' => $resourceManager, 'resource_id' => $resourceId]);
return new Redis($options);
}

/**
* @return PHPUnit_Framework_MockObject_MockObject|RedisResource
*/
private function mockInitializedRedisResource()
{
$redis = $this->getMock(RedisResource::class);
$redis->socket = true;
return $redis;
}
}