1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
<?php
/**
* FileSystem Cache Adapter.
*
* @package Silla.IO
* @subpackage Core\Modules\Cache\Adapters
* @author Plamen Nikolov <plamen@athlonsofia.com>
* @copyright Copyright (c) 2015, Silla.io
* @license http://opensource.org/licenses/GPL-3.0 GNU General Public License, version 3.0 (GPLv3)
*/
namespace Core\Modules\Cache\Adapters;
use Core;
use Core\Helpers\File;
/**
* Class FileSystem Adapter for caching data.
*/
class FileSystem implements Core\Modules\Cache\Interfaces\Adapter
{
/**
* Stores value by key.
*
* @param string $key Cache key.
* @param mixed $value Cache value.
* @param integer $expire Expiration time, in seconds(optional).
*
* @access public
* @uses Core\Helpers\File
*
* @return boolean
*/
public function store($key, $value, $expire = 0)
{
if ($expire) {
$expire = time() + $expire;
}
$content = array($expire, $value);
return File::putContents(self::storagePath() . self::generateName($key), serialize($content));
}
/**
* Fetches stored value by key.
*
* @param string $key Cache key.
*
* @access public
*
* @return mixed
*/
public function fetch($key)
{
$file = self::storagePath() . self::generateName($key);
$expire = null;
$value = null;
try {
$content = File::getContents($file);
if ($content) {
list($expire, $value) = unserialize($content);
}
} catch (\Exception $e) {
return null;
}
if ($expire && $expire < time()) {
try {
File::delete($file);
} catch (\Exception $e) {
// Provide comment why we are not processing the catched exception.
}
return null;
}
return $value;
}
/**
* Checks if a key-value pair exists.
*
* @param string $key Cache key.
*
* @return boolean
*/
public function exists($key)
{
$file = self::storagePath() . self::generateName($key);
$file = File::getFullPath($file);
return is_file($file);
}
/**
* Removes a key-value pair.
*
* @param string $key Cache key.
*
* @return boolean
*/
public function remove($key)
{
$file = self::storagePath() . self::generateName($key);
try {
return File::delete($file);
} catch (\Exception $e) {
var_log($e->getMessage());
return false;
}
}
/**
* Generates cache name.
*
* @param string $key Cache key.
*
* @access private
* @static
*
* @return string
*/
private static function generateName($key)
{
return md5($key) . '.tmp';
}
/**
* Generates storage path.
*
* @access private
* @static
*
* @return string
*/
private static function storagePath()
{
return Core\Config()->paths('tmp') . 'cache' . DIRECTORY_SEPARATOR;
}
}