5 * Definition of Drush\Cache\FileCache.
11 * Default cache implementation.
13 * This cache implementation uses plain text files
14 * containing serialized php to store cached data. Each cache bin corresponds
15 * to a directory by the same name.
17 class FileCache implements CacheInterface {
18 const EXTENSION = '.cache';
21 function __construct($bin) {
23 $this->directory = $this->cacheDirectory();
27 * Returns the cache directory for the given bin.
31 function cacheDirectory($bin = NULL) {
32 $bin = $bin ? $bin : $this->bin;
33 return drush_directory_cache($bin);
38 $cache = $this->getMultiple($cids);
42 function getMultiple(&$cids) {
45 foreach ($cids as $cid) {
46 $filename = $this->getFilePath($cid);
47 if (!file_exists($filename)) throw new \Exception;
49 $item = $this->readFile($filename);
54 $cids = array_diff($cids, array_keys($cache));
57 catch (\Exception $e) {
63 * Returns the contents of the given filename unserialized.
65 * @param string $filename
66 * Absolute path to filename to read contents from.
68 function readFile($filename) {
69 $item = file_get_contents($filename);
70 return $item ? unserialize($item) : FALSE;
73 function set($cid, $data, $expire = DRUSH_CACHE_PERMANENT) {
76 $cache = new \stdClass;
78 $cache->data = is_object($data) ? clone $data : $data;
79 $cache->created = $created;
80 if ($expire == DRUSH_CACHE_TEMPORARY) {
81 $cache->expire = $created + 2591999;
83 // Expire time is in seconds if less than 30 days, otherwise is a timestamp.
84 elseif ($expire != DRUSH_CACHE_PERMANENT && $expire < 2592000) {
85 $cache->expire = $created + $expire;
88 $cache->expire = $expire;
91 // Ensure the cache directory still exists, in case a backend process
92 // cleared the cache after the cache was initialized.
93 drush_mkdir($this->directory);
95 $filename = $this->getFilePath($cid);
96 return $this->writeFile($filename, $cache);
100 * Serializes data and write it to the given filename.
102 * @param string $filename
103 * Absolute path to filename to write cache data.
105 * Cache data to serialize and write to $filename.
107 function writeFile($filename, $cache) {
108 return file_put_contents($filename, serialize($cache));
111 function clear($cid = NULL, $wildcard = FALSE) {
112 $bin_dir = $this->cacheDirectory();
115 drush_delete_dir($bin_dir, TRUE);
120 drush_delete_dir($bin_dir, TRUE);
123 $matches = drush_scan_directory($bin_dir, "/^$cid/", array('.', '..'));
124 $files = $files + array_keys($matches);
128 $files[] = $this->getFilePath($cid);
131 foreach ($files as $f) {
132 if (file_exists($f)) {
140 $files = drush_scan_directory($this->directory, "//", array('.', '..'));
141 return empty($files);
145 * Converts a cache id to a full path.
148 * The cache ID of the data to retrieve.
151 * The full path to the cache file.
153 protected function getFilePath($cid) {
154 return $this->directory . '/' . str_replace(array(':', '\\', '/'), '.', $cid) . self::EXTENSION;