diff --git a/CRM/Utils/Cache.php b/CRM/Utils/Cache.php index 3306f821a735..a1cffded146b 100644 --- a/CRM/Utils/Cache.php +++ b/CRM/Utils/Cache.php @@ -258,4 +258,32 @@ public static function getCacheDriver() { return $className; } + /** + * Generate a unique negative-acknowledgement token (NACK). + * + * When using PSR-16 to read a value, the `$cahce->get()` will a return a default + * value on cache-miss, so it's hard to know if you've gotten a geniune value + * from the cache or just a default. If you're in an edge-case where it matters + * (and you want to do has()+get() in a single roundtrip), use the nack() as + * the default: + * + * $nack = CRM_Utils_Cache::nack(); + * $value = $cache->get('foo', $nack); + * echo ($value === $nack) ? "Cache has a value, and we got it" : "Cache has no value". + * + * The value should be unique to avoid accidental matches. As a performance + * tweak, we may reuse the NACK a few times within the current page-view. + * + * @return string + * Unique nonce value indicating a "negative acknowledgement" (failed read). + * If we need to accurately perform has($key)+get($key), we can + * use `get($key,$nack)`. + */ + public static function nack() { + if (!isset(Civi::$statics[__CLASS__]['nack'])) { + Civi::$statics[__CLASS__]['nack'] = 'NACK:' . md5(CRM_Utils_Request::id() . CIVICRM_SITE_KEY . CIVICRM_DSN . mt_rand(0, 10000)); + } + return Civi::$statics[__CLASS__]; + } + } diff --git a/CRM/Utils/Cache/NaiveHasTrait.php b/CRM/Utils/Cache/NaiveHasTrait.php index 4c270b2bd9a3..3a8260e7aff9 100644 --- a/CRM/Utils/Cache/NaiveHasTrait.php +++ b/CRM/Utils/Cache/NaiveHasTrait.php @@ -33,17 +33,14 @@ * The traditional CRM_Utils_Cache_Interface did not support has(). * To get drop-in compliance with PSR-16, we use a naive adapter. * - * Ideally, these should be replaced with more performant/native versions. + * There may be opportunities to replace/optimize in specific drivers. */ trait CRM_Utils_Cache_NaiveHasTrait { public function has($key) { - // This is crazy-talk. If you've got an environment setup where you might - // be investigating this, fix your preferred cache driver by - // replacing `NaiveHasTrait` with a decent function. - $hasDefaultA = ($this->get($key, NULL) === NULL); - $hasDefaultB = ($this->get($key, 123) === 123); - return !($hasDefaultA && $hasDefaultB); + $nack = CRM_Utils_Cache::nack() . 'ht'; + $value = $this->get($key, $nack); + return ($value !== $nack); } }