Cache.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. <?php
  2. require_once(__DIR__ . '/CacheInterface.php');
  3. class Cache {
  4. static protected $dirCache;
  5. public function __construct(){
  6. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  7. }
  8. static public function create($nameCache){
  9. if(!static::isValidNameCache($nameCache)){
  10. throw new \InvalidArgumentException('Name cache must be at least one
  11. uppercase follow or not by alphanumeric or dash characters.');
  12. }
  13. $pathCache = self::getDir() . $nameCache . '.php';
  14. if(!file_exists($pathCache)){
  15. throw new \Exception('The cache you looking for does not exist.');
  16. }
  17. require_once $pathCache;
  18. return new $nameCache();
  19. }
  20. static public function setDir($dirCache){
  21. if(!is_string($dirCache)){
  22. throw new \InvalidArgumentException('Dir cache must be a string.');
  23. }
  24. if(!file_exists($dirCache)){
  25. throw new \Exception('Dir cache does not exist.');
  26. }
  27. self::$dirCache = $dirCache;
  28. }
  29. static public function getDir(){
  30. $dirCache = self::$dirCache;
  31. if(is_null($dirCache)){
  32. throw new \LogicException(__CLASS__ . ' class need to know cache path !');
  33. }
  34. return $dirCache;
  35. }
  36. static public function isValidNameCache($nameCache){
  37. return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameCache);
  38. }
  39. static public function utf8_encode_deep(&$input){
  40. if (is_string($input)){
  41. $input = utf8_encode($input);
  42. } elseif(is_array($input)){
  43. foreach($input as &$value){
  44. Cache::utf8_encode_deep($value);
  45. }
  46. unset($value);
  47. } elseif(is_object($input)){
  48. $vars = array_keys(get_object_vars($input));
  49. foreach($vars as $var){
  50. Cache::utf8_encode_deep($input->$var);
  51. }
  52. }
  53. }
  54. static public function purge(){
  55. $cacheTimeLimit = time() - 86400; // 86400 -> 24h
  56. $cachePath = 'cache';
  57. if(file_exists($cachePath)){
  58. $cacheIterator = new RecursiveIteratorIterator(
  59. new RecursiveDirectoryIterator($cachePath),
  60. RecursiveIteratorIterator::CHILD_FIRST
  61. );
  62. foreach($cacheIterator as $cacheFile){
  63. if(in_array($cacheFile->getBasename(), array('.', '..')))
  64. continue;
  65. elseif($cacheFile->isFile()){
  66. if(filemtime($cacheFile->getPathname()) < $cacheTimeLimit)
  67. unlink($cacheFile->getPathname());
  68. }
  69. }
  70. }
  71. }
  72. }