]> git.mxchange.org Git - friendica.git/blob - src/Core/Cache/DatabaseCacheDriver.php
Add ICacheDriver->getAllKeys method
[friendica.git] / src / Core / Cache / DatabaseCacheDriver.php
1 <?php
2
3 namespace Friendica\Core\Cache;
4
5 use Friendica\Core\Cache;
6 use Friendica\Database\DBA;
7 use Friendica\Util\DateTimeFormat;
8
9 /**
10  * Database Cache Driver
11  *
12  * @author Hypolite Petovan <hypolite@mrpetovan.com>
13  */
14 class DatabaseCacheDriver extends AbstractCacheDriver implements ICacheDriver
15 {
16         /**
17          * (@inheritdoc)
18          */
19         public function getAllKeys()
20         {
21                 $stmt = DBA::select('cache', ['k'], ['`expires` >= ?', DateTimeFormat::utcNow()]);
22
23                 return DBA::toArray($stmt);
24         }
25
26         /**
27          * (@inheritdoc)
28          */
29         public function get($key)
30         {
31                 $cache = DBA::selectFirst('cache', ['v'], ['`k` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
32
33                 if (DBA::isResult($cache)) {
34                         $cached = $cache['v'];
35                         $value = @unserialize($cached);
36
37                         // Only return a value if the serialized value is valid.
38                         // We also check if the db entry is a serialized
39                         // boolean 'false' value (which we want to return).
40                         if ($cached === serialize(false) || $value !== false) {
41                                 return $value;
42                         }
43                 }
44
45                 return null;
46         }
47
48         /**
49          * (@inheritdoc)
50          */
51         public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
52         {
53                 $fields = [
54                         'v'       => serialize($value),
55                         'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds'),
56                         'updated' => DateTimeFormat::utcNow()
57                 ];
58
59                 return DBA::update('cache', $fields, ['k' => $key], true);
60         }
61
62         /**
63          * (@inheritdoc)
64          */
65         public function delete($key)
66         {
67                 return DBA::delete('cache', ['k' => $key]);
68         }
69
70         /**
71          * (@inheritdoc)
72          */
73         public function clear($outdated = true)
74         {
75                 if ($outdated) {
76                         return DBA::delete('cache', ['`expires` < NOW()']);
77                 } else {
78                         return DBA::delete('cache', ['`k` IS NOT NULL ']);
79                 }
80         }
81 }