Skip to content

Commit 6ffbcc2

Browse files
committed
fix: make router cache attributes time independent
1 parent 12cf2b4 commit 6ffbcc2

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

system/Router/Attributes/Cache.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Attribute;
1717
use CodeIgniter\HTTP\RequestInterface;
1818
use CodeIgniter\HTTP\ResponseInterface;
19+
use CodeIgniter\I18n\Time;
1920

2021
/**
2122
* Cache Attribute
@@ -74,7 +75,8 @@ public function before(RequestInterface $request): RequestInterface|ResponseInte
7475
foreach ($cached['headers'] as $name => $value) {
7576
$response->setHeader($name, $value);
7677
}
77-
$response->setHeader('Age', (string) (time() - ($cached['timestamp'] ?? time())));
78+
$time = Time::now()->getTimestamp();
79+
$response->setHeader('Age', (string) ($time - ($cached['timestamp'] ?? $time)));
7880

7981
return $response;
8082
}
@@ -122,7 +124,7 @@ public function after(RequestInterface $request, ResponseInterface $response): ?
122124
'body' => $response->getBody(),
123125
'headers' => $headers,
124126
'status' => $response->getStatusCode(),
125-
'timestamp' => time(),
127+
'timestamp' => Time::now()->getTimestamp(),
126128
];
127129

128130
cache()->save($cacheKey, $data, $this->for);

tests/system/Router/Attributes/CacheTest.php

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use CodeIgniter\HTTP\ResponseInterface;
1818
use CodeIgniter\HTTP\SiteURI;
1919
use CodeIgniter\HTTP\UserAgent;
20+
use CodeIgniter\I18n\Time;
2021
use CodeIgniter\Test\CIUnitTestCase;
2122
use CodeIgniter\Test\Mock\MockAppConfig;
2223
use Config\Services;
@@ -34,6 +35,8 @@ protected function setUp(): void
3435

3536
// Clear cache before each test
3637
cache()->clean();
38+
39+
Time::setTestNow('2026-01-10 12:00:00');
3740
}
3841

3942
public function testConstructorDefaults(): void
@@ -73,7 +76,7 @@ public function testBeforeReturnsCachedResponseWhenFound(): void
7376
'body' => 'Cached content',
7477
'status' => 200,
7578
'headers' => ['Content-Type' => 'text/html'],
76-
'timestamp' => time() - 10,
79+
'timestamp' => Time::now()->getTimestamp() - 10,
7780
];
7881
cache()->save($cacheKey, $cachedData, 3600);
7982

@@ -124,7 +127,7 @@ public function testBeforeUsesCustomCacheKey(): void
124127
'body' => 'Custom cached content',
125128
'status' => 200,
126129
'headers' => [],
127-
'timestamp' => time(),
130+
'timestamp' => Time::now()->getTimestamp(),
128131
];
129132
cache()->save('my_custom_key', $cachedData, 3600);
130133

0 commit comments

Comments
 (0)