Yaffs site version 1.1
[yaffs-website] / vendor / twig / twig / lib / Twig / Cache / Filesystem.php
1 <?php
2
3 /*
4  * This file is part of Twig.
5  *
6  * (c) Fabien Potencier
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 /**
13  * Implements a cache on the filesystem.
14  *
15  * @author Andrew Tch <andrew@noop.lv>
16  */
17 class Twig_Cache_Filesystem implements Twig_CacheInterface
18 {
19     const FORCE_BYTECODE_INVALIDATION = 1;
20
21     private $directory;
22     private $options;
23
24     /**
25      * @param $directory string The root cache directory
26      * @param $options   int    A set of options
27      */
28     public function __construct($directory, $options = 0)
29     {
30         $this->directory = rtrim($directory, '\/').'/';
31         $this->options = $options;
32     }
33
34     public function generateKey($name, $className)
35     {
36         $hash = hash('sha256', $className);
37
38         return $this->directory.$hash[0].$hash[1].'/'.$hash.'.php';
39     }
40
41     public function load($key)
42     {
43         if (file_exists($key)) {
44             @include_once $key;
45         }
46     }
47
48     public function write($key, $content)
49     {
50         $dir = dirname($key);
51         if (!is_dir($dir)) {
52             if (false === @mkdir($dir, 0777, true)) {
53                 if (PHP_VERSION_ID >= 50300) {
54                     clearstatcache(true, $dir);
55                 }
56                 if (!is_dir($dir)) {
57                     throw new RuntimeException(sprintf('Unable to create the cache directory (%s).', $dir));
58                 }
59             }
60         } elseif (!is_writable($dir)) {
61             throw new RuntimeException(sprintf('Unable to write in the cache directory (%s).', $dir));
62         }
63
64         $tmpFile = tempnam($dir, basename($key));
65         if (false !== @file_put_contents($tmpFile, $content) && @rename($tmpFile, $key)) {
66             @chmod($key, 0666 & ~umask());
67
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);
74                 }
75             }
76
77             return;
78         }
79
80         throw new RuntimeException(sprintf('Failed to write cache file "%s".', $key));
81     }
82
83     public function getTimestamp($key)
84     {
85         if (!file_exists($key)) {
86             return 0;
87         }
88
89         return (int) @filemtime($key);
90     }
91 }
92
93 class_alias('Twig_Cache_Filesystem', 'Twig\Cache\FilesystemCache', false);