1: <?php
2:
3: /**
4: * This file is part of the Nette Framework (https://nette.org)
5: * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6: */
7:
8: namespace Nette\Templating;
9:
10: use Nette;
11: use Nette\Caching;
12:
13:
14: /**
15: * Template stored in file.
16: *
17: * @author David Grudl
18: */
19: class FileTemplate extends Template implements IFileTemplate
20: {
21: /** @var string */
22: private $file;
23:
24:
25: /**
26: * Constructor.
27: * @param string template file path
28: */
29: public function __construct($file = NULL)
30: {
31: if ($file !== NULL) {
32: $this->setFile($file);
33: }
34: }
35:
36:
37: /**
38: * Sets the path to the template file.
39: * @param string template file path
40: * @return self
41: */
42: public function setFile($file)
43: {
44: $this->file = realpath($file);
45: if (!$this->file) {
46: throw new Nette\FileNotFoundException("Missing template file '$file'.");
47: }
48: return $this;
49: }
50:
51:
52: /**
53: * Returns the path to the template file.
54: * @return string template file path
55: */
56: public function getFile()
57: {
58: return $this->file;
59: }
60:
61:
62: /**
63: * Returns template source code.
64: * @return string
65: */
66: public function getSource()
67: {
68: return file_get_contents($this->file);
69: }
70:
71:
72: /********************* rendering ****************d*g**/
73:
74:
75: /**
76: * Renders template to output.
77: * @return void
78: */
79: public function render()
80: {
81: if ($this->file == NULL) { // intentionally ==
82: throw new Nette\InvalidStateException("Template file name was not specified.");
83: }
84:
85: $cache = new Caching\Cache($storage = $this->getCacheStorage(), 'Nette.FileTemplate');
86: if ($storage instanceof Caching\Storages\PhpFileStorage) {
87: $storage->hint = str_replace(dirname(dirname($this->file)), '', $this->file);
88: }
89: $cached = $compiled = $cache->load($this->file);
90:
91: if ($compiled === NULL) {
92: try {
93: $compiled = "<?php\n\n// source file: $this->file\n\n?>" . $this->compile();
94:
95: } catch (FilterException $e) {
96: $e->setSourceFile($this->file);
97: throw $e;
98: }
99:
100: $cache->save($this->file, $compiled, array(
101: Caching\Cache::FILES => $this->file,
102: Caching\Cache::CONSTS => 'Nette\Framework::REVISION',
103: ));
104: $cached = $cache->load($this->file);
105: }
106:
107: if ($cached !== NULL && $storage instanceof Caching\Storages\PhpFileStorage) {
108: Nette\Utils\LimitedScope::load($cached['file'], $this->getParameters());
109: } else {
110: Nette\Utils\LimitedScope::evaluate($compiled, $this->getParameters());
111: }
112: }
113:
114: }
115: