aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRomain d'Alverny <rda@mageia.org>2012-06-11 12:15:13 +0000
committerRomain d'Alverny <rda@mageia.org>2012-06-11 12:15:13 +0000
commita8f8f22fb0f291fe76c2248750c81874b7572b9a (patch)
tree260dcabe4854ed0298e8b05c22085bcc90a86311
parente721066d6287156f9ea3d49edbaf9899f10500bb (diff)
downloadnav-a8f8f22fb0f291fe76c2248750c81874b7572b9a.tar
nav-a8f8f22fb0f291fe76c2248750c81874b7572b9a.tar.gz
nav-a8f8f22fb0f291fe76c2248750c81874b7572b9a.tar.bz2
nav-a8f8f22fb0f291fe76c2248750c81874b7572b9a.tar.xz
nav-a8f8f22fb0f291fe76c2248750c81874b7572b9a.zip
new NCache class
-rw-r--r--lib.php106
1 files changed, 106 insertions, 0 deletions
diff --git a/lib.php b/lib.php
index 28b72cf..600f97d 100644
--- a/lib.php
+++ b/lib.php
@@ -1,6 +1,112 @@
<?php
// definition
+class NCache
+{
+ function __construct() { }
+
+ /**
+ * Factory.
+ *
+ * @param string $path where cache file store is located, relative to app path.
+ * @param integer $timeout in seconds
+ *
+ * @return NCache
+ */
+ function build($path, $timeout = 3600)
+ {
+ $path = __DIR__ . '/' . $path;
+
+ if (!is_dir($path))
+ return null;
+
+ if ($timeout < 60)
+ $timeout = 60;
+
+ $i = new self;
+ $i->_path = $path;
+ $i->_timeout = $timeout;
+
+ return $i;
+ }
+
+ /**
+ * Get value for $key.
+ *
+ * @param mixed $key
+ *
+ * @return mixed
+ */
+ function get($key = null)
+ {
+ if (is_null($key))
+ return false;
+
+ $filename = $this->_get_filename($key);
+
+ if ($this->_is_valid_file($filename, $this->_timeout)) {
+ return unserialize(file_get_contents($filename));
+ }
+
+ return null;
+ }
+
+ /**
+ * Save $value under $key.
+ *
+ * @param mixed $key
+ * @param mixed $value
+ */
+ function set($key, $value)
+ {
+ if (is_null($key))
+ return false;
+
+ $filename = $this->_get_filename($key);
+ file_put_contents($filename, serialize($value));
+
+ return true;
+ }
+
+ /**
+ * Get cache file from key.
+ *
+ * @param mixed $key
+ *
+ * @return string
+ */
+ private function _get_filename($key)
+ {
+ $key = hash('sha1', serialize($key));
+
+ return $this->_path . '/' . $key . '.cache';
+ }
+
+ /**
+ * Check that the cache file exists and has not expired.
+ *
+ * @param string $filename
+ *
+ * @return boolean
+ */
+ private function _is_valid_file($filename, $timeout)
+ {
+ if (!file_exists($filename)) {
+ //error_log(sprintf('Could not find %s', $filename), 0);
+ return false;
+ }
+
+ if (filemtime($filename) + $timeout < time()) {
+ //error_log(sprintf('%s timestamp expired (timeout was %ds.).', $filename, $timeout));
+ unlink($filename);
+ return false;
+ }
+
+ //error_log(sprintf('Found %s', $filename));
+ return true;
+ }
+}
+
class l10n
{
public static $t;