init
[garradin.git] / include / lib.static_cache.php
1 <?php
2
3 namespace Garradin;
4
5 class Static_Cache
6 {
7 const EXPIRE = 3600; // 1h
8 const CLEAN_EXPIRE = 86400; // 1 day
9
10 protected static function _getCacheDir()
11 {
12 return DATA_ROOT . '/cache/static';
13 }
14
15 protected static function _getCachePath($id)
16 {
17 $id = 'cache_' . sha1($id);
18 return self::_getCacheDir() . '/' . $id;
19 }
20
21 static public function store($id, $content)
22 {
23 $path = self::_getCachePath($id);
24 return (bool) file_put_contents($path, $content);
25 }
26
27 static public function expired($id, $expire = self::EXPIRE)
28 {
29 $path = self::_getCachePath($id);
30 $time = @filemtime($path);
31
32 if (!$time)
33 {
34 return true;
35 }
36
37 return ($time > (time() - (int)$expire)) ? false : true;
38 }
39
40 static public function get($id)
41 {
42 $path = self::_getCachePath($id);
43 return file_get_contents($path);
44 }
45
46 static public function display($id)
47 {
48 $path = self::_getCachePath($id);
49 return readfile($path);
50 }
51
52 static public function getPath($id)
53 {
54 return self::_getCachePath($id);
55 }
56
57 static public function remove($id)
58 {
59 $path = self::_getCachePath($id);
60 return unlink($path);
61 }
62
63 static public function clean($expire = self::CLEAN_EXPIRE)
64 {
65 $dir = self::_getCacheDir();
66 $d = dir($dir);
67
68 $expire = time() - $expire;
69
70 while ($file = $d->read())
71 {
72 if ($file[0] == '.')
73 {
74 continue;
75 }
76
77 if (filemtime($dir . '/' . $file) > $expire)
78 {
79 unlink($dir . '/' . $file);
80 }
81 }
82
83 $d->close();
84
85 return true;
86 }
87 }