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