Skip to content

Commit a68e8d5

Browse files
committed
remove excessive cache key generator calls
1 parent e2eb4de commit a68e8d5

2 files changed

Lines changed: 12 additions & 3 deletions

File tree

src/CacheBuilder.php

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,11 @@ class CacheBuilder implements ICacheBuilder {
6565
*/
6666
private $dispatcher = null;
6767

68+
/**
69+
* @var bool
70+
*/
71+
private $isCacheKeyStale = true;
72+
6873
/**
6974
* @var Closure
7075
*/
@@ -131,7 +136,7 @@ public function get() {
131136

132137
// the cache key used for setting a value may be different than the key used to get a value if upstream
133138
// ...dependencies and state have changed - to be safe, we regenerate the key
134-
$this->cacheKey = null;
139+
$this->isCacheKeyStale = true;
135140
$key = $this->getCacheKey();
136141
if($this->getCache() !== null && $key !== null) {
137142
$cacheLifespanBuilder = $this->cacheLifespanBuilder;
@@ -157,9 +162,10 @@ public function getCache() : ?CacheInterface {
157162
}
158163

159164
public function getCacheKey() : ?string {
160-
if($this->cacheKey === null) {
165+
if($this->isCacheKeyStale) {
161166
$cacheKeyBuilder = $this->cacheKeyBuilder;
162167
$this->cacheKey = $cacheKeyBuilder();
168+
$this->isCacheKeyStale = false;
163169
}
164170
return $this->cacheKey;
165171
}

tests/CacheBuilder_Test.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -412,14 +412,16 @@ public function Cache_hit_fails_validation_with_build_and_updated_cache_key(bool
412412
[static::equalTo((new Event('cache:set.success'))->withCache($cache, 'bar'))]
413413
);
414414
$key = 'foo';
415+
$counter = 0;
415416

416417
// act
417418
$builder = (new CacheBuilder())
418419
->withBuilder(function() use (&$key) : string {
419420
$key = 'bar';
420421
return 'xyzzy';
421422
})
422-
->withCache($cache, function() use (&$key) : string {
423+
->withCache($cache, function() use (&$key, &$counter) : string {
424+
$counter++;
423425
return $key;
424426
})
425427
->withCacheValidator(function($result) : bool {
@@ -439,6 +441,7 @@ public function Cache_hit_fails_validation_with_build_and_updated_cache_key(bool
439441

440442
// assert
441443
static::assertEquals('xyzzy', $result);
444+
static::assertEquals(2, $counter);
442445
}
443446

444447
/**

0 commit comments

Comments
 (0)