Skip to content

Commit

Permalink
Merge pull request #13514 from totten/master-nack-rev
Browse files Browse the repository at this point in the history
(dev/core#635) CRM_Utils_Cache::nack() - Fix format
  • Loading branch information
eileenmcnaughton authored Jan 30, 2019
2 parents dce9a66 + 8986147 commit da667a5
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 6 deletions.
11 changes: 6 additions & 5 deletions CRM/Utils/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -285,19 +285,20 @@ public static function getCacheDriver() {
* $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.
* The value should be unique to avoid accidental matches.
*
* @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));
$st =& Civi::$statics[__CLASS__];
if (!isset($st['nack-c'])) {
$st['nack-c'] = md5(CRM_Utils_Request::id() . CIVICRM_SITE_KEY . CIVICRM_DSN . mt_rand(0, 10000));
$st['nack-i'] = 0;
}
return Civi::$statics[__CLASS__];
return 'NACK:' . $st['nack-c'] . $st['nack-i']++;
}

}
2 changes: 1 addition & 1 deletion CRM/Utils/Cache/NaiveHasTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
trait CRM_Utils_Cache_NaiveHasTrait {

public function has($key) {
$nack = CRM_Utils_Cache::nack() . 'ht';
$nack = CRM_Utils_Cache::nack();
$value = $this->get($key, $nack);
return ($value !== $nack);
}
Expand Down
24 changes: 24 additions & 0 deletions tests/phpunit/CRM/Utils/CacheTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/**
* Class CRM_Utils_CacheTest
* @group headless
*/
class CRM_Utils_CacheTest extends CiviUnitTestCase {

public function testNack() {
$values = [];
for ($i = 0; $i < 5; $i++) {
$nack = CRM_Utils_Cache::nack();
$this->assertRegExp('/^NACK:[a-z0-9]+$/', $nack);
$values[] = $nack;
}
sort($values);
$this->assertEquals($values, array_unique($values));

// The random token should at the start should same -- because we don't
// the overhead of re-generating it frequently.
$this->assertEquals(substr($values[0], 0, 37), substr($values[1], 0, 37));
}

}

0 comments on commit da667a5

Please sign in to comment.