template.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. <?php
  2. /**
  3. * HTML template rendering functions.
  4. *
  5. * @author Taddeus Kroes
  6. * @version 1.0
  7. * @date 14-07-2012
  8. */
  9. namespace WebBasics;
  10. require_once 'node.php';
  11. /**
  12. * A Template object represents a template file.
  13. *
  14. * A template file contains 'blocks' that can be rendered zero or more times.
  15. * Each block has a set of properties that can be accessed using curly
  16. * brackets ('{' and '}'). Curly brackets may contain macro's to minimize
  17. * common view logic in controllers.
  18. *
  19. * Example template 'page.tpl':
  20. * <code>
  21. * &lt;html&gt;
  22. * &lt;head&gt;
  23. * &lt;title&gt;{page_title}&lt;/title&gt;
  24. * &lt;/head&gt;
  25. * &lt;body&gt;
  26. * &lt;h1&gt;{page_title}&lt;/h1&gt;
  27. * &lt;div id="content"&gt;{page_content}&lt;/div&gt;
  28. * &lt;div id="ads"&gt;
  29. * {block:ad}
  30. * &lt;div class="ad"&gt;{ad_content}&lt;/div&gt;
  31. * {end}
  32. * &lt;/div&gt;
  33. * &lt;/body&gt;
  34. * &lt;/html&gt;
  35. * </code>
  36. * And the corresponding PHP code:
  37. * <code>
  38. * $tpl = new Template('page');
  39. * $tpl->set(array(
  40. * 'page_title' => 'Some title',
  41. * 'page_content' => 'Lorem ipsum ...'
  42. * ));
  43. *
  44. * foreach( array('Some ad', 'Another ad', 'More ads') as $ad )
  45. * $tpl->add('ad')->set('ad_content', $ad);
  46. *
  47. * echo $tpl->render();
  48. * </code>
  49. * The output will be:
  50. * <code>
  51. * &lt;html&gt;
  52. * &lt;head&gt;
  53. * &lt;title&gt;Some title&lt;/title&gt;
  54. * &lt;/head&gt;
  55. * &lt;body&gt;
  56. * &lt;h1&gt;Some title&lt;/h1&gt;
  57. * &lt;div id="content"&gt;Some content&lt;/div&gt;
  58. * &lt;div id="ads"&gt;
  59. * &lt;div class="ad"&gt;Some ad&lt;/div&gt;
  60. * &lt;div class="ad"&gt;Another ad&lt;/div&gt;
  61. * &lt;div class="ad"&gt;More ads&lt;/div&gt;
  62. * &lt;/div&gt;
  63. * &lt;/body&gt;
  64. * &lt;/html&gt;
  65. * </code>
  66. *
  67. * @package WebBasics
  68. */
  69. class Template extends Node {
  70. /**
  71. * Default extension of template files.
  72. *
  73. * @var array
  74. */
  75. const DEFAULT_EXTENSION = '.tpl';
  76. /**
  77. * Root directories from which template files are included.
  78. *
  79. * @var array
  80. */
  81. private static $include_path = array();
  82. /**
  83. * The path the template was found in.
  84. *
  85. * @var string
  86. */
  87. private $path;
  88. /**
  89. * The content of the template file.
  90. *
  91. * @var string
  92. */
  93. private $file_content;
  94. /**
  95. * The block structure of the template file.
  96. *
  97. * @var Node
  98. */
  99. private $root_block;
  100. /**
  101. * Create a new Template object, representing a template file.
  102. *
  103. * Template files are assumed to have the .tpl extension. If no extension
  104. * is specified, '.tpl' is appended to the filename.
  105. *
  106. * @param string $filename The path to the template file from one of the root directories.
  107. */
  108. function __construct($filename) {
  109. // Add default extension if none is found
  110. strpos($filename, '.') === false && $filename .= self::DEFAULT_EXTENSION;
  111. $look_in = count(self::$include_path) ? self::$include_path : array('.');
  112. $found = false;
  113. foreach( $look_in as $root ) {
  114. $path = $root.$filename;
  115. if( file_exists($path) ) {
  116. $this->path = $path;
  117. $this->file_content = file_get_contents($path);
  118. $found = true;
  119. break;
  120. }
  121. }
  122. if( !$found ) {
  123. throw new \RuntimeException(
  124. sprintf("Could not find template file \"%s\", looked in folders:\n%s",
  125. $filename, implode("\n", $look_in))
  126. );
  127. }
  128. $this->parse_blocks();
  129. }
  130. /**
  131. * Get the path to the template file (including one of the include paths).
  132. *
  133. * @return string the path to the template file.
  134. */
  135. function get_path() {
  136. return $this->path;
  137. }
  138. /**
  139. * Parse the content of the template file into a tree structure of blocks
  140. * and variables.
  141. */
  142. private function parse_blocks() {
  143. $current = $root = new Node('block');
  144. $after = $this->file_content;
  145. $line_count = 0;
  146. while( preg_match('/(.*?)\{([^}]+)}(.*)/s', $after, $matches) ) {
  147. list($before, $brackets_content, $after) = array_slice($matches, 1);
  148. $line_count += substr_count($before, "\n");
  149. //var_dump(array_slice($matches, 1));
  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.
  224. *
  225. * ------------
  226. * If-statement
  227. * ------------
  228. * <code>{if:condition:success_variable[:else:failure_variable]}</code>
  229. * *condition* is evaluated to a boolean. If it evaluates to TRUE, the
  230. * value of *success_variable* is used. Otherwise, the value of
  231. * *failure_variable* is used (defaults to an empty string if no
  232. * else-statement is specified).
  233. *
  234. * @param string $variable The variable to replace.
  235. * @param Node $data The data block to search in for a value.
  236. * @return string The variable's value if it exists, the original string
  237. * with curly brackets otherwise.
  238. * @throws \UnexpectedValueException If a helper function is not callable.
  239. */
  240. private static function replace_variable($variable, Node $data) {
  241. // If-(else-)statement
  242. if( preg_match('/^if:([^:]*):(.*?)(?::else:(.*))?$/', $variable, $matches) ) {
  243. $condition = $data->get($matches[1]);
  244. $if = $data->get($matches[2]);
  245. if( $condition )
  246. return $if;
  247. return count($matches) > 3 ? self::replace_variable($matches[3], $data) : '';
  248. }
  249. // Default: variable with optional helper functions
  250. $parts = explode(':', $variable);
  251. $name = $parts[0];
  252. $helper_functions = array_slice($parts, 1);
  253. if( strpos($name, '.') !== false ) {
  254. // Variable of the form 'foo.bar'
  255. list($variable_name, $property) = explode('.', $name, 2);
  256. $object = $data->get($variable_name);
  257. if( is_object($object) && property_exists($object, $property) ) {
  258. // Object property
  259. $value = $object->$property;
  260. } elseif( is_array($object) && isset($object[$property]) ) {
  261. // Associative array index
  262. $value = $object[$property];
  263. }
  264. }
  265. // Default: Simple variable name
  266. if( !isset($value) )
  267. $value = $data->get($name);
  268. // Don't continue if the variable name is not found in the data block
  269. if( $value !== null ) {
  270. // Apply helper functions to the variable's value iteratively
  271. foreach( $helper_functions as $func ) {
  272. if( !is_callable($func) ) {
  273. throw new \UnexpectedValueException(
  274. sprintf('Helper function "%s" is not callable.', $func)
  275. );
  276. }
  277. $value = $func($value);
  278. }
  279. return $value;
  280. }
  281. return '{'.$variable.'}';
  282. }
  283. /**
  284. * Remove all current include paths.
  285. */
  286. static function clear_include_path() {
  287. self::$include_path = array();
  288. }
  289. /**
  290. * Replace all include paths by a single new one.
  291. *
  292. * @param string $path The new path to set as root.
  293. * @uses clear_include_path()
  294. */
  295. static function set_root($path) {
  296. self::clear_include_path();
  297. self::add_root($path);
  298. }
  299. /**
  300. * Add a new include path.
  301. *
  302. * @param string $path The path to add.
  303. * @throws FileNotFoundError If the path does not exist.
  304. */
  305. static function add_root($path) {
  306. if( $path[strlen($path) - 1] != '/' )
  307. $path .= '/';
  308. if( !is_dir($path) )
  309. throw new FileNotFoundError($path, true);
  310. self::$include_path[] = $path;
  311. }
  312. }
  313. /**
  314. * Error, thrown when an error occurs during the parsing of a template file.
  315. *
  316. * @package WebBasics
  317. */
  318. class ParseError extends \RuntimeException {
  319. /**
  320. * Constructor.
  321. *
  322. * Sets an error message with the path to the template file and a line number.
  323. *
  324. * @param Template $tpl The template in which the error occurred.
  325. * @param string $message A message describing the error.
  326. * @param int $line The line number at which the error occurred.
  327. */
  328. function __construct(Template $tpl, $message, $line) {
  329. $this->message = sprintf('Parse error in file %s, line %d: %s',
  330. $tpl->get_path(), $line, $message);
  331. }
  332. }
  333. ?>