Refactoring Core class structures ...

This commit is contained in:
Philipp 2021-10-26 21:44:29 +02:00
parent 57b4c008cb
commit b216317477
No known key found for this signature in database
GPG key ID: 24A7501396EB5432
130 changed files with 1625 additions and 1397 deletions

View file

@ -19,23 +19,24 @@
*
*/
namespace Friendica\Core\Cache;
namespace Friendica\Core\Cache\Capability;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\Exception\CachePersistenceException;
/**
* Cache Interface
* Interface for caches
*/
interface ICache
interface ICanCache
{
/**
* Lists all cache keys
*
* @param string prefix optional a prefix to search
* @param string|null prefix optional a prefix to search
*
* @return array Empty if it isn't supported by the cache driver
*/
public function getAllKeys($prefix = null);
public function getAllKeys(?string $prefix = null): array;
/**
* Fetches cached data according to the key
@ -43,41 +44,50 @@ interface ICache
* @param string $key The key to the cached data
*
* @return mixed Cached $value or "null" if not found
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function get($key);
public function get(string $key);
/**
* Stores data in the cache identified by the key. The input $value can have multiple formats.
*
* @param string $key The cache key
* @param mixed $value The value to store
* @param integer $ttl The cache lifespan, must be one of the Cache constants
* @param string $key The cache key
* @param mixed $value The value to store
* @param integer $ttl The cache lifespan, must be one of the Cache constants
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES);
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool;
/**
* Delete a key from the cache
*
* @param string $key The cache key
* @param string $key The cache key
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function delete($key);
public function delete(string $key): bool;
/**
* Remove outdated data from the cache
* @param boolean $outdated just remove outdated values
*
* @param boolean $outdated just remove outdated values
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function clear($outdated = true);
public function clear(bool $outdated = true): bool;
/**
* Returns the name of the current cache
*
* @return string
*/
public function getName();
public function getName(): string;
}

View file

@ -19,43 +19,52 @@
*
*/
namespace Friendica\Core\Cache;
namespace Friendica\Core\Cache\Capability;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\Exception\CachePersistenceException;
/**
* This interface defines methods for Memory-Caches only
*/
interface IMemoryCache extends ICache
interface ICanCacheInMemory extends ICanCache
{
/**
* Sets a value if it's not already stored
*
* @param string $key The cache key
* @param mixed $value The old value we know from the cache
* @param int $ttl The cache lifespan, must be one of the Cache constants
* @param string $key The cache key
* @param mixed $value The old value we know from the cache
* @param int $ttl The cache lifespan, must be one of the Cache constants
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES);
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool;
/**
* Compares if the old value is set and sets the new value
*
* @param string $key The cache key
* @param mixed $oldValue The old value we know from the cache
* @param mixed $newValue The new value we want to set
* @param int $ttl The cache lifespan, must be one of the Cache constants
* @param string $key The cache key
* @param mixed $oldValue The old value we know from the cache
* @param mixed $newValue The new value we want to set
* @param int $ttl The cache lifespan, must be one of the Cache constants
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES);
public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool;
/**
* Compares if the old value is set and removes it
*
* @param string $key The cache key
* @param mixed $value The old value we know and want to delete
* @param string $key The cache key
* @param mixed $value The old value we know and want to delete
*
* @return bool
*
* @throws CachePersistenceException In case the underlying cache driver has errors during persistence
*/
public function compareDelete($key, $value);
public function compareDelete(string $key, $value): bool;
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Cache\Exception;
use Throwable;
class CachePersistenceException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -0,0 +1,13 @@
<?php
namespace Friendica\Core\Cache\Exception;
use Throwable;
class InvalidCacheDriverException extends \RuntimeException
{
public function __construct($message = "", Throwable $previous = null)
{
parent::__construct($message, 500, $previous);
}
}

View file

@ -22,9 +22,12 @@
namespace Friendica\Core\Cache\Factory;
use Friendica\App\BaseURL;
use Friendica\Core\Cache;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Cache\Enum;
use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Cache\Type;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Friendica\Database\Database;
use Friendica\Util\Profiler;
use Psr\Log\LoggerInterface;
@ -36,15 +39,15 @@ use Psr\Log\LoggerInterface;
*
* A basic class to generate a CacheDriver
*/
class CacheFactory
class Cache
{
/**
* @var string The default cache if nothing set
*/
const DEFAULT_TYPE = Cache\Enum\Type::DATABASE;
const DEFAULT_TYPE = Enum\Type::DATABASE;
/**
* @var IConfig The IConfiguration to read parameters out of the config
* @var IManageConfigValues The IConfiguration to read parameters out of the config
*/
private $config;
@ -68,7 +71,7 @@ class CacheFactory
*/
private $logger;
public function __construct(BaseURL $baseURL, IConfig $config, Database $dba, Profiler $profiler, LoggerInterface $logger)
public function __construct(BaseURL $baseURL, IManageConfigValues $config, Database $dba, Profiler $profiler, LoggerInterface $logger)
{
$this->hostname = $baseURL->getHostname();
$this->config = $config;
@ -80,39 +83,41 @@ class CacheFactory
/**
* This method creates a CacheDriver for the given cache driver name
*
* @param string $type The cache type to create (default is per config)
* @param string|null $type The cache type to create (default is per config)
*
* @return ICache The instance of the CacheDriver
* @throws \Exception The exception if something went wrong during the CacheDriver creation
* @return ICanCache The instance of the CacheDriver
*
* @throws InvalidCacheDriverException In case the underlying cache driver isn't valid or not configured properly
* @throws CachePersistenceException In case the underlying cache has errors during persistence
*/
public function create(string $type = null)
public function create(string $type = null): ICanCache
{
if (empty($type)) {
$type = $this->config->get('system', 'cache_driver', self::DEFAULT_TYPE);
}
switch ($type) {
case Cache\Enum\Type::MEMCACHE:
$cache = new Cache\Type\MemcacheCache($this->hostname, $this->config);
case Enum\Type::MEMCACHE:
$cache = new Type\MemcacheCache($this->hostname, $this->config);
break;
case Cache\Enum\Type::MEMCACHED:
$cache = new Cache\Type\MemcachedCache($this->hostname, $this->config, $this->logger);
case Enum\Type::MEMCACHED:
$cache = new Type\MemcachedCache($this->hostname, $this->config, $this->logger);
break;
case Cache\Enum\Type::REDIS:
$cache = new Cache\Type\RedisCache($this->hostname, $this->config);
case Enum\Type::REDIS:
$cache = new Type\RedisCache($this->hostname, $this->config);
break;
case Cache\Enum\Type::APCU:
$cache = new Cache\Type\APCuCache($this->hostname);
case Enum\Type::APCU:
$cache = new Type\APCuCache($this->hostname);
break;
default:
$cache = new Cache\Type\DatabaseCache($this->hostname, $this->dba);
$cache = new Type\DatabaseCache($this->hostname, $this->dba);
}
$profiling = $this->config->get('system', 'profiling', false);
// In case profiling is enabled, wrap the ProfilerCache around the current cache
if (isset($profiling) && $profiling !== false) {
return new Cache\Type\ProfilerCache($cache, $this->profiler);
return new Type\ProfilerCacheDecorator($cache, $this->profiler);
} else {
return $cache;
}

View file

@ -21,28 +21,28 @@
namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
/**
* APCu Cache.
*/
class APCuCache extends BaseCache implements IMemoryCache
class APCuCache extends AbstractCache implements ICanCacheInMemory
{
use TraitCompareSet;
use TraitCompareDelete;
use CompareSetTrait;
use CompareDeleteTrait;
/**
* @throws Exception
* @param string $hostname
*
* @throws InvalidCacheDriverException
*/
public function __construct(string $hostname)
{
if (!self::isAvailable()) {
throw new Exception('APCu is not available.');
throw new InvalidCacheDriverException('APCu is not available.');
}
parent::__construct($hostname);
@ -51,9 +51,9 @@ class APCuCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
$ns = $this->getCacheKey($prefix);
$ns = $this->getCacheKey($prefix ?? '');
$ns = preg_quote($ns, '/');
if (class_exists('\APCIterator')) {
@ -73,12 +73,11 @@ class APCuCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
$return = null;
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
$cached = apcu_fetch($cachekey, $success);
$cached = apcu_fetch($cacheKey, $success);
if (!$success) {
return null;
}
@ -89,30 +88,30 @@ class APCuCache extends BaseCache implements IMemoryCache
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
$return = $value;
return $value;
}
return $return;
return null;
}
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
$cached = serialize($value);
if ($ttl > 0) {
return apcu_store(
$cachekey,
$cacheKey,
$cached,
$ttl
);
} else {
return apcu_store(
$cachekey,
$cacheKey,
$cached
);
}
@ -121,16 +120,16 @@ class APCuCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
$cachekey = $this->getCacheKey($key);
return apcu_delete($cachekey);
$cacheKey = $this->getCacheKey($key);
return apcu_delete($cacheKey);
}
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
if ($outdated) {
return true;
@ -151,15 +150,15 @@ class APCuCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cached = serialize($value);
$cacheKey = $this->getCacheKey($key);
$cached = serialize($value);
return apcu_add($cachekey, $cached);
return apcu_add($cacheKey, $cached);
}
public static function isAvailable()
public static function isAvailable(): bool
{
if (!extension_loaded('apcu')) {
return false;
@ -178,7 +177,7 @@ class APCuCache extends BaseCache implements IMemoryCache
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::APCU;
}

View file

@ -21,12 +21,12 @@
namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Cache\Capability\ICanCache;
/**
* Abstract class for common used functions
*/
abstract class BaseCache implements ICache
abstract class AbstractCache implements ICanCache
{
/**
* @var string The hostname
@ -42,9 +42,8 @@ abstract class BaseCache implements ICache
* Returns the prefix (to avoid namespace conflicts)
*
* @return string
* @throws \Exception
*/
protected function getPrefix()
protected function getPrefix(): string
{
// We fetch with the hostname as key to avoid problems with other applications
return $this->hostName;
@ -52,19 +51,20 @@ abstract class BaseCache implements ICache
/**
* @param string $key The original key
*
* @return string The cache key used for the cache
* @throws \Exception
*/
protected function getCacheKey($key)
protected function getCacheKey(string $key): string
{
return $this->getPrefix() . ":" . $key;
}
/**
* @param array $keys A list of cached keys
* @return array A list of original keys
* @param string[] $keys A list of cached keys
*
* @return string[] A list of original keys
*/
protected function getOriginalKeys($keys)
protected function getOriginalKeys(array $keys): array
{
if (empty($keys)) {
return [];
@ -84,12 +84,12 @@ abstract class BaseCache implements ICache
* Filters the keys of an array with a given prefix
* Returns the filtered keys as an new array
*
* @param array $keys The keys, which should get filtered
* @param string[] $keys The keys, which should get filtered
* @param string|null $prefix The prefix (if null, all keys will get returned)
*
* @return array The filtered array with just the keys
* @return string[] The filtered array with just the keys
*/
protected function filterArrayKeysByPrefix(array $keys, string $prefix = null)
protected function filterArrayKeysByPrefix(array $keys, string $prefix = null): array
{
if (empty($prefix)) {
return $keys;

View file

@ -21,25 +21,23 @@
namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum;
/**
* Implementation of the IMemoryCache mainly for testing purpose
*/
class ArrayCache extends BaseCache implements IMemoryCache
class ArrayCache extends AbstractCache implements ICanCacheInMemory
{
use TraitCompareDelete;
use CompareDeleteTrait;
/** @var array Array with the cached data */
protected $cachedData = array();
protected $cachedData = [];
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
return $this->filterArrayKeysByPrefix(array_keys($this->cachedData), $prefix);
}
@ -47,7 +45,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
if (isset($this->cachedData[$key])) {
return $this->cachedData[$key];
@ -58,7 +56,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{
$this->cachedData[$key] = $value;
return true;
@ -67,7 +65,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
unset($this->cachedData[$key]);
return true;
@ -76,7 +74,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
// Array doesn't support TTL so just don't delete something
if ($outdated) {
@ -90,7 +88,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{
if (isset($this->cachedData[$key])) {
return false;
@ -102,7 +100,7 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES)
public function compareSet(string $key, $oldValue, $newValue, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{
if ($this->get($key) === $oldValue) {
return $this->set($key, $newValue);
@ -114,8 +112,8 @@ class ArrayCache extends BaseCache implements IMemoryCache
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::ARRAY;
return Enum\Type::ARRAY;
}
}

View file

@ -24,28 +24,28 @@ namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration;
/**
* Trait TraitCompareSetDelete
*
* This Trait is to compensate non native "exclusive" sets/deletes in caches
* This Trait is to compensate nonnative "exclusive" sets/deletes in caches
*/
trait TraitCompareDelete
trait CompareDeleteTrait
{
abstract public function get($key);
abstract public function get(string $key);
abstract public function set($key, $value, $ttl = Duration::FIVE_MINUTES);
abstract public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
abstract public function delete($key);
abstract public function delete(string $key);
abstract public function add($key, $value, $ttl = Duration::FIVE_MINUTES);
abstract public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
/**
* NonNative - Compares if the old value is set and removes it
*
* @param string $key The cache key
* @param mixed $value The old value we know and want to delete
* @param string $key The cache key
* @param mixed $value The old value we know and want to delete
*
* @return bool
*/
public function compareDelete($key, $value) {
public function compareDelete(string $key, $value): bool
{
if ($this->add($key . "_lock", true)) {
if ($this->get($key) === $value) {
$this->delete($key);

View file

@ -24,37 +24,36 @@ namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration;
/**
* Trait TraitCompareSetDelete
*
* This Trait is to compensate non native "exclusive" sets/deletes in caches
* This Trait is to compensate nonnative "exclusive" sets/deletes in caches
*/
trait TraitCompareSet
trait CompareSetTrait
{
abstract public function get($key);
abstract public function get(string $key);
abstract public function set($key, $value, $ttl = Duration::FIVE_MINUTES);
abstract public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
abstract public function delete($key);
abstract public function delete(string $key);
abstract public function add($key, $value, $ttl = Duration::FIVE_MINUTES);
abstract public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES);
/**
* NonNative - Compares if the old value is set and sets the new value
*
* @param string $key The cache key
* @param mixed $oldValue The old value we know from the cache
* @param mixed $newValue The new value we want to set
* @param string $key The cache key
* @param mixed $oldValue The old value we know from the cache
* @param mixed $newValue The new value we want to set
* @param int $ttl The cache lifespan, must be one of the Cache constants
*
* @return bool
*/
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES) {
public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{
if ($this->add($key . "_lock", true)) {
if ($this->get($key) === $oldValue) {
$this->set($key, $newValue, $ttl);
$this->delete($key . "_lock");
return true;
} else {
} else {
$this->delete($key . "_lock");
return false;
}

View file

@ -21,16 +21,16 @@
namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Enum;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Database\Database;
use Friendica\Util\DateTimeFormat;
/**
* Database Cache
*/
class DatabaseCache extends BaseCache implements ICache
class DatabaseCache extends AbstractCache implements ICanCache
{
/**
* @var Database
@ -46,22 +46,29 @@ class DatabaseCache extends BaseCache implements ICache
/**
* (@inheritdoc)
*
* @throws CachePersistenceException
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else {
$where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
}
try {
if (empty($prefix)) {
$where = ['`expires` >= ?', DateTimeFormat::utcNow()];
} else {
$where = ['`expires` >= ? AND `k` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
}
$stmt = $this->dba->select('cache', ['k'], $where);
$stmt = $this->dba->select('cache', ['k'], $where);
$keys = [];
while ($key = $this->dba->fetch($stmt)) {
array_push($keys, $key['k']);
$keys = [];
while ($key = $this->dba->fetch($stmt)) {
array_push($keys, $key['k']);
}
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot fetch all keys with prefix %s', $prefix), $exception);
} finally {
$this->dba->close($stmt);
}
$this->dba->close($stmt);
return $keys;
}
@ -69,20 +76,26 @@ class DatabaseCache extends BaseCache implements ICache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
$cache = $this->dba->selectFirst('cache', ['v'], ['`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()]);
try {
$cache = $this->dba->selectFirst('cache', ['v'], [
'`k` = ? AND (`expires` >= ? OR `expires` = -1)', $key, DateTimeFormat::utcNow()
]);
if ($this->dba->isResult($cache)) {
$cached = $cache['v'];
$value = @unserialize($cached);
if ($this->dba->isResult($cache)) {
$cached = $cache['v'];
$value = @unserialize($cached);
// Only return a value if the serialized value is valid.
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
return $value;
// Only return a value if the serialized value is valid.
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
return $value;
}
}
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot get cache entry with key %s', $key), $exception);
}
return null;
@ -91,50 +104,62 @@ class DatabaseCache extends BaseCache implements ICache
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Enum\Duration::FIVE_MINUTES): bool
{
if ($ttl > 0) {
$fields = [
'v' => serialize($value),
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
'updated' => DateTimeFormat::utcNow()
];
} else {
$fields = [
'v' => serialize($value),
'expires' => -1,
'updated' => DateTimeFormat::utcNow()
];
try {
if ($ttl > 0) {
$fields = [
'v' => serialize($value),
'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
'updated' => DateTimeFormat::utcNow()
];
} else {
$fields = [
'v' => serialize($value),
'expires' => -1,
'updated' => DateTimeFormat::utcNow()
];
}
return $this->dba->update('cache', $fields, ['k' => $key], true);
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot set cache entry with key %s', $key), $exception);
}
return $this->dba->update('cache', $fields, ['k' => $key], true);
}
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
return $this->dba->delete('cache', ['k' => $key]);
try {
return $this->dba->delete('cache', ['k' => $key]);
} catch (\Exception $exception) {
throw new CachePersistenceException(sprintf('Cannot delete cache entry with key %s', $key), $exception);
}
}
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
if ($outdated) {
return $this->dba->delete('cache', ['`expires` < NOW()']);
} else {
return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
try {
if ($outdated) {
return $this->dba->delete('cache', ['`expires` < NOW()']);
} else {
return $this->dba->delete('cache', ['`k` IS NOT NULL ']);
}
} catch (\Exception $exception) {
throw new CachePersistenceException('Cannot clear cache', $exception);
}
}
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::DATABASE;
return Enum\Type::DATABASE;
}
}

View file

@ -21,24 +21,22 @@
namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Type\TraitMemcacheCommand;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Memcache;
/**
* Memcache Cache
*/
class MemcacheCache extends BaseCache implements IMemoryCache
class MemcacheCache extends AbstractCache implements ICanCacheInMemory
{
use TraitCompareSet;
use TraitCompareDelete;
use TraitMemcacheCommand;
use CompareSetTrait;
use CompareDeleteTrait;
use MemcacheCommandTrait;
/**
* @var Memcache
@ -46,30 +44,34 @@ class MemcacheCache extends BaseCache implements IMemoryCache
private $memcache;
/**
* @throws Exception
* @param string $hostname
* @param IManageConfigValues $config
*
* @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/
public function __construct(string $hostname, IConfig $config)
public function __construct(string $hostname, IManageConfigValues $config)
{
if (!class_exists('Memcache', false)) {
throw new Exception('Memcache class isn\'t available');
throw new InvalidCacheDriverException('Memcache class isn\'t available');
}
parent::__construct($hostname);
$this->memcache = new Memcache();
$this->server = $config->get('system', 'memcache_host');;
$this->port = $config->get('system', 'memcache_port');
$this->server = $config->get('system', 'memcache_host');
$this->port = $config->get('system', 'memcache_port');
if (!@$this->memcache->connect($this->server, $this->port)) {
throw new Exception('Expected Memcache server at ' . $this->server . ':' . $this->port . ' isn\'t available');
throw new CachePersistenceException('Expected Memcache server at ' . $this->server . ':' . $this->port . ' isn\'t available');
}
}
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
$keys = $this->getOriginalKeys($this->getMemcacheKeys());
@ -79,17 +81,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
$return = null;
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
// We fetch with the hostname as key to avoid problems with other applications
$cached = $this->memcache->get($cachekey);
$cached = $this->memcache->get($cacheKey);
// @see http://php.net/manual/en/memcache.get.php#84275
if (is_bool($cached) || is_double($cached) || is_long($cached)) {
return $return;
return null;
}
$value = @unserialize($cached);
@ -98,30 +99,30 @@ class MemcacheCache extends BaseCache implements IMemoryCache
// We also check if the db entry is a serialized
// boolean 'false' value (which we want to return).
if ($cached === serialize(false) || $value !== false) {
$return = $value;
return $value;
}
return $return;
return null;
}
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
// We store with the hostname as key to avoid problems with other applications
if ($ttl > 0) {
return $this->memcache->set(
$cachekey,
$cacheKey,
serialize($value),
MEMCACHE_COMPRESSED,
time() + $ttl
);
} else {
return $this->memcache->set(
$cachekey,
$cacheKey,
serialize($value),
MEMCACHE_COMPRESSED
);
@ -131,16 +132,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
$cachekey = $this->getCacheKey($key);
return $this->memcache->delete($cachekey);
$cacheKey = $this->getCacheKey($key);
return $this->memcache->delete($cacheKey);
}
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
if ($outdated) {
return true;
@ -152,16 +153,16 @@ class MemcacheCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
return $this->memcache->add($cachekey, serialize($value), MEMCACHE_COMPRESSED, $ttl);
$cacheKey = $this->getCacheKey($key);
return $this->memcache->add($cacheKey, serialize($value), MEMCACHE_COMPRESSED, $ttl);
}
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::MEMCACHE;
}

View file

@ -21,7 +21,7 @@
namespace Friendica\Core\Cache\Type;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Core\Cache\Exception\CachePersistenceException;
/**
* Trait for Memcache to add a custom version of the
@ -29,7 +29,7 @@ use Friendica\Network\HTTPException\InternalServerErrorException;
*
* Adds the possibility to directly communicate with the memcache too
*/
trait TraitMemcacheCommand
trait MemcacheCommandTrait
{
/**
* @var string server address
@ -52,23 +52,19 @@ trait TraitMemcacheCommand
*
* @return array All keys of the memcache instance
*
* @throws InternalServerErrorException
* @throws CachePersistenceException
*/
protected function getMemcacheKeys()
protected function getMemcacheKeys(): array
{
$string = $this->sendMemcacheCommand("stats items");
$lines = explode("\r\n", $string);
$slabs = [];
$keys = [];
foreach ($lines as $line) {
if (preg_match("/STAT items:([\d]+):number ([\d]+)/", $line, $matches) &&
isset($matches[1]) &&
!in_array($matches[1], $keys)) {
$slabs[] = $matches[1];
$string = $this->sendMemcacheCommand("stats cachedump " . $matches[1] . " " . $matches[2]);
isset($matches[1]) &&
!in_array($matches[1], $keys)) {
$string = $this->sendMemcacheCommand("stats cachedump " . $matches[1] . " " . $matches[2]);
preg_match_all("/ITEM (.*?) /", $string, $matches);
$keys = array_merge($keys, $matches[1]);
}
@ -88,20 +84,19 @@ trait TraitMemcacheCommand
*
* @return string The returned buffer result
*
* @throws InternalServerErrorException In case the memcache server isn't available (anymore)
* @throws CachePersistenceException In case the memcache server isn't available (anymore)
*/
protected function sendMemcacheCommand(string $command)
protected function sendMemcacheCommand(string $command): string
{
$s = @fsockopen($this->server, $this->port);
if (!$s) {
throw new InternalServerErrorException("Cant connect to:" . $this->server . ':' . $this->port);
throw new CachePersistenceException("Cant connect to:" . $this->server . ':' . $this->port);
}
fwrite($s, $command . "\r\n");
$buf = '';
while (!feof($s)) {
$buf .= fgets($s, 256);
if (strpos($buf, "END\r\n") !== false) { // stat says end

View file

@ -21,25 +21,23 @@
namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Type\TraitCompareDelete;
use Friendica\Core\Cache\Type\TraitCompareSet;
use Friendica\Core\Cache\Type\TraitMemcacheCommand;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Memcached;
use Psr\Log\LoggerInterface;
/**
* Memcached Cache
*/
class MemcachedCache extends BaseCache implements IMemoryCache
class MemcachedCache extends AbstractCache implements ICanCacheInMemory
{
use TraitCompareSet;
use TraitCompareDelete;
use TraitMemcacheCommand;
use CompareSetTrait;
use CompareDeleteTrait;
use MemcacheCommandTrait;
/**
* @var \Memcached
@ -58,14 +56,17 @@ class MemcachedCache extends BaseCache implements IMemoryCache
* 1 => ...
* }
*
* @param array $memcached_hosts
* @param string $hostname
* @param IManageConfigValues $config
* @param LoggerInterface $logger
*
* @throws \Exception
* @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/
public function __construct(string $hostname, IConfig $config, LoggerInterface $logger)
public function __construct(string $hostname, IManageConfigValues $config, LoggerInterface $logger)
{
if (!class_exists('Memcached', false)) {
throw new Exception('Memcached class isn\'t available');
throw new InvalidCacheDriverException('Memcached class isn\'t available');
}
parent::__construct($hostname);
@ -83,19 +84,19 @@ class MemcachedCache extends BaseCache implements IMemoryCache
});
$this->server = $memcached_hosts[0][0] ?? 'localhost';
$this->port = $memcached_hosts[0][1] ?? 11211;
$this->port = $memcached_hosts[0][1] ?? 11211;
$this->memcached->addServers($memcached_hosts);
if (count($this->memcached->getServerList()) == 0) {
throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
throw new CachePersistenceException('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
}
}
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
$keys = $this->getOriginalKeys($this->getMemcacheKeys());
@ -105,40 +106,40 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
$return = null;
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
// We fetch with the hostname as key to avoid problems with other applications
$value = $this->memcached->get($cachekey);
$value = $this->memcached->get($cacheKey);
if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
$return = $value;
return $value;
} elseif ($this->memcached->getResultCode() === Memcached::RES_NOTFOUND) {
$this->logger->notice('Try to use unknown key.', ['key' => $key]);
return null;
} else {
$this->logger->debug('Memcached \'get\' failed', ['result' => $this->memcached->getResultMessage()]);
throw new CachePersistenceException(sprintf('Cannot get cache entry with key %s', $key), new \MemcachedException($this->memcached->getResultMessage(), $this->memcached->getResultCode()));
}
return $return;
}
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
// We store with the hostname as key to avoid problems with other applications
if ($ttl > 0) {
return $this->memcached->set(
$cachekey,
$cacheKey,
$value,
$ttl
);
} else {
return $this->memcached->set(
$cachekey,
$cacheKey,
$value
);
}
@ -147,16 +148,16 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
$cachekey = $this->getCacheKey($key);
return $this->memcached->delete($cachekey);
$cacheKey = $this->getCacheKey($key);
return $this->memcached->delete($cacheKey);
}
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
if ($outdated) {
return true;
@ -168,16 +169,16 @@ class MemcachedCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
return $this->memcached->add($cachekey, $value, $ttl);
$cacheKey = $this->getCacheKey($key);
return $this->memcached->add($cacheKey, $value, $ttl);
}
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::MEMCACHED;
}

View file

@ -22,19 +22,19 @@
namespace Friendica\Core\Cache\Type;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\ICache;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Capability\ICanCache;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Util\Profiler;
/**
* This class wraps cache driver so they can get profiled - in case the profiler is enabled
* This class wraps cache driver, so they can get profiled - in case the profiler is enabled
*
* It is using the decorator pattern (@see
* It is using the decorator pattern (@see https://en.wikipedia.org/wiki/Decorator_pattern )
*/
class ProfilerCache implements ICache, IMemoryCache
class ProfilerCacheDecorator implements ICanCache, ICanCacheInMemory
{
/**
* @var ICache The original cache driver
* @var ICanCache The original cache driver
*/
private $cache;
@ -43,7 +43,7 @@ class ProfilerCache implements ICache, IMemoryCache
*/
private $profiler;
public function __construct(ICache $cache, Profiler $profiler)
public function __construct(ICanCache $cache, Profiler $profiler)
{
$this->cache = $cache;
$this->profiler = $profiler;
@ -52,7 +52,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
$this->profiler->startRecording('cache');
@ -66,7 +66,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function get($key)
public function get(string $key)
{
$this->profiler->startRecording('cache');
@ -80,7 +80,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$this->profiler->startRecording('cache');
@ -94,7 +94,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function delete($key)
public function delete(string $key): bool
{
$this->profiler->startRecording('cache');
@ -108,7 +108,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
$this->profiler->startRecording('cache');
@ -122,9 +122,9 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
if ($this->cache instanceof IMemoryCache) {
if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache');
$return = $this->cache->add($key, $value, $ttl);
@ -140,9 +140,9 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES)
public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{
if ($this->cache instanceof IMemoryCache) {
if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache');
$return = $this->cache->compareSet($key, $oldValue, $newValue, $ttl);
@ -158,9 +158,9 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function compareDelete($key, $value)
public function compareDelete(string $key, $value): bool
{
if ($this->cache instanceof IMemoryCache) {
if ($this->cache instanceof ICanCacheInMemory) {
$this->profiler->startRecording('cache');
$return = $this->cache->compareDelete($key, $value);
@ -176,7 +176,7 @@ class ProfilerCache implements ICache, IMemoryCache
/**
* {@inheritDoc}
*/
public function GetName()
public function GetName(): string
{
return $this->cache->getName() . ' (with profiler)';
}

View file

@ -23,15 +23,17 @@ namespace Friendica\Core\Cache\Type;
use Exception;
use Friendica\Core\Cache\Enum\Duration;
use Friendica\Core\Cache\IMemoryCache;
use Friendica\Core\Cache\Capability\ICanCacheInMemory;
use Friendica\Core\Cache\Enum\Type;
use Friendica\Core\Config\IConfig;
use Friendica\Core\Cache\Exception\CachePersistenceException;
use Friendica\Core\Cache\Exception\InvalidCacheDriverException;
use Friendica\Core\Config\Capability\IManageConfigValues;
use Redis;
/**
* Redis Cache. This driver is based on Memcache driver
*/
class RedisCache extends BaseCache implements IMemoryCache
class RedisCache extends AbstractCache implements ICanCacheInMemory
{
/**
* @var Redis
@ -39,12 +41,13 @@ class RedisCache extends BaseCache implements IMemoryCache
private $redis;
/**
* @throws Exception
* @throws InvalidCacheDriverException
* @throws CachePersistenceException
*/
public function __construct(string $hostname, IConfig $config)
public function __construct(string $hostname, IManageConfigValues $config)
{
if (!class_exists('Redis', false)) {
throw new Exception('Redis class isn\'t available');
throw new InvalidCacheDriverException('Redis class isn\'t available');
}
parent::__construct($hostname);
@ -57,24 +60,24 @@ class RedisCache extends BaseCache implements IMemoryCache
$redis_db = $config->get('system', 'redis_db', 0);
if (isset($redis_port) && !@$this->redis->connect($redis_host, $redis_port)) {
throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
} elseif (!@$this->redis->connect($redis_host)) {
throw new Exception('Expected Redis server at ' . $redis_host . ' isn\'t available');
throw new CachePersistenceException('Expected Redis server at ' . $redis_host . ' isn\'t available');
}
if (isset($redis_pw) && !$this->redis->auth($redis_pw)) {
throw new Exception('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port);
throw new CachePersistenceException('Cannot authenticate redis server at ' . $redis_host . ':' . $redis_port);
}
if ($redis_db !== 0 && !$this->redis->select($redis_db)) {
throw new Exception('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port);
throw new CachePersistenceException('Cannot switch to redis db ' . $redis_db . ' at ' . $redis_host . ':' . $redis_port);
}
}
/**
* (@inheritdoc)
*/
public function getAllKeys($prefix = null)
public function getAllKeys(?string $prefix = null): array
{
if (empty($prefix)) {
$search = '*';
@ -90,13 +93,13 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function get($key)
public function get(string $key)
{
$return = null;
$cachekey = $this->getCacheKey($key);
$return = null;
$cacheKey = $this->getCacheKey($key);
$cached = $this->redis->get($cachekey);
if ($cached === false && !$this->redis->exists($cachekey)) {
$cached = $this->redis->get($cacheKey);
if ($cached === false && !$this->redis->exists($cacheKey)) {
return null;
}
@ -115,21 +118,21 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
public function set(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
$cached = serialize($value);
if ($ttl > 0) {
return $this->redis->setex(
$cachekey,
$cacheKey,
$ttl,
$cached
);
} else {
return $this->redis->set(
$cachekey,
$cacheKey,
$cached
);
}
@ -138,10 +141,10 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function delete($key)
public function delete(string $key): bool
{
$cachekey = $this->getCacheKey($key);
$this->redis->del($cachekey);
$cacheKey = $this->getCacheKey($key);
$this->redis->del($cacheKey);
// Redis doesn't have an error state for del()
return true;
}
@ -149,7 +152,7 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function clear($outdated = true)
public function clear(bool $outdated = true): bool
{
if ($outdated) {
return true;
@ -161,34 +164,30 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
public function add(string $key, $value, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cached = serialize($value);
$cacheKey = $this->getCacheKey($key);
$cached = serialize($value);
return $this->redis->setnx($cachekey, $cached);
return $this->redis->setnx($cacheKey, $cached);
}
/**
* (@inheritdoc)
*/
public function compareSet($key, $oldValue, $newValue, $ttl = Duration::FIVE_MINUTES)
public function compareSet(string $key, $oldValue, $newValue, int $ttl = Duration::FIVE_MINUTES): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
$newCached = serialize($newValue);
$this->redis->watch($cachekey);
$this->redis->watch($cacheKey);
// If the old value isn't what we expected, somebody else changed the key meanwhile
if ($this->get($key) === $oldValue) {
if ($ttl > 0) {
$result = $this->redis->multi()
->setex($cachekey, $ttl, $newCached)
->exec();
$result = $this->redis->multi()->setex($cacheKey, $ttl, $newCached)->exec();
} else {
$result = $this->redis->multi()
->set($cachekey, $newCached)
->exec();
$result = $this->redis->multi()->set($cacheKey, $newCached)->exec();
}
return $result !== false;
}
@ -199,17 +198,15 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* (@inheritdoc)
*/
public function compareDelete($key, $value)
public function compareDelete(string $key, $value): bool
{
$cachekey = $this->getCacheKey($key);
$cacheKey = $this->getCacheKey($key);
$this->redis->watch($cachekey);
$this->redis->watch($cacheKey);
// If the old value isn't what we expected, somebody else changed the key meanwhile
if ($this->get($key) === $value) {
$result = $this->redis->multi()
->del($cachekey)
->exec();
return $result !== false;
$this->redis->multi()->del($cacheKey)->exec();
return true;
}
$this->redis->unwatch();
return false;
@ -218,7 +215,7 @@ class RedisCache extends BaseCache implements IMemoryCache
/**
* {@inheritDoc}
*/
public function getName()
public function getName(): string
{
return Type::REDIS;
}