Skip to content

Commit

Permalink
Ensure datetime cache durations account for script execution time
Browse files Browse the repository at this point in the history
  • Loading branch information
timacdonald committed Nov 6, 2024
1 parent ca0617a commit b9b50c0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/Illuminate/Cache/Repository.php
Original file line number Diff line number Diff line change
Expand Up @@ -625,6 +625,8 @@ protected function getSeconds($ttl)

if ($duration instanceof DateTimeInterface) {
$duration = Carbon::now()->diffInSeconds($duration, false);

$duration = (int) ceil($duration);
}

return (int) ($duration > 0 ? $duration : 0);
Expand Down
19 changes: 19 additions & 0 deletions tests/Integration/Cache/RepositoryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@

namespace Illuminate\Tests\Integration\Cache;

use Illuminate\Cache\Events\KeyWritten;
use Illuminate\Foundation\Testing\LazilyRefreshDatabase;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Event;
use Orchestra\Testbench\Attributes\WithMigration;
use Orchestra\Testbench\TestCase;

Expand Down Expand Up @@ -235,4 +237,21 @@ public function testItImplicitlyClearsTtlKeysFromFileDriver()
$this->assertFalse($cache->getFilesystem()->exists($cache->path('illuminate:cache:flexible:created:count')));
$this->assertTrue($cache->missing('illuminate:cache:flexible:created:count'));
}

public function testItRoundsDateTimeValuesToAccountForTimePassedDuringScriptExecution()
{
// do not freeze time as this test depends on time progressing duration execution.
$cache = Cache::driver('array');
$events = [];
Event::listen(function (KeyWritten $event) use (&$events) {
$events[] = $event;
});

$result = $cache->put('foo', 'bar', now()->addSecond());

$this->assertTrue($result);
$this->assertCount(1, $events);
$this->assertSame('foo', $events[0]->key);
$this->assertSame(1, $events[0]->seconds);
}
}

0 comments on commit b9b50c0

Please sign in to comment.