4 * This file is part of Twig.
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
13 * Implements a cache on the filesystem.
15 * @author Andrew Tch <andrew@noop.lv>
17 class Twig_Cache_Filesystem implements Twig_CacheInterface
19 const FORCE_BYTECODE_INVALIDATION = 1;
25 * @param $directory string The root cache directory
26 * @param $options int A set of options
28 public function __construct($directory, $options = 0)
30 $this->directory = rtrim($directory, '\/').'/';
31 $this->options = $options;
34 public function generateKey($name, $className)
36 $hash = hash('sha256', $className);
38 return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';
41 public function load($key)
43 if (file_exists($key)) {
48 public function write($key, $content)
52 if (false === @mkdir($dir, 0777, true)) {
53 if (PHP_VERSION_ID >= 50300) {
54 clearstatcache(true, $dir);
57 throw new RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir));
60 } elseif (!is_writable($dir)) {
61 throw new RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir));
64 $tmpFile = tempnam($dir, basename($key));
65 if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {
66 @chmod($key, 0666 & ~umask());
68 if (self::FORCE_BYTECODE_INVALIDATION == ($this->options & self::FORCE_BYTECODE_INVALIDATION)) {
69 // Compile cached file into bytecode cache
70 if (function_exists('opcache_invalidate')) {
71 opcache_invalidate($key, true);
72 } elseif (function_exists('apc_compile_file')) {
73 apc_compile_file($key);
80 throw new RuntimeException(sprintf('Failed to write cache file "%s".', $key));
83 public function getTimestamp($key)
85 if (!file_exists($key)) {
89 return (int) @filemtime($key);
93 class_alias('Twig_Cache_Filesystem', 'Twig\Cache\FilesystemCache', false);