Skip to content

Commit 091d4d4

Browse files
authored
Ensure datetime cache durations account for script execution time (#53431)
1 parent 47a6953 commit 091d4d4

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/Illuminate/Cache/Repository.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -624,7 +624,9 @@ protected function getSeconds($ttl)
624624
$duration = $this->parseDateInterval($ttl);
625625

626626
if ($duration instanceof DateTimeInterface) {
627-
$duration = Carbon::now()->diffInSeconds($duration, false);
627+
$duration = (int) ceil(
628+
Carbon::now()->diffInMilliseconds($duration, false) / 1000
629+
);
628630
}
629631

630632
return (int) ($duration > 0 ? $duration : 0);

tests/Integration/Cache/RepositoryTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@
22

33
namespace Illuminate\Tests\Integration\Cache;
44

5+
use Illuminate\Cache\Events\KeyWritten;
56
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
67
use Illuminate\Support\Carbon;
78
use Illuminate\Support\Facades\Cache;
9+
use Illuminate\Support\Facades\Event;
810
use Orchestra\Testbench\Attributes\WithMigration;
911
use Orchestra\Testbench\TestCase;
1012

@@ -235,4 +237,21 @@ public function testItImplicitlyClearsTtlKeysFromFileDriver()
235237
$this->assertFalse($cache->getFilesystem()->exists($cache->path('illuminate:cache:flexible:created:count')));
236238
$this->assertTrue($cache->missing('illuminate:cache:flexible:created:count'));
237239
}
240+
241+
public function testItRoundsDateTimeValuesToAccountForTimePassedDuringScriptExecution()
242+
{
243+
// do not freeze time as this test depends on time progressing duration execution.
244+
$cache = Cache::driver('array');
245+
$events = [];
246+
Event::listen(function (KeyWritten $event) use (&$events) {
247+
$events[] = $event;
248+
});
249+
250+
$result = $cache->put('foo', 'bar', now()->addSecond());
251+
252+
$this->assertTrue($result);
253+
$this->assertCount(1, $events);
254+
$this->assertSame('foo', $events[0]->key);
255+
$this->assertSame(1, $events[0]->seconds);
256+
}
238257
}

0 commit comments

Comments
 (0)