1 <?php
2 /**
3 * Cache.php
4 *
5 * @author Elvyrra S.A.S
6 * @license http://rem.mit-license.org/ MIT
7 */
8
9 namespace Hawk;
10
11 /**
12 * This class is used to manage cache in Hawk. It allows to save cache files in the folder /cache,
13 * and detect if a file is cached. This class is very useful to increase the application performances.
14 *
15 * @package Core
16 */
17 class Cache extends Singleton{
18
19 /**
20 * The cache instance
21 *
22 * @var Cache
23 */
24 protected static $instance;
25
26 /**
27 * Get the full path for a given cache file path, relative to CACHE_DIR
28 *
29 * @param string $cacheFile The path of the cache file
30 *
31 * @return string The full path of the cache file
32 */
33 public function getCacheFilePath($cacheFile){
34 return CACHE_DIR . $cacheFile;
35 }
36
37 /**
38 * Check if a file is cached. This function returns true if $cacheFile does not exist or if $source is newer than $cacheFile
39 *
40 * @param string $source The path of the source file
41 * @param string $cacheFile The path of the cache file, relative to CACHE_DIR
42 *
43 * @return boolean True if the file cached, else false
44 */
45 public function isCached($source, $cacheFile){
46 return is_file($this->getCacheFilePath($cacheFile)) && filemtime($source) < filemtime($this->getCacheFilePath($cacheFile));
47 }
48
49
50 /**
51 * Get the content of a cache file
52 *
53 * @param string $cacheFile The path of the cache file
54 *
55 * @return string The content of the cache file
56 */
57 public function getCacheContent($cacheFile){
58 return file_get_contents($this->getCacheFilePath($cacheFile));
59 }
60
61
62 /**
63 * Include a cache file
64 *
65 * @param string $cacheFile The cache file to include
66 *
67 * @return mixed The data returned in the cache file
68 */
69 public function includeCache($cacheFile){
70 return include $this->getCacheFilePath($cacheFile);
71 }
72
73
74 /**
75 * Save data in a cache file
76 *
77 * @param string $cacheFile The path of the cache file, relative to CACHE_DIR
78 * @param string $content The content to write in the cache file
79 */
80 public function save($cacheFile, $content){
81 if(!is_dir(dirname($this->getCacheFilePath($cacheFile)))) {
82 mkdir(dirname($this->getCacheFilePath($cacheFile)), 0755, true);
83 }
84 file_put_contents($this->getCacheFilePath($cacheFile), $content);
85 }
86
87
88 /**
89 * Clear a cache file or directory
90 *
91 * @param string $cacheFile The cache file or directory to clear
92 */
93 public function clear($cacheFile = '*'){
94 App::fs()->remove($this->getCacheFilePath($cacheFile));
95 }
96
97
98
99 }