From d903350b0b445d06819d7160f5c4c0943dfe0f0b Mon Sep 17 00:00:00 2001 From: Tim Otten Date: Fri, 22 Jun 2018 19:22:34 -0700 Subject: [PATCH] Redis - Updates to comply with PSR-16 --- CRM/Utils/Cache/Redis.php | 32 +++++++++++-- .../E2E/Cache/ConfiguredMemoryTest.php | 48 +++++++++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 tests/phpunit/E2E/Cache/ConfiguredMemoryTest.php diff --git a/CRM/Utils/Cache/Redis.php b/CRM/Utils/Cache/Redis.php index 01fc538c9355..d8f60eaa25e8 100644 --- a/CRM/Utils/Cache/Redis.php +++ b/CRM/Utils/Cache/Redis.php @@ -123,10 +123,11 @@ public function __construct($config) { * @throws Exception */ public function set($key, $value, $ttl = NULL) { - if ($ttl !== NULL) { - throw new \RuntimeException("FIXME: " . __CLASS__ . "::set() should support non-NULL TTL"); + CRM_Utils_Cache::assertValidKey($key); + if (is_int($ttl) && $ttl <= 0) { + return $this->delete($key); } - if (!$this->_cache->set($this->_prefix . $key, serialize($value), $this->_timeout)) { + if (!$this->_cache->setex($this->_prefix . $key, $this->convertTtl($ttl), serialize($value))) { if (PHP_SAPI === 'cli' || (Civi\Core\Container::isContainerBooted() && CRM_Core_Permission::check('view debug output'))) { CRM_Core_Error::fatal("Redis set ($key) failed: " . $this->_cache->getLastError()); } @@ -146,6 +147,7 @@ public function set($key, $value, $ttl = NULL) { * @return mixed */ public function get($key, $default = NULL) { + CRM_Utils_Cache::assertValidKey($key); $result = $this->_cache->get($this->_prefix . $key); return ($result === FALSE) ? $default : unserialize($result); } @@ -156,6 +158,7 @@ public function get($key, $default = NULL) { * @return bool */ public function delete($key) { + CRM_Utils_Cache::assertValidKey($key); $this->_cache->delete($this->_prefix . $key); return TRUE; } @@ -177,4 +180,27 @@ public function clear() { return $this->flush(); } + /** + * Normalize a TTL. + * + * @param NULL|int|DateInterval $ttl + * @return int + * Seconds until expiration. + * @throws \CRM_Utils_Cache_InvalidArgumentException + */ + private function convertTtl($ttl) { + if ($ttl === NULL) { + return self::DEFAULT_TIMEOUT; + } + elseif (is_int($ttl)) { + return $ttl; + } + elseif ($ttl instanceof DateInterval) { + return date_add(new DateTime(), $ttl)->getTimestamp() - time(); + } + else { + throw new CRM_Utils_Cache_InvalidArgumentException("Invalid cache TTL"); + } + } + } diff --git a/tests/phpunit/E2E/Cache/ConfiguredMemoryTest.php b/tests/phpunit/E2E/Cache/ConfiguredMemoryTest.php new file mode 100644 index 000000000000..5f1ea8bc079f --- /dev/null +++ b/tests/phpunit/E2E/Cache/ConfiguredMemoryTest.php @@ -0,0 +1,48 @@ +markTestSkipped('This environment is not configured to use a memory-backed cache service.'); + } + } + +}