template.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. <?php
  2. /**
  3. * HTML template rendering functions.
  4. *
  5. * @author Taddeus Kroes
  6. * @date 14-07-2012
  7. */
  8. namespace WebBasics;
  9. require_once 'node.php';
  10. /**
  11. * A Template object represents a template file.
  12. *
  13. * A template file contains 'blocks' that can be rendered zero or more times.
  14. * Each block has a set of properties that can be accessed using curly
  15. * brackets ('{' and '}'). Curly brackets may contain macro's to minimize
  16. * common view logic in controllers.
  17. *
  18. * Example template 'page.tpl':
  19. * <code>
  20. * &lt;html&gt;
  21. * &lt;head&gt;
  22. * &lt;title&gt;{page_title}&lt;/title&gt;
  23. * &lt;/head&gt;
  24. * &lt;body&gt;
  25. * &lt;h1&gt;{page_title}&lt;/h1&gt;
  26. * &lt;div id="content"&gt;{page_content}&lt;/div&gt;
  27. * &lt;div id="ads"&gt;
  28. * {block:ad}
  29. * &lt;div class="ad"&gt;{ad_content}&lt;/div&gt;
  30. * {end}
  31. * &lt;/div&gt;
  32. * &lt;/body&gt;
  33. * &lt;/html&gt;
  34. * </code>
  35. * And the corresponding PHP code:
  36. * <code>
  37. * $tpl = new Template('page');
  38. * $tpl->set(array(
  39. * 'page_title' => 'Some title',
  40. * 'page_content' => 'Lorem ipsum ...'
  41. * ));
  42. *
  43. * foreach( array('Some ad', 'Another ad', 'More ads') as $ad )
  44. * $tpl->add('ad')->set('ad_content', $ad);
  45. *
  46. * echo $tpl->render();
  47. * </code>
  48. * The output will be:
  49. * <code>
  50. * &lt;html&gt;
  51. * &lt;head&gt;
  52. * &lt;title&gt;Some title&lt;/title&gt;
  53. * &lt;/head&gt;
  54. * &lt;body&gt;
  55. * &lt;h1&gt;Some title&lt;/h1&gt;
  56. * &lt;div id="content"&gt;Some content&lt;/div&gt;
  57. * &lt;div id="ads"&gt;
  58. * &lt;div class="ad"&gt;Some ad&lt;/div&gt;
  59. * &lt;div class="ad"&gt;Another ad&lt;/div&gt;
  60. * &lt;div class="ad"&gt;More ads&lt;/div&gt;
  61. * &lt;/div&gt;
  62. * &lt;/body&gt;
  63. * &lt;/html&gt;
  64. * </code>
  65. *
  66. * @package WebBasics
  67. */
  68. class Template extends Node {
  69. /**
  70. * Default extension of template files.
  71. *
  72. * @var array
  73. */
  74. const DEFAULT_EXTENSION = '.tpl';
  75. /**
  76. * Root directories from which template files are included.
  77. *
  78. * @var array
  79. */
  80. private static $include_path = array();
  81. /**
  82. * The path the template was found in.
  83. *
  84. * @var string
  85. */
  86. private $path;
  87. /**
  88. * The content of the template file.
  89. *
  90. * @var string
  91. */
  92. private $file_content;
  93. /**
  94. * The block structure of the template file.
  95. *
  96. * @var Node
  97. */
  98. private $root_block;
  99. /**
  100. * Create a new Template object, representing a template file.
  101. *
  102. * Template files are assumed to have the .tpl extension. If no extension
  103. * is specified, '.tpl' is appended to the filename.
  104. *
  105. * @param string $filename The path to the template file from one of the root directories.
  106. */
  107. function __construct($filename) {
  108. // Add default extension if none is found
  109. strpos($filename, '.') === false && $filename .= self::DEFAULT_EXTENSION;
  110. $look_in = count(self::$include_path) ? self::$include_path : array('.');
  111. $found = false;
  112. foreach( $look_in as $root ) {
  113. $path = $root.$filename;
  114. if( file_exists($path) ) {
  115. $this->path = $path;
  116. $this->file_content = file_get_contents($path);
  117. $found = true;
  118. break;
  119. }
  120. }
  121. if( !$found ) {
  122. throw new \RuntimeException(
  123. sprintf("Could not find template file \"%s\", looked in folders:\n%s",
  124. $filename, implode("\n", $look_in))
  125. );
  126. }
  127. $this->parse_blocks();
  128. }
  129. /**
  130. * Get the path to the template file (including one of the include paths).
  131. *
  132. * @return string The path to the template file.
  133. */
  134. function get_path() {
  135. return $this->path;
  136. }
  137. /**
  138. * Parse the content of the template file into a tree structure of blocks
  139. * and variables.
  140. *
  141. * @throws ParseError If an {end} tag is not used properly.
  142. */
  143. private function parse_blocks() {
  144. $current = $root = new Node('block');
  145. $after = $this->file_content;
  146. $line_count = 0;
  147. while( preg_match('/(.*?)\{([^}]+)}(.*)/s', $after, $matches) ) {
  148. list($before, $brackets_content, $after) = array_slice($matches, 1);
  149. $line_count += substr_count($before, "\n");
  150. // Everything before the new block belongs to its parent
  151. $current->add('html')->set('content', $before);
  152. if( $brackets_content == 'end' ) {
  153. // {end} encountered, go one level up in the tree
  154. if( $current->is_root() )
  155. throw new ParseError($this, 'unexpected {end}', $line_count + 1);
  156. $current = $current->get_parent();
  157. } elseif( substr($brackets_content, 0, 6) == 'block:' ) {
  158. // {block:...} encountered
  159. $block_name = substr($brackets_content, 6);
  160. // Go one level deeper into the tree
  161. $current = $current->add('block')->set('name', $block_name);
  162. } else {
  163. // Variable or something else
  164. $current->add('variable')->set('content', $brackets_content);
  165. }
  166. }
  167. $line_count += substr_count($after, "\n");
  168. if( $current !== $root )
  169. throw new ParseError($this, 'missing {end}', $line_count + 1);
  170. // Add the last remaining content to the root node
  171. $root->add('html')->set('content', $after);
  172. $this->root_block = $root;
  173. }
  174. /**
  175. * Replace blocks and variables in the template's content.
  176. *
  177. * @return string The template's content, with replaced blocks and variables.
  178. */
  179. function render() {
  180. // Use recursion to parse all blocks from the root level
  181. return self::render_block($this->root_block, $this);
  182. }
  183. /**
  184. * Render a single block, recursively parsing its sub-blocks with a given data scope.
  185. *
  186. * @param Node $block The block to render.
  187. * @param Node $data The data block to search in for the variable values.
  188. * @return string The rendered block.
  189. * @uses replace_variable()
  190. */
  191. private static function render_block(Node $block, Node $data) {
  192. $html = '';
  193. foreach( $block->get_children() as $child ) {
  194. switch( $child->get_name() ) {
  195. case 'html':
  196. $html .= $child->get('content');
  197. break;
  198. case 'block':
  199. $block_name = $child->get('name');
  200. foreach( $data->find($block_name) as $child_data )
  201. $html .= self::render_block($child, $child_data);
  202. break;
  203. case 'variable':
  204. $html .= self::replace_variable($child->get('content'), $data);
  205. }
  206. }
  207. return $html;
  208. }
  209. /**
  210. * Replace a variable name if it exists within a given data scope.
  211. *
  212. * Applies any of the following macro's:
  213. *
  214. * --------
  215. * Variable
  216. * --------
  217. * <code>{var_name[:func1:func2:...]}</code>
  218. * *var_name* can be of the form *foo.bar*. In this case, *foo* is the
  219. * name of an object or associative array variable. *bar* is a property
  220. * name to get of the object, or the associative index to the array.
  221. * *func1*, *func2*, etc. are helper functions that are executed in the
  222. * same order as listed. The retuen value of each helper function replaces
  223. * the previous variable value. *var_name* Can also be the name of a
  224. * defined constant.
  225. *
  226. * ------------
  227. * If-statement
  228. * ------------
  229. * <code>{if:condition:success_variable[:else:failure_variable]}</code>
  230. * *condition* is evaluated to a boolean. If it evaluates to TRUE, the
  231. * value of *success_variable* is used. Otherwise, the value of
  232. * *failure_variable* is used (defaults to an empty string if no
  233. * else-statement is specified).
  234. *
  235. * @param string $variable The variable to replace.
  236. * @param Node $data The data block to search in for a value.
  237. * @return string The variable's value if it exists, the original string
  238. * with curly brackets otherwise.
  239. * @throws \UnexpectedValueException If a helper function is not callable.
  240. */
  241. private static function replace_variable($variable, Node $data) {
  242. // If-(else-)statement
  243. if( preg_match('/^if:([^:]*):(.*?)(?::else:(.*))?$/', $variable, $matches) ) {
  244. $condition = $data->get($matches[1]);
  245. $if = $data->get($matches[2]);
  246. if( $condition )
  247. return $if;
  248. return count($matches) > 3 ? self::replace_variable($matches[3], $data) : '';
  249. }
  250. // Default: variable with optional helper functions
  251. $parts = explode(':', $variable);
  252. $name = $parts[0];
  253. $helper_functions = array_slice($parts, 1);
  254. if( strpos($name, '.') !== false ) {
  255. // Variable of the form 'foo.bar'
  256. list($variable_name, $property) = explode('.', $name, 2);
  257. $object = $data->get($variable_name);
  258. if( is_object($object) && property_exists($object, $property) ) {
  259. // Object property
  260. $value = $object->$property;
  261. } elseif( is_array($object) && isset($object[$property]) ) {
  262. // Associative array index
  263. $value = $object[$property];
  264. }
  265. }
  266. // Default: Simple variable name
  267. if( !isset($value) ) {
  268. $value = $data->get($name);
  269. if( $value === null && defined($name) )
  270. $value = constant($name);
  271. }
  272. // Don't continue if the variable name is not found in the data block
  273. if( $value !== null ) {
  274. // Apply helper functions to the variable's value iteratively
  275. foreach( $helper_functions as $func ) {
  276. if( !is_callable($func) ) {
  277. throw new \UnexpectedValueException(
  278. sprintf('Helper function "%s" is not callable.', $func)
  279. );
  280. }
  281. $value = $func($value);
  282. }
  283. return $value;
  284. }
  285. return '{'.$variable.'}';
  286. }
  287. /**
  288. * Remove all current include paths.
  289. */
  290. static function clear_include_path() {
  291. self::$include_path = array();
  292. }
  293. /**
  294. * Replace all include paths by a single new one.
  295. *
  296. * @param string $path The new path to set as root.
  297. * @uses clear_include_path()
  298. */
  299. static function set_root($path) {
  300. self::clear_include_path();
  301. self::add_root($path);
  302. }
  303. /**
  304. * Add a new include path.
  305. *
  306. * @param string $path The path to add.
  307. * @throws FileNotFoundError If the path does not exist.
  308. */
  309. static function add_root($path) {
  310. if( $path[strlen($path) - 1] != '/' )
  311. $path .= '/';
  312. if( !is_dir($path) )
  313. throw new FileNotFoundError($path, true);
  314. self::$include_path[] = $path;
  315. }
  316. }
  317. /**
  318. * Error, thrown when an error occurs during the parsing of a template file.
  319. *
  320. * @package WebBasics
  321. */
  322. class ParseError extends \RuntimeException {
  323. /**
  324. * Constructor.
  325. *
  326. * Sets an error message with the path to the template file and a line number.
  327. *
  328. * @param Template $tpl The template in which the error occurred.
  329. * @param string $message A message describing the error.
  330. * @param int $line The line number at which the error occurred.
  331. */
  332. function __construct(Template $tpl, $message, $line) {
  333. $this->message = sprintf('Parse error in file %s, line %d: %s',
  334. $tpl->get_path(), $line, $message);
  335. }
  336. }
  337. ?>