From 8ae000358591d4bc603f0d14d7154a78894aea1a Mon Sep 17 00:00:00 2001 From: John Zwarthoed Date: Tue, 20 May 2025 13:33:41 +0200 Subject: [PATCH] Added option to always defer for flexible cache --- src/Illuminate/Cache/Repository.php | 5 +++-- tests/Integration/Cache/RepositoryTest.php | 25 ++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Cache/Repository.php b/src/Illuminate/Cache/Repository.php index 3eb6f700ed01..5b55da8e3008 100755 --- a/src/Illuminate/Cache/Repository.php +++ b/src/Illuminate/Cache/Repository.php @@ -483,9 +483,10 @@ public function rememberForever($key, Closure $callback) * @param array{ 0: \DateTimeInterface|\DateInterval|int, 1: \DateTimeInterface|\DateInterval|int } $ttl * @param (callable(): TCacheValue) $callback * @param array{ seconds?: int, owner?: string }|null $lock + * @param bool $alwaysDefer * @return TCacheValue */ - public function flexible($key, $ttl, $callback, $lock = null) + public function flexible($key, $ttl, $callback, $lock = null, $alwaysDefer = false) { [ $key => $value, @@ -520,7 +521,7 @@ public function flexible($key, $ttl, $callback, $lock = null) }); }; - defer($refresh, "illuminate:cache:flexible:{$key}"); + defer($refresh, "illuminate:cache:flexible:{$key}", $alwaysDefer); return $value; } diff --git a/tests/Integration/Cache/RepositoryTest.php b/tests/Integration/Cache/RepositoryTest.php index 8b13595cd5c5..ea340418b298 100644 --- a/tests/Integration/Cache/RepositoryTest.php +++ b/tests/Integration/Cache/RepositoryTest.php @@ -238,6 +238,31 @@ public function testItImplicitlyClearsTtlKeysFromFileDriver() $this->assertTrue($cache->missing('illuminate:cache:flexible:created:count')); } + public function testItCanAlwaysDefer() + { + $this->freezeTime(); + $cache = Cache::driver('array'); + $count = 0; + + // Cache is empty. The value should be populated... + $cache->flexible('foo', [10, 20], function () use (&$count) { + return ++$count; + }, alwaysDefer: true); + + // First call to flexible() should not defer + $this->assertCount(0, defer()); + + Carbon::setTestNow(now()->addSeconds(11)); + + // Second callback should defer with always now true + $cache->flexible('foo', [10, 20], function () use (&$count) { + return ++$count; + }, alwaysDefer: true); + + $this->assertCount(1, defer()); + $this->assertTrue(defer()->first()->always); + } + public function testItRoundsDateTimeValuesToAccountForTimePassedDuringScriptExecution() { // do not freeze time as this test depends on time progressing duration execution.