PageRenderTime 47ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/core/classes/framework/cache/engine/file.php

https://github.com/GinoPane/fantasia
PHP | 139 lines | 107 code | 25 blank | 7 comment | 16 complexity | c533133b55fa5da1490eda0bc3b0a2af MD5 | raw file
  1. <?php
  2. class Cache_Engine_File implements Cache_Interface {
  3. private $_cacheDir = null;
  4. /**
  5. *
  6. * Creates new FileBasedCache instance
  7. *
  8. * @param string $directory
  9. * @throws Exception
  10. */
  11. function __construct($directory = "")
  12. {
  13. if (!$directory)
  14. {
  15. $directory = Loader::getCacheDirectoryPath();
  16. }
  17. else
  18. {
  19. $directory = Loader::getDirectPath($directory);
  20. }
  21. if (!is_dir($directory) || !is_writable($directory))
  22. {
  23. throw new Exception("Directory \"{$directory}\" is not writeable or does not exist!");
  24. }
  25. else
  26. {
  27. $this->_cacheDir = $directory;
  28. }
  29. }
  30. private function _cacheFileName($key)
  31. {
  32. return $this->_cacheDir . Cfg_App::DS . md5($key);
  33. }
  34. public function get($key)
  35. {
  36. $cachePath = $this->_cacheFileName($key);
  37. $cache = null;
  38. if (is_readable($cachePath))
  39. {
  40. $fp = fopen($cachePath, 'rb');
  41. if ($fp)
  42. {
  43. flock($fp, LOCK_SH);
  44. $cache = '';
  45. if (filesize($cachePath) > 0)
  46. {
  47. $cache = @unserialize(fread($fp, filesize($cachePath)));
  48. }
  49. else
  50. {
  51. $cache = null;
  52. }
  53. flock($fp, LOCK_UN);
  54. fclose($fp);
  55. }
  56. else
  57. {
  58. trigger_error("Can not open \"{$cachePath}\" for reading!", E_USER_WARNING);
  59. }
  60. }
  61. else
  62. {
  63. trigger_error("\"{$cachePath}\" is not readable!", E_USER_WARNING);
  64. }
  65. return $cache;
  66. }
  67. public function set($key, $data)
  68. {
  69. $cachePath = $this->_cacheFileName($key);
  70. $fp = fopen($cachePath, 'wb');
  71. if ($fp)
  72. {
  73. if (flock($fp, LOCK_EX))
  74. {
  75. fwrite($fp, serialize($data));
  76. flock($fp, LOCK_UN);
  77. }
  78. else
  79. {
  80. trigger_error("Can not get lock for \"{$cachePath}\"!", E_USER_WARNING);
  81. return false;
  82. }
  83. fclose($fp);
  84. chmod($cachePath, 0777);
  85. }
  86. else
  87. {
  88. trigger_error("Can not open \"{$cachePath}\" for writing!", E_USER_WARNING);
  89. return false;
  90. }
  91. return true;
  92. }
  93. public function clear($key)
  94. {
  95. $cachePath = $this->_cacheFileName($key);
  96. if (file_exists($cachePath))
  97. {
  98. if (unlink($cachePath))
  99. {
  100. return true;
  101. }
  102. else
  103. {
  104. trigger_error("Can not delete \"{$cachePath}\" cache file!", E_USER_NOTICE);
  105. return false;
  106. }
  107. }
  108. else
  109. {
  110. trigger_error("Can not locate \"{$cachePath}\" cache file!", E_USER_NOTICE);
  111. }
  112. return false;
  113. }
  114. }