From 4444985e8f99ed0892bd288cbf7d819d1aba55dc Mon Sep 17 00:00:00 2001 From: Tim Groeneveld Date: Mon, 30 Nov 2015 12:49:16 +1100 Subject: [PATCH 1/2] Fix code so it follows the PSR-2 rules. --- cache.class.php | 627 ++++++++++++++++++++++++++---------------------- 1 file changed, 336 insertions(+), 291 deletions(-) diff --git a/cache.class.php b/cache.class.php index 33c7c23..77c02b2 100644 --- a/cache.class.php +++ b/cache.class.php @@ -2,312 +2,357 @@ /** * Simple Cache class - * API Documentation: https://github.com/cosenary/Simple-PHP-Cache - * - * @author Christian Metz - * @since 22.12.2011 + * API Documentation: https://github.com/cosenary/Simple-PHP-Cache. + * + * @author Christian Metz + * + * @since 22.12.2011 + * * @copyright Christian Metz - MetzWeb Networks - * @version 1.6 - * @license BSD http://www.opensource.org/licenses/bsd-license.php + * + * @version 1.6 + * + * @license BSD http://www.opensource.org/licenses/bsd-license.php */ +class Cache +{ + /** + * The path to the cache file folder. + * + * @var string + */ + private $_cachepath = 'cache/'; -class Cache { - - /** - * The path to the cache file folder - * - * @var string - */ - private $_cachepath = 'cache/'; - - /** - * The name of the default cache file - * - * @var string - */ - private $_cachename = 'default'; - - /** - * The cache file extension - * - * @var string - */ - private $_extension = '.cache'; - - /** - * Default constructor - * - * @param string|array [optional] $config - * @return void - */ - public function __construct($config = null) { - if (true === isset($config)) { - if (is_string($config)) { - $this->setCache($config); - } else if (is_array($config)) { - $this->setCache($config['name']); - $this->setCachePath($config['path']); - $this->setExtension($config['extension']); - } + /** + * The name of the default cache file. + * + * @var string + */ + private $_cachename = 'default'; + + /** + * The cache file extension. + * + * @var string + */ + private $_extension = '.cache'; + + /** + * Default constructor. + * + * @param string|array [optional] $config + */ + public function __construct($config = null) + { + if (true === isset($config)) { + if (is_string($config)) { + $this->setCache($config); + } elseif (is_array($config)) { + $this->setCache($config['name']); + $this->setCachePath($config['path']); + $this->setExtension($config['extension']); + } + } } - } - - /** - * Check whether data accociated with a key - * - * @param string $key - * @return boolean - */ - public function isCached($key) { - if (false != $this->_loadCache()) { - $cachedData = $this->_loadCache(); - return isset($cachedData[$key]['data']); + + /** + * Check whether data accociated with a key. + * + * @param string $key + * + * @return bool + */ + public function isCached($key) + { + if (false != $this->_loadCache()) { + $cachedData = $this->_loadCache(); + + return isset($cachedData[$key]['data']); + } } - } - - /** - * Store data in the cache - * - * @param string $key - * @param mixed $data - * @param integer [optional] $expiration - * @return object - */ - public function store($key, $data, $expiration = 0) { - $storeData = array( - 'time' => time(), - 'expire' => $expiration, - 'data' => serialize($data) - ); - $dataArray = $this->_loadCache(); - if (true === is_array($dataArray)) { - $dataArray[$key] = $storeData; - } else { - $dataArray = array($key => $storeData); + + /** + * Store data in the cache. + * + * @param string $key + * @param mixed $data + * @param int [optional] $expiration + * + * @return object + */ + public function store($key, $data, $expiration = 0) + { + $storeData = array( + 'time' => time(), + 'expire' => $expiration, + 'data' => serialize($data), + ); + $dataArray = $this->_loadCache(); + if (true === is_array($dataArray)) { + $dataArray[$key] = $storeData; + } else { + $dataArray = array($key => $storeData); + } + $cacheData = json_encode($dataArray); + file_put_contents($this->getCacheDir(), $cacheData); + + return $this; } - $cacheData = json_encode($dataArray); - file_put_contents($this->getCacheDir(), $cacheData); - return $this; - } - - /** - * Retrieve cached data by its key - * - * @param string $key - * @param boolean [optional] $timestamp - * @return string - */ - public function retrieve($key, $timestamp = false) { - $cachedData = $this->_loadCache(); - (false === $timestamp) ? $type = 'data' : $type = 'time'; - if (!isset($cachedData[$key][$type])) return null; - return unserialize($cachedData[$key][$type]); - } - - /** - * Retrieve all cached data - * - * @param boolean [optional] $meta - * @return array - */ - public function retrieveAll($meta = false) { - if ($meta === false) { - $results = array(); - $cachedData = $this->_loadCache(); - if ($cachedData) { - foreach ($cachedData as $k => $v) { - $results[$k] = unserialize($v['data']); + + /** + * Retrieve cached data by its key. + * + * @param string $key + * @param bool [optional] $timestamp + * + * @return string + */ + public function retrieve($key, $timestamp = false) + { + $cachedData = $this->_loadCache(); + (false === $timestamp) ? $type = 'data' : $type = 'time'; + if (!isset($cachedData[$key][$type])) { + return; } - } - return $results; - } else { - return $this->_loadCache(); + + return unserialize($cachedData[$key][$type]); } - } - - /** - * Erase cached entry by its key - * - * @param string $key - * @return object - */ - public function erase($key) { - $cacheData = $this->_loadCache(); - if (true === is_array($cacheData)) { - if (true === isset($cacheData[$key])) { - unset($cacheData[$key]); - $cacheData = json_encode($cacheData); - file_put_contents($this->getCacheDir(), $cacheData); - } else { - throw new Exception("Error: erase() - Key '{$key}' not found."); - } + + /** + * Retrieve all cached data. + * + * @param bool [optional] $meta + * + * @return array + */ + public function retrieveAll($meta = false) + { + if ($meta === false) { + $results = array(); + $cachedData = $this->_loadCache(); + if ($cachedData) { + foreach ($cachedData as $k => $v) { + $results[$k] = unserialize($v['data']); + } + } + + return $results; + } else { + return $this->_loadCache(); + } } - return $this; - } - - /** - * Erase all expired entries - * - * @return integer - */ - public function eraseExpired() { - $cacheData = $this->_loadCache(); - if (true === is_array($cacheData)) { - $counter = 0; - foreach ($cacheData as $key => $entry) { - if (true === $this->_checkExpired($entry['time'], $entry['expire'])) { - unset($cacheData[$key]); - $counter++; + + /** + * Erase cached entry by its key. + * + * @param string $key + * + * @return object + */ + public function erase($key) + { + $cacheData = $this->_loadCache(); + if (true === is_array($cacheData)) { + if (true === isset($cacheData[$key])) { + unset($cacheData[$key]); + $cacheData = json_encode($cacheData); + file_put_contents($this->getCacheDir(), $cacheData); + } else { + throw new Exception("Error: erase() - Key '{$key}' not found."); + } } - } - if ($counter > 0) { - $cacheData = json_encode($cacheData); - file_put_contents($this->getCacheDir(), $cacheData); - } - return $counter; + + return $this; + } + + /** + * Erase all expired entries. + * + * @return int + */ + public function eraseExpired() + { + $cacheData = $this->_loadCache(); + if (true === is_array($cacheData)) { + $counter = 0; + foreach ($cacheData as $key => $entry) { + if (true === $this->_checkExpired($entry['time'], $entry['expire'])) { + unset($cacheData[$key]); + ++$counter; + } + } + if ($counter > 0) { + $cacheData = json_encode($cacheData); + file_put_contents($this->getCacheDir(), $cacheData); + } + + return $counter; + } + } + + /** + * Erase all cached entries. + * + * @return object + */ + public function eraseAll() + { + $cacheDir = $this->getCacheDir(); + if (true === file_exists($cacheDir)) { + $cacheFile = fopen($cacheDir, 'w'); + fclose($cacheFile); + } + + return $this; } - } - - /** - * Erase all cached entries - * - * @return object - */ - public function eraseAll() { - $cacheDir = $this->getCacheDir(); - if (true === file_exists($cacheDir)) { - $cacheFile = fopen($cacheDir, 'w'); - fclose($cacheFile); + + /** + * Load appointed cache. + * + * @return mixed + */ + private function _loadCache() + { + if (true === file_exists($this->getCacheDir())) { + $file = file_get_contents($this->getCacheDir()); + + return json_decode($file, true); + } else { + return false; + } } - return $this; - } - - /** - * Load appointed cache - * - * @return mixed - */ - private function _loadCache() { - if (true === file_exists($this->getCacheDir())) { - $file = file_get_contents($this->getCacheDir()); - return json_decode($file, true); - } else { - return false; + + /** + * Get the cache directory path. + * + * @return string + */ + public function getCacheDir() + { + if (true === $this->_checkCacheDir()) { + $filename = $this->getCache(); + $filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower($filename)); + + return $this->getCachePath().$this->_getHash($filename).$this->getExtension(); + } } - } - - /** - * Get the cache directory path - * - * @return string - */ - public function getCacheDir() { - if (true === $this->_checkCacheDir()) { - $filename = $this->getCache(); - $filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower($filename)); - return $this->getCachePath() . $this->_getHash($filename) . $this->getExtension(); + + /** + * Get the filename hash. + * + * @return string + */ + private function _getHash($filename) + { + return sha1($filename); } - } - - /** - * Get the filename hash - * - * @return string - */ - private function _getHash($filename) { - return sha1($filename); - } - - /** - * Check whether a timestamp is still in the duration - * - * @param integer $timestamp - * @param integer $expiration - * @return boolean - */ - private function _checkExpired($timestamp, $expiration) { - $result = false; - if ($expiration !== 0) { - $timeDiff = time() - $timestamp; - ($timeDiff > $expiration) ? $result = true : $result = false; + + /** + * Check whether a timestamp is still in the duration. + * + * @param int $timestamp + * @param int $expiration + * + * @return bool + */ + private function _checkExpired($timestamp, $expiration) + { + $result = false; + if ($expiration !== 0) { + $timeDiff = time() - $timestamp; + ($timeDiff > $expiration) ? $result = true : $result = false; + } + + return $result; } - return $result; - } - - /** - * Check if a writable cache directory exists and if not create a new one - * - * @return boolean - */ - private function _checkCacheDir() { - if (!is_dir($this->getCachePath()) && !mkdir($this->getCachePath(), 0775, true)) { - throw new Exception('Unable to create cache directory ' . $this->getCachePath()); - } elseif (!is_readable($this->getCachePath()) || !is_writable($this->getCachePath())) { - if (!chmod($this->getCachePath(), 0775)) { - throw new Exception($this->getCachePath() . ' must be readable and writeable'); - } + + /** + * Check if a writable cache directory exists and if not create a new one. + * + * @throws Exception when cache directory can not be created + * + * @return bool + */ + private function _checkCacheDir() + { + if (!is_dir($this->getCachePath()) && !mkdir($this->getCachePath(), 0775, true)) { + throw new Exception('Unable to create cache directory '.$this->getCachePath()); + } elseif (!is_readable($this->getCachePath()) || !is_writable($this->getCachePath())) { + if (!chmod($this->getCachePath(), 0775)) { + throw new Exception($this->getCachePath().' must be readable and writeable'); + } + } + + return true; } - return true; - } - - /** - * Cache path Setter - * - * @param string $path - * @return object - */ - public function setCachePath($path) { - $this->_cachepath = $path; - return $this; - } - - /** - * Cache path Getter - * - * @return string - */ - public function getCachePath() { - return $this->_cachepath; - } - - /** - * Cache name Setter - * - * @param string $name - * @return object - */ - public function setCache($name) { - $this->_cachename = $name; - return $this; - } - - /** - * Cache name Getter - * - * @return void - */ - public function getCache() { - return $this->_cachename; - } - - /** - * Cache file extension Setter - * - * @param string $ext - * @return object - */ - public function setExtension($ext) { - $this->_extension = $ext; - return $this; - } - - /** - * Cache file extension Getter - * - * @return string - */ - public function getExtension() { - return $this->_extension; - } + /** + * Cache path Setter. + * + * @param string $path + * + * @return object + */ + public function setCachePath($path) + { + $this->_cachepath = $path; + + return $this; + } + + /** + * Cache path Getter. + * + * @return string + */ + public function getCachePath() + { + return $this->_cachepath; + } + + /** + * Cache name Setter. + * + * @param string $name + * + * @return object + */ + public function setCache($name) + { + $this->_cachename = $name; + + return $this; + } + + /** + * Cache name Getter. + */ + public function getCache() + { + return $this->_cachename; + } + + /** + * Cache file extension Setter. + * + * @param string $ext + * + * @return object + */ + public function setExtension($ext) + { + $this->_extension = $ext; + + return $this; + } + + /** + * Cache file extension Getter. + * + * @return string + */ + public function getExtension() + { + return $this->_extension; + } } From ba7d29fad4378d05e4297b8741c58e8c9b5b3597 Mon Sep 17 00:00:00 2001 From: Tim Groeneveld Date: Wed, 30 Dec 2015 10:01:06 +1000 Subject: [PATCH 2/2] Fix & Merge #1, adding the option to autoexpire cache items --- README.markdown | 4 ++- cache.class.php | 65 ++++++++++++++++++++++++++++++++++++++++--------- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/README.markdown b/README.markdown index ebc9320..7368972 100644 --- a/README.markdown +++ b/README.markdown @@ -141,7 +141,7 @@ This allows you retrieve all the cached data at once. You get the meta data by s ### Erase data ### -For erasing cached data are these three methods available: +For erasing cached data are these four methods available: - `erase($key)` Erases a single entry by its key. - `eraseAll()` Erases all entries from the Cache file. @@ -154,6 +154,8 @@ For erasing cached data are these three methods available: ?> ``` +- `autoEraseExpired(<$flag>)` Erases items automatically when calling `isCached()`, `retreive()`, and `retreiveAll()` + ### Check cached data ### `isCached($key)` diff --git a/cache.class.php b/cache.class.php index 77c02b2..1c8e284 100644 --- a/cache.class.php +++ b/cache.class.php @@ -37,6 +37,13 @@ class Cache */ private $_extension = '.cache'; + /** + * Determines if expired items are auto erased. + * + * @var bool + */ + private $_autoEraseExpired = false; + /** * Default constructor. * @@ -44,7 +51,7 @@ class Cache */ public function __construct($config = null) { - if (true === isset($config)) { + if (isset($config) === true) { if (is_string($config)) { $this->setCache($config); } elseif (is_array($config)) { @@ -64,7 +71,11 @@ public function __construct($config = null) */ public function isCached($key) { - if (false != $this->_loadCache()) { + if ($this->_autoEraseExpired === true) { + $this->eraseExpired(); + } + + if ($this->_loadCache() != false) { $cachedData = $this->_loadCache(); return isset($cachedData[$key]['data']); @@ -87,12 +98,15 @@ public function store($key, $data, $expiration = 0) 'expire' => $expiration, 'data' => serialize($data), ); + $dataArray = $this->_loadCache(); - if (true === is_array($dataArray)) { + + if (is_array($dataArray) === true) { $dataArray[$key] = $storeData; } else { $dataArray = array($key => $storeData); } + $cacheData = json_encode($dataArray); file_put_contents($this->getCacheDir(), $cacheData); @@ -109,8 +123,13 @@ public function store($key, $data, $expiration = 0) */ public function retrieve($key, $timestamp = false) { + if ($this->_autoEraseExpired === true) { + $this->eraseExpired(); + } + $cachedData = $this->_loadCache(); - (false === $timestamp) ? $type = 'data' : $type = 'time'; + + ($timestamp === false) ? $type = 'data' : $type = 'time'; if (!isset($cachedData[$key][$type])) { return; } @@ -127,6 +146,10 @@ public function retrieve($key, $timestamp = false) */ public function retrieveAll($meta = false) { + if ($this->_autoEraseExpired === true) { + $this->eraseExpired(); + } + if ($meta === false) { $results = array(); $cachedData = $this->_loadCache(); @@ -147,13 +170,16 @@ public function retrieveAll($meta = false) * * @param string $key * + * @throws Exception + * * @return object */ public function erase($key) { $cacheData = $this->_loadCache(); - if (true === is_array($cacheData)) { - if (true === isset($cacheData[$key])) { + + if (is_array($cacheData) === true) { + if (isset($cacheData[$key]) === true) { unset($cacheData[$key]); $cacheData = json_encode($cacheData); file_put_contents($this->getCacheDir(), $cacheData); @@ -173,14 +199,16 @@ public function erase($key) public function eraseExpired() { $cacheData = $this->_loadCache(); - if (true === is_array($cacheData)) { + if (is_array($cacheData) === true) { $counter = 0; + foreach ($cacheData as $key => $entry) { - if (true === $this->_checkExpired($entry['time'], $entry['expire'])) { + if ($this->_checkExpired($entry['time'], $entry['expire']) === true) { unset($cacheData[$key]); ++$counter; } } + if ($counter > 0) { $cacheData = json_encode($cacheData); file_put_contents($this->getCacheDir(), $cacheData); @@ -198,7 +226,8 @@ public function eraseExpired() public function eraseAll() { $cacheDir = $this->getCacheDir(); - if (true === file_exists($cacheDir)) { + + if (file_exists($cacheDir) === true) { $cacheFile = fopen($cacheDir, 'w'); fclose($cacheFile); } @@ -213,7 +242,7 @@ public function eraseAll() */ private function _loadCache() { - if (true === file_exists($this->getCacheDir())) { + if (file_exists($this->getCacheDir()) === true) { $file = file_get_contents($this->getCacheDir()); return json_decode($file, true); @@ -229,7 +258,7 @@ private function _loadCache() */ public function getCacheDir() { - if (true === $this->_checkCacheDir()) { + if ($this->_checkCacheDir() === true) { $filename = $this->getCache(); $filename = preg_replace('/[^0-9a-z\.\_\-]/i', '', strtolower($filename)); @@ -355,4 +384,18 @@ public function getExtension() { return $this->_extension; } + + /** + * Set auto erase behavior. + * + * @param bool $flag should we automatically expire old cached items? + * + * @return bool + */ + public function autoEraseExpired($flag = true) + { + $this->_autoEraseExpired = $flag; + + return $flag; + } }