Cache.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. namespace Gregwar\Cache;
  3. /**
  4. * A cache system based on files
  5. *
  6. * @author Gregwar <g.passault@gmail.com>
  7. */
  8. class Cache
  9. {
  10. /**
  11. * Cache directory
  12. */
  13. protected $cacheDirectory;
  14. /**
  15. * Use a different directory as actual cache
  16. */
  17. protected $actualCacheDirectory = null;
  18. /**
  19. * Prefix directories size
  20. *
  21. * For instance, if the file is helloworld.txt and the prefix size is
  22. * 5, the cache file will be: h/e/l/l/o/helloworld.txt
  23. *
  24. * This is useful to avoid reaching a too large number of files into the
  25. * cache system directories
  26. */
  27. protected $prefixSize = 5;
  28. /**
  29. * Directory mode
  30. *
  31. * Allows setting of the access mode for the directories created.
  32. */
  33. protected $directoryMode = 0755;
  34. /**
  35. * Constructs the cache system
  36. */
  37. public function __construct($cacheDirectory = 'cache')
  38. {
  39. $this->cacheDirectory = $cacheDirectory;
  40. }
  41. /**
  42. * Sets the cache directory
  43. *
  44. * @param $cacheDirectory the cache directory
  45. */
  46. public function setCacheDirectory($cacheDirectory)
  47. {
  48. $this->cacheDirectory = $cacheDirectory;
  49. return $this;
  50. }
  51. /**
  52. * Gets the cache directory
  53. *
  54. * @return string the cache directory
  55. */
  56. public function getCacheDirectory()
  57. {
  58. return $this->cacheDirectory;
  59. }
  60. /**
  61. * Sets the actual cache directory
  62. */
  63. public function setActualCacheDirectory($actualCacheDirectory = null)
  64. {
  65. $this->actualCacheDirectory = $actualCacheDirectory;
  66. return $this;
  67. }
  68. /**
  69. * Returns the actual cache directory
  70. */
  71. public function getActualCacheDirectory()
  72. {
  73. return $this->actualCacheDirectory ?: $this->cacheDirectory;
  74. }
  75. /**
  76. * Change the prefix size
  77. *
  78. * @param $prefixSize the size of the prefix directories
  79. */
  80. public function setPrefixSize($prefixSize)
  81. {
  82. $this->prefixSize = $prefixSize;
  83. return $this;
  84. }
  85. /**
  86. * Change the directory mode
  87. *
  88. * @param $directoryMode the directory mode to use
  89. */
  90. public function setDirectoryMode($directoryMode)
  91. {
  92. if (!$directoryMode) {
  93. $directoryMode = 0755;
  94. }
  95. $this->directoryMode = $directoryMode;
  96. return $this;
  97. }
  98. /**
  99. * Creates a directory
  100. *
  101. * @param $directory, the target directory
  102. */
  103. protected function mkdir($directory)
  104. {
  105. if (!is_dir($directory)) {
  106. @mkdir($directory, $this->directoryMode, true);
  107. }
  108. }
  109. /**
  110. * Gets the cache file name
  111. *
  112. * @param $filename, the name of the cache file
  113. * @param $actual get the actual file or the public file
  114. * @param $mkdir, a boolean to enable/disable the construction of the
  115. * cache file directory
  116. */
  117. public function getCacheFile($filename, $actual = false, $mkdir = false)
  118. {
  119. $path = array();
  120. // Getting the length of the filename before the extension
  121. $parts = explode('.', $filename);
  122. $len = strlen($parts[0]);
  123. for ($i=0; $i<min($len, $this->prefixSize); $i++) {
  124. $path[] = $filename[$i];
  125. }
  126. $path = implode('/', $path);
  127. $actualDir = $this->getActualCacheDirectory() . '/' . $path;
  128. if ($mkdir && !is_dir($actualDir)) {
  129. mkdir($actualDir, $this->directoryMode, true);
  130. }
  131. $path .= '/' . $filename;
  132. if ($actual) {
  133. return $this->getActualCacheDirectory() . '/' . $path;
  134. } else {
  135. return $this->getCacheDirectory() . '/' . $path;
  136. }
  137. }
  138. /**
  139. * Checks that the cache conditions are respected
  140. *
  141. * @param $cacheFile the cache file
  142. * @param $conditions an array of conditions to check
  143. */
  144. protected function checkConditions($cacheFile, array $conditions = array())
  145. {
  146. // Implicit condition: the cache file should exist
  147. if (!file_exists($cacheFile)) {
  148. return false;
  149. }
  150. foreach ($conditions as $type => $value) {
  151. switch ($type) {
  152. case 'maxage':
  153. case 'max-age':
  154. // Return false if the file is older than $value
  155. $age = time() - filectime($cacheFile);
  156. if ($age > $value) {
  157. return false;
  158. }
  159. break;
  160. case 'younger-than':
  161. case 'youngerthan':
  162. // Return false if the file is older than the file $value, or the files $value
  163. $check = function($filename) use ($cacheFile) {
  164. return !file_exists($filename) || filectime($cacheFile) < filectime($filename);
  165. };
  166. if (!is_array($value)) {
  167. if (!$this->isRemote($value) && $check($value)) {
  168. return false;
  169. }
  170. } else {
  171. foreach ($value as $file) {
  172. if (!$this->isRemote($file) && $check($file)) {
  173. return false;
  174. }
  175. }
  176. }
  177. break;
  178. default:
  179. throw new \Exception('Cache condition '.$type.' not supported');
  180. }
  181. }
  182. return true;
  183. }
  184. /**
  185. * Checks if the targt filename exists in the cache and if the conditions
  186. * are respected
  187. *
  188. * @param $filename the filename
  189. * @param $conditions the conditions to respect
  190. */
  191. public function exists($filename, array $conditions = array())
  192. {
  193. $cacheFile = $this->getCacheFile($filename, true);
  194. return $this->checkConditions($cacheFile, $conditions);
  195. }
  196. /**
  197. * Alias for exists
  198. */
  199. public function check($filename, array $conditions = array())
  200. {
  201. return $this->exists($filename, $conditions);
  202. }
  203. /**
  204. * Write data in the cache
  205. */
  206. public function set($filename, $contents = '')
  207. {
  208. $cacheFile = $this->getCacheFile($filename, true, true);
  209. file_put_contents($cacheFile, $contents);
  210. return $this;
  211. }
  212. /**
  213. * Alias for set()
  214. */
  215. public function write($filename, $contents = '')
  216. {
  217. return $this->set($filename, $contents);
  218. }
  219. /**
  220. * Get data from the cache
  221. */
  222. public function get($filename, array $conditions = array())
  223. {
  224. if ($this->exists($filename, $conditions)) {
  225. return file_get_contents($this->getCacheFile($filename, true));
  226. } else {
  227. return null;
  228. }
  229. }
  230. /**
  231. * Is this URL remote?
  232. */
  233. protected function isRemote($file)
  234. {
  235. return preg_match('/^http(s{0,1}):\/\//', $file);
  236. }
  237. /**
  238. * Get or create the cache entry
  239. *
  240. * @param $filename the cache file name
  241. * @param $conditions an array of conditions about expiration
  242. * @param $function the closure to call if the file does not exists
  243. * @param $file returns the cache file or the file contents
  244. * @param $actual returns the actual cache file
  245. */
  246. public function getOrCreate($filename, array $conditions = array(), $function, $file = false, $actual = false)
  247. {
  248. if (!is_callable($function)) {
  249. throw new InvalidArgumentException('The argument $function should be callable');
  250. }
  251. $cacheFile = $this->getCacheFile($filename, true, true);
  252. $data = null;
  253. if ($this->check($filename, $conditions)) {
  254. $data = file_get_contents($cacheFile);
  255. } else {
  256. if(file_exists($cacheFile)) {
  257. unlink($cacheFile);
  258. }
  259. $data = call_user_func($function, $cacheFile);
  260. // Test if the closure wrote the file or if it returned the data
  261. if (!file_exists($cacheFile)) {
  262. $this->set($filename, $data);
  263. } else {
  264. $data = file_get_contents($cacheFile);
  265. }
  266. }
  267. return $file ? $this->getCacheFile($filename, $actual) : $data;
  268. }
  269. /**
  270. * Alias to getOrCreate with $file = true
  271. */
  272. public function getOrCreateFile($filename, array $conditions = array(), $function, $actual = false)
  273. {
  274. return $this->getOrCreate($filename, $conditions, $function, true, $actual);
  275. }
  276. }