]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | ||
3 | namespace Shaarli\Render; | |
4 | ||
5 | use DatePeriod; | |
6 | use Shaarli\Feed\CachedPage; | |
7 | ||
8 | /** | |
9 | * Cache utilities | |
10 | */ | |
11 | class PageCacheManager | |
12 | { | |
13 | /** @var string Cache directory */ | |
14 | protected $pageCacheDir; | |
15 | ||
16 | /** @var bool */ | |
17 | protected $isLoggedIn; | |
18 | ||
19 | public function __construct(string $pageCacheDir, bool $isLoggedIn) | |
20 | { | |
21 | $this->pageCacheDir = $pageCacheDir; | |
22 | $this->isLoggedIn = $isLoggedIn; | |
23 | } | |
24 | ||
25 | /** | |
26 | * Purges all cached pages | |
27 | * | |
28 | * @return string|null an error string if the directory is missing | |
29 | */ | |
30 | public function purgeCachedPages(): ?string | |
31 | { | |
32 | if (!is_dir($this->pageCacheDir)) { | |
33 | $error = sprintf(t('Cannot purge %s: no directory'), $this->pageCacheDir); | |
34 | error_log($error); | |
35 | ||
36 | return $error; | |
37 | } | |
38 | ||
39 | array_map('unlink', glob($this->pageCacheDir . '/*.cache')); | |
40 | ||
41 | return null; | |
42 | } | |
43 | ||
44 | /** | |
45 | * Invalidates caches when the database is changed or the user logs out. | |
46 | */ | |
47 | public function invalidateCaches(): void | |
48 | { | |
49 | // Purge page cache shared by sessions. | |
50 | $this->purgeCachedPages(); | |
51 | } | |
52 | ||
53 | /** | |
54 | * Get CachedPage instance for provided URL. | |
55 | * | |
56 | * @param string $pageUrl | |
57 | * @param ?DatePeriod $validityPeriod Optionally specify a time limit on requested cache | |
58 | * | |
59 | * @return CachedPage | |
60 | */ | |
61 | public function getCachePage(string $pageUrl, DatePeriod $validityPeriod = null): CachedPage | |
62 | { | |
63 | return new CachedPage( | |
64 | $this->pageCacheDir, | |
65 | $pageUrl, | |
66 | false === $this->isLoggedIn, | |
67 | $validityPeriod | |
68 | ); | |
69 | } | |
70 | } |