1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19:
20: class NFileTemplate extends NTemplate implements IFileTemplate
21: {
22:
23: public static $cacheExpire = NULL;
24:
25:
26: private static $cacheStorage;
27:
28:
29: private $file;
30:
31:
32:
33: 34: 35: 36:
37: public function __construct($file = NULL)
38: {
39: if ($file !== NULL) {
40: $this->setFile($file);
41: }
42: }
43:
44:
45:
46: 47: 48: 49: 50:
51: public function setFile($file)
52: {
53: if (!is_file($file)) {
54: throw new FileNotFoundException("Missing template file '$file'.");
55: }
56: $this->file = $file;
57: return $this;
58: }
59:
60:
61:
62: 63: 64: 65:
66: public function getFile()
67: {
68: return $this->file;
69: }
70:
71:
72:
73:
74:
75:
76:
77: 78: 79: 80:
81: public function render()
82: {
83: if ($this->file == NULL) { 84: throw new InvalidStateException("Template file name was not specified.");
85: }
86:
87: $this->__set('template', $this);
88:
89: $shortName = str_replace(dirname(dirname($this->file)), '', $this->file);
90:
91: $cache = new NCache($this->getCacheStorage(), 'Nette.FileTemplate');
92: $key = trim(strtr($shortName, '\\/@', '.._'), '.') . '-' . md5($this->file);
93: $cached = $content = $cache[$key];
94:
95: if ($content === NULL) {
96: if (!$this->getFilters()) {
97: $this->onPrepareFilters($this);
98: }
99:
100: if (!$this->getFilters()) {
101: NLimitedScope::load($this->file, $this->getParams());
102: return;
103: }
104:
105: $content = $this->compile(file_get_contents($this->file), "file \xE2\x80\xA6$shortName");
106: $cache->save(
107: $key,
108: $content,
109: array(
110: NCache::FILES => $this->file,
111: NCache::EXPIRE => self::$cacheExpire,
112: NCache::CONSTS => 'NFramework::REVISION',
113: )
114: );
115: $cache->release();
116: $cached = $cache[$key];
117: }
118:
119: if ($cached !== NULL && self::$cacheStorage instanceof NTemplateCacheStorage) {
120: NLimitedScope::load($cached['file'], $this->getParams());
121: fclose($cached['handle']);
122:
123: } else {
124: NLimitedScope::evaluate($content, $this->getParams());
125: }
126: }
127:
128:
129:
130:
131:
132:
133:
134: 135: 136: 137: 138:
139: public static function setCacheStorage(ICacheStorage $storage)
140: {
141: self::$cacheStorage = $storage;
142: }
143:
144:
145:
146: 147: 148:
149: public static function getCacheStorage()
150: {
151: if (self::$cacheStorage === NULL) {
152: $dir = NEnvironment::getVariable('tempDir') . '/cache';
153: umask(0000);
154: @mkdir($dir, 0755); 155: self::$cacheStorage = new NTemplateCacheStorage($dir);
156: }
157: return self::$cacheStorage;
158: }
159:
160: }
161: