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 Template extends BaseTemplate implements IFileTemplate
27: {
28:
29: public static $cacheExpire = NULL;
30:
31:
32: private static $cacheStorage;
33:
34:
35: private $file;
36:
37:
38:
39: 40: 41: 42:
43: public function __construct($file = NULL)
44: {
45: if ($file !== NULL) {
46: $this->setFile($file);
47: }
48: }
49:
50:
51:
52: 53: 54: 55: 56:
57: public function setFile($file)
58: {
59: if (!is_file($file)) {
60: throw new \FileNotFoundException("Missing template file '$file'.");
61: }
62: $this->file = $file;
63: return $this;
64: }
65:
66:
67:
68: 69: 70: 71:
72: public function getFile()
73: {
74: return $this->file;
75: }
76:
77:
78:
79:
80:
81:
82:
83: 84: 85: 86:
87: public function render()
88: {
89: if ($this->file == NULL) {
90: throw new \InvalidStateException("Template file name was not specified.");
91: }
92:
93: $this->__set('template', $this);
94:
95: $cache = new Cache($this->getCacheStorage(), 'Nette.Template');
96: $key = md5($this->file) . '.' . basename($this->file);
97: $cached = $content = $cache[$key];
98:
99: if ($content === NULL) {
100: if (!$this->getFilters()) {
101: $this->onPrepareFilters($this);
102: }
103:
104: if (!$this->getFilters()) {
105: LimitedScope::load($this->file, $this->getParams());
106: return;
107: }
108:
109: try {
110: $shortName = $this->file;
111: $shortName = str_replace(Environment::getVariable('appDir'), "\xE2\x80\xA6", $shortName);
112: } catch (\Exception $foo) {
113: }
114:
115: $content = $this->compile(file_get_contents($this->file), "file $shortName");
116: $cache->save(
117: $key,
118: $content,
119: array(
120: Cache::FILES => $this->file,
121: Cache::EXPIRE => self::$cacheExpire,
122: )
123: );
124: $cache->release();
125: $cached = $cache[$key];
126: }
127:
128: if ($cached !== NULL && self::$cacheStorage instanceof TemplateCacheStorage) {
129: LimitedScope::load($cached['file'], $this->getParams());
130: flock($cached['handle'], LOCK_UN);
131: fclose($cached['handle']);
132:
133: } else {
134: LimitedScope::evaluate($content, $this->getParams());
135: }
136: }
137:
138:
139:
140:
141:
142:
143:
144: 145: 146: 147: 148:
149: public static function setCacheStorage(Nette\Caching\ICacheStorage $storage)
150: {
151: self::$cacheStorage = $storage;
152: }
153:
154:
155:
156: 157: 158:
159: public static function getCacheStorage()
160: {
161: if (self::$cacheStorage === NULL) {
162: self::$cacheStorage = new TemplateCacheStorage(Environment::getVariable('tempDir'));
163: }
164: return self::$cacheStorage;
165: }
166:
167: }
168: