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