Skip to content

Commit c6a8d46

Browse files
committed
Clarify cache helper callback flow
1 parent 05eddad commit c6a8d46

2 files changed

Lines changed: 34 additions & 3 deletions

File tree

src/Database/Database.php

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8567,9 +8567,10 @@ public function find(string $collection, array $queries = [], string $forPermiss
85678567
/**
85688568
* Execute a callback behind a cache-aside lookup.
85698569
*
8570-
* The callback value is returned to the caller. Use $toCache when the
8571-
* returned value needs to be serialized before saving, and $fromCache when
8572-
* the cached payload needs validation or hydration before reuse.
8570+
* The callback runs on cache miss and its value is returned to the caller.
8571+
* Use $toCache when that value needs serialization before saving, and
8572+
* $fromCache when the cached payload needs validation or hydration before
8573+
* reuse.
85738574
*
85748575
* @template T
85758576
* @param string $key

tests/unit/ListCacheTest.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,36 @@ private function seedProject(Database $database, string $id, string $name): void
4646
]));
4747
}
4848

49+
public function testWithCacheUsesCallbackOnMissAndCachesResult(): void
50+
{
51+
$cache = new HashMemoryCache();
52+
$database = $this->createDatabase($cache);
53+
54+
$callbackCalls = 0;
55+
56+
$value = $database->withCache(
57+
'key',
58+
function () use (&$callbackCalls): array {
59+
$callbackCalls++;
60+
return ['value' => 'fresh'];
61+
},
62+
);
63+
64+
$this->assertSame(['value' => 'fresh'], $value);
65+
$this->assertSame(1, $callbackCalls);
66+
67+
$value = $database->withCache(
68+
'key',
69+
function () use (&$callbackCalls): array {
70+
$callbackCalls++;
71+
return ['value' => 'new'];
72+
},
73+
);
74+
75+
$this->assertSame(['value' => 'fresh'], $value);
76+
$this->assertSame(1, $callbackCalls);
77+
}
78+
4979
public function testWithCacheReturnsValidatedCachedValue(): void
5080
{
5181
$cache = new HashMemoryCache();

0 commit comments

Comments
 (0)