/core/classes/framework/cache/engine/file.php
PHP | 139 lines | 107 code | 25 blank | 7 comment | 16 complexity | c533133b55fa5da1490eda0bc3b0a2af MD5 | raw file
- <?php
- class Cache_Engine_File implements Cache_Interface {
-
- private $_cacheDir = null;
-
- /**
- *
- * Creates new FileBasedCache instance
- *
- * @param string $directory
- * @throws Exception
- */
- function __construct($directory = "")
- {
- if (!$directory)
- {
- $directory = Loader::getCacheDirectoryPath();
- }
- else
- {
- $directory = Loader::getDirectPath($directory);
- }
-
- if (!is_dir($directory) || !is_writable($directory))
- {
- throw new Exception("Directory \"{$directory}\" is not writeable or does not exist!");
- }
- else
- {
- $this->_cacheDir = $directory;
- }
- }
-
- private function _cacheFileName($key)
- {
- return $this->_cacheDir . Cfg_App::DS . md5($key);
- }
-
- public function get($key)
- {
- $cachePath = $this->_cacheFileName($key);
-
- $cache = null;
- if (is_readable($cachePath))
- {
- $fp = fopen($cachePath, 'rb');
- if ($fp)
- {
- flock($fp, LOCK_SH);
- $cache = '';
- if (filesize($cachePath) > 0)
- {
- $cache = @unserialize(fread($fp, filesize($cachePath)));
- }
- else
- {
- $cache = null;
- }
- flock($fp, LOCK_UN);
- fclose($fp);
- }
- else
- {
- trigger_error("Can not open \"{$cachePath}\" for reading!", E_USER_WARNING);
- }
- }
- else
- {
- trigger_error("\"{$cachePath}\" is not readable!", E_USER_WARNING);
- }
- return $cache;
- }
-
- public function set($key, $data)
- {
- $cachePath = $this->_cacheFileName($key);
- $fp = fopen($cachePath, 'wb');
-
- if ($fp)
- {
- if (flock($fp, LOCK_EX))
- {
- fwrite($fp, serialize($data));
- flock($fp, LOCK_UN);
- }
- else
- {
- trigger_error("Can not get lock for \"{$cachePath}\"!", E_USER_WARNING);
-
- return false;
- }
-
- fclose($fp);
-
- chmod($cachePath, 0777);
- }
- else
- {
- trigger_error("Can not open \"{$cachePath}\" for writing!", E_USER_WARNING);
-
- return false;
- }
-
- return true;
- }
-
- public function clear($key)
- {
- $cachePath = $this->_cacheFileName($key);
-
- if (file_exists($cachePath))
- {
- if (unlink($cachePath))
- {
- return true;
- }
- else
- {
- trigger_error("Can not delete \"{$cachePath}\" cache file!", E_USER_NOTICE);
-
- return false;
- }
- }
- else
- {
- trigger_error("Can not locate \"{$cachePath}\" cache file!", E_USER_NOTICE);
- }
-
- return false;
- }
- }