]> git.immae.eu Git - github/shaarli/Shaarli.git/blame - application/feed/CachedPage.php
Daily RSS Cache: invalidate cache base on the date
[github/shaarli/Shaarli.git] / application / feed / CachedPage.php
CommitLineData
01e48f26 1<?php
dfc650aa 2
f00600a2
A
3declare(strict_types=1);
4
dfc650aa 5namespace Shaarli\Feed;
f24896b2 6
f00600a2
A
7use DatePeriod;
8
01e48f26
V
9/**
10 * Simple cache system, mainly for the RSS/ATOM feeds
11 */
12class CachedPage
13{
f00600a2
A
14 /** Directory containing page caches */
15 protected $cacheDir;
16
17 /** Should this URL be cached (boolean)? */
18 protected $shouldBeCached;
01e48f26 19
f00600a2
A
20 /** Name of the cache file for this URL */
21 protected $filename;
01e48f26 22
f00600a2
A
23 /** @var DatePeriod|null Optionally specify a period of time for cache validity */
24 protected $validityPeriod;
01e48f26
V
25
26 /**
27 * Creates a new CachedPage
28 *
f00600a2
A
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
01e48f26 33 */
f00600a2 34 public function __construct($cacheDir, $url, $shouldBeCached, ?DatePeriod $validityPeriod)
01e48f26
V
35 {
36 // TODO: check write access to the cache directory
37 $this->cacheDir = $cacheDir;
dfc650aa 38 $this->filename = $this->cacheDir . '/' . sha1($url) . '.cache';
01e48f26 39 $this->shouldBeCached = $shouldBeCached;
f00600a2 40 $this->validityPeriod = $validityPeriod;
01e48f26
V
41 }
42
43 /**
44 * Returns the cached version of a page, if it exists and should be cached
45 *
7af9a418 46 * @return string a cached version of the page if it exists, null otherwise
01e48f26
V
47 */
48 public function cachedVersion()
49 {
50 if (!$this->shouldBeCached) {
51 return null;
52 }
f00600a2
A
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 }
01e48f26 64 }
f00600a2
A
65
66 return file_get_contents($this->filename);
01e48f26
V
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}