]>
Commit | Line | Data |
---|---|---|
1 | <?php | |
2 | ||
3 | declare(strict_types=1); | |
4 | ||
5 | namespace Shaarli\Feed; | |
6 | ||
7 | use DatePeriod; | |
8 | ||
9 | /** | |
10 | * Simple cache system, mainly for the RSS/ATOM feeds | |
11 | */ | |
12 | class CachedPage | |
13 | { | |
14 | /** Directory containing page caches */ | |
15 | protected $cacheDir; | |
16 | ||
17 | /** Should this URL be cached (boolean)? */ | |
18 | protected $shouldBeCached; | |
19 | ||
20 | /** Name of the cache file for this URL */ | |
21 | protected $filename; | |
22 | ||
23 | /** @var DatePeriod|null Optionally specify a period of time for cache validity */ | |
24 | protected $validityPeriod; | |
25 | ||
26 | /** | |
27 | * Creates a new CachedPage | |
28 | * | |
29 | * @param string $cacheDir page cache directory | |
30 | * @param string $url page URL | |
31 | * @param bool $shouldBeCached whether this page needs to be cached | |
32 | * @param ?DatePeriod $validityPeriod Optionally specify a time limit on requested cache | |
33 | */ | |
34 | public function __construct($cacheDir, $url, $shouldBeCached, ?DatePeriod $validityPeriod) | |
35 | { | |
36 | // TODO: check write access to the cache directory | |
37 | $this->cacheDir = $cacheDir; | |
38 | $this->filename = $this->cacheDir . '/' . sha1($url) . '.cache'; | |
39 | $this->shouldBeCached = $shouldBeCached; | |
40 | $this->validityPeriod = $validityPeriod; | |
41 | } | |
42 | ||
43 | /** | |
44 | * Returns the cached version of a page, if it exists and should be cached | |
45 | * | |
46 | * @return string a cached version of the page if it exists, null otherwise | |
47 | */ | |
48 | public function cachedVersion() | |
49 | { | |
50 | if (!$this->shouldBeCached) { | |
51 | return null; | |
52 | } | |
53 | if (!is_file($this->filename)) { | |
54 | return null; | |
55 | } | |
56 | if ($this->validityPeriod !== null) { | |
57 | $cacheDate = \DateTime::createFromFormat('U', (string) filemtime($this->filename)); | |
58 | if ( | |
59 | $cacheDate < $this->validityPeriod->getStartDate() | |
60 | || $cacheDate > $this->validityPeriod->getEndDate() | |
61 | ) { | |
62 | return null; | |
63 | } | |
64 | } | |
65 | ||
66 | return file_get_contents($this->filename); | |
67 | } | |
68 | ||
69 | /** | |
70 | * Puts a page in the cache | |
71 | * | |
72 | * @param string $pageContent XML content to cache | |
73 | */ | |
74 | public function cache($pageContent) | |
75 | { | |
76 | if (!$this->shouldBeCached) { | |
77 | return; | |
78 | } | |
79 | file_put_contents($this->filename, $pageContent); | |
80 | } | |
81 | } |