Skip to content

Commit ff1497c

Browse files
authored
fix $item (#8)
* fix $item move logging
1 parent edb414a commit ff1497c

File tree

1 file changed

+13
-5
lines changed

1 file changed

+13
-5
lines changed

src/CacheWithResilience.php

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -63,8 +63,9 @@ public function getItem(string $key, bool $returnStaleValue = false): CacheItemI
6363
// when we want the item to be consider as expired, the second one is the real TTL that we tell redis.
6464
// The second one is only mean to be used in case of issues like DB down and only requires to
6565
// set $returnStaleValue to true
66-
if (false === $returnStaleValue && time() > $value['expiresAt']) {
67-
// we need edit the item to return false when calling "$item->isHit()". In order to do that
66+
$standardCacheLifetimeExpired = (time() > $value['expiresAt']);
67+
if (false === $returnStaleValue && $standardCacheLifetimeExpired) {
68+
// we need to edit the item to return false when calling "$item->isHit()". In order to do that
6869
// we can't edit the $item properties directly because they are protected but instead we can use a bind
6970
// closure, this is actually what symfony does to instantiate the item
7071
$resetCacheItem = \Closure::bind(
@@ -79,6 +80,11 @@ function () {
7980
return $resetCacheItem();
8081
}
8182

83+
if ($returnStaleValue && $standardCacheLifetimeExpired) {
84+
$this->staleContentServedCounter++;
85+
$this->logger->error('stale-if-error number ' . $this->staleContentServedCounter . ' served for: ' . $key);
86+
}
87+
8288
// in setItem() value gets wrapped into an array. set the item to its original value
8389
$val = $item->get();
8490
$item->set($val['value']);
@@ -117,7 +123,11 @@ public function setItem(CacheItemInterface $item, $value, $ttl): bool
117123
// instead of setting the item to expire at $expiresAt we use "$resilienceTtl"
118124
// this way in case of error we can return the stale value
119125
$item->expiresAfter($this->resilienceTtl);
120-
return $this->cachePool->save($item);
126+
$result = $this->cachePool->save($item);
127+
// Because PHP assigns objects by reference after storing the $item in redis we should set it back to
128+
// its original value, this way further operations on $item will behalf as expected
129+
$item->set($value);
130+
return $result;
121131
}
122132

123133
/**
@@ -147,8 +157,6 @@ public function getOrSet(string $key, $ttl, callable $function, array $arguments
147157
// return stale value instead of failing
148158
$cacheItem = $this->getItem($key, true);
149159
if ($cacheItem->isHit()) {
150-
$this->staleContentServedCounter++;
151-
$this->logger->error('stale-if-error number ' . $this->staleContentServedCounter . ' served for: ' . $key);
152160
$this->logger->error($e->getMessage());
153161
return $cacheItem->get();
154162
}

0 commit comments

Comments
 (0)