Skip to content

Commit 4836d2c

Browse files
committed
Merge branch 'review-cache'
2 parents aa4ef57 + 3ee42f9 commit 4836d2c

File tree

2 files changed

+19
-3
lines changed

2 files changed

+19
-3
lines changed

src/Store/CacheStore.php

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
use Lkrms\Store\Concept\SqliteStore;
66
use DateTimeInterface;
77
use InvalidArgumentException;
8+
use LogicException;
89

910
/**
1011
* A SQLite-backed key-value store
@@ -61,10 +62,12 @@ public function set(string $key, $value, $expires = null)
6162
} elseif (!$expires) {
6263
$expires = null;
6364
} elseif (!is_int($expires) || $expires < 0) {
65+
// @codeCoverageIgnoreStart
6466
throw new InvalidArgumentException(sprintf(
6567
'Invalid $expires: %s',
6668
$expires
6769
));
70+
// @codeCoverageIgnoreEnd
6871
} elseif ($expires < 1625061600) {
6972
// Assume values less than the timestamp of 1 Jul 2021 00:00:00 AEST
7073
// are lifetimes in seconds
@@ -274,7 +277,11 @@ public function flush()
274277
*/
275278
public function maybeGet(string $key, callable $callback, $expires = null)
276279
{
277-
$store = $this->asOfNow();
280+
$store =
281+
$this->Now === null
282+
? $this->asOfNow()
283+
: $this;
284+
278285
if ($store->has($key)) {
279286
return $store->get($key);
280287
}
@@ -299,8 +306,12 @@ public function maybeGet(string $key, callable $callback, $expires = null)
299306
*/
300307
public function asOfNow(?int $now = null)
301308
{
302-
if ($now === null && $this->Now !== null) {
303-
return $this;
309+
if ($this->Now !== null) {
310+
// @codeCoverageIgnoreStart
311+
throw new LogicException(
312+
sprintf('Calls to %s cannot be nested', __METHOD__)
313+
);
314+
// @codeCoverageIgnoreEnd
304315
}
305316

306317
$clone = clone $this;

tests/unit/Store/CacheStoreTest.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,7 @@ public function testWithExpiration(): void
4747
{
4848
$arr = ['foo' => 'bar'];
4949
$this->Cache->set(__METHOD__, $arr, new DateTimeImmutable('24 hours ago'));
50+
$this->Cache->set('key0', 'value0', new DateTimeImmutable('10 seconds ago'));
5051
$this->Cache->set('key1', 'value1', 60);
5152
$this->Cache->set('key2', 'value2', time() + 60);
5253
$now = time();
@@ -57,6 +58,10 @@ public function testWithExpiration(): void
5758
$this->assertTrue($this->Cache->has(__METHOD__, 0));
5859
$this->assertSame($arr, $this->Cache->get(__METHOD__, 0));
5960

61+
$this->assertFalse($this->Cache->has('key0'));
62+
$this->assertTrue($this->Cache->has('key0', 60));
63+
$this->assertSame('value0', $this->Cache->get('key0', 60));
64+
6065
$this->Cache->flush();
6166
$this->assertFalse($this->Cache->has(__METHOD__, 0));
6267
$this->assertFalse($this->Cache->get(__METHOD__, 0));

0 commit comments

Comments
 (0)