* @package generis */ class KeyValueCache extends ConfigurableService implements SimpleCache { use MultipleCacheTrait; const OPTION_PERSISTENCE = 'persistence'; /** @var common_persistence_KeyValuePersistence */ private $persistence; public function set($key, $value, $ttl = null) { if ($ttl instanceof DateInterval) { $ttl = $this->dateIntervalToSeconds($ttl); } return $this->getPersistence()->set($key, $value, $ttl); } public function clear() { try { return $this->getPersistence()->purge(); } catch (common_exception_NotImplemented $e) { return false; } } public function delete($key) { return $this->getPersistence()->del($key); } public function get($key, $default = null) { $returnValue = $this->getPersistence()->get($key); // persistence can return false on a value of false or a not found key return ($returnValue !== false || $this->has($key)) ? $returnValue : $default; } public function has($key) { return $this->getPersistence()->exists($key); } protected function dateIntervalToSeconds(DateInterval $dateInterval): int { $reference = new DateTimeImmutable; $endTime = $reference->add($dateInterval); return $endTime->getTimestamp() - $reference->getTimestamp(); } /** * @return common_persistence_KeyValuePersistence */ protected function getPersistence() { if (is_null($this->persistence)) { $this->persistence = $this->getServiceLocator()->get(PersistenceManager::SERVICE_ID)->getPersistenceById($this->getOption(self::OPTION_PERSISTENCE)); } return $this->persistence; } }