template.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382
  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. * @throws ParseError If an {end} tag is not used properly.
  143. */
  144. private function parse_blocks() {
  145. $current = $root = new Node('block');
  146. $after = $this->file_content;
  147. $line_count = 0;
  148. while( preg_match('/(.*?)\{([^}]+)}(.*)/s', $after, $matches) ) {
  149. list($before, $brackets_content, $after) = array_slice($matches, 1);
  150. $line_count += substr_count($before, "\n");
  151. //var_dump(array_slice($matches, 1));
  152. // Everything before the new block belongs to its parent
  153. $current->add('html')->set('content', $before);
  154. if( $brackets_content == 'end' ) {
  155. // {end} encountered, go one level up in the tree
  156. if( $current->is_root() )
  157. throw new ParseError($this, 'unexpected {end}', $line_count + 1);
  158. $current = $current->get_parent();
  159. } elseif( substr($brackets_content, 0, 6) == 'block:' ) {
  160. // {block:...} encountered
  161. $block_name = substr($brackets_content, 6);
  162. // Go one level deeper into the tree
  163. $current = $current->add('block')->set('name', $block_name);
  164. } else {
  165. // Variable or something else
  166. $current->add('variable')->set('content', $brackets_content);
  167. }
  168. }
  169. $line_count += substr_count($after, "\n");
  170. if( $current !== $root )
  171. throw new ParseError($this, 'missing {end}', $line_count + 1);
  172. // Add the last remaining content to the root node
  173. $root->add('html')->set('content', $after);
  174. $this->root_block = $root;
  175. }
  176. /**
  177. * Replace blocks and variables in the template's content.
  178. *
  179. * @return string The template's content, with replaced blocks and variables.
  180. */
  181. function render() {
  182. // Use recursion to parse all blocks from the root level
  183. return self::render_block($this->root_block, $this);
  184. }
  185. /**
  186. * Render a single block, recursively parsing its sub-blocks with a given data scope.
  187. *
  188. * @param Node $block The block to render.
  189. * @param Node $data The data block to search in for the variable values.
  190. * @return string The rendered block.
  191. * @uses replace_variable()
  192. */
  193. private static function render_block(Node $block, Node $data) {
  194. $html = '';
  195. foreach( $block->get_children() as $child ) {
  196. switch( $child->get_name() ) {
  197. case 'html':
  198. $html .= $child->get('content');
  199. break;
  200. case 'block':
  201. $block_name = $child->get('name');
  202. foreach( $data->find($block_name) as $child_data )
  203. $html .= self::render_block($child, $child_data);
  204. break;
  205. case 'variable':
  206. $html .= self::replace_variable($child->get('content'), $data);
  207. }
  208. }
  209. return $html;
  210. }
  211. /**
  212. * Replace a variable name if it exists within a given data scope.
  213. *
  214. * Applies any of the following macro's:
  215. *
  216. * --------
  217. * Variable
  218. * --------
  219. * <code>{var_name[:func1:func2:...]}</code>
  220. * *var_name* can be of the form *foo.bar*. In this case, *foo* is the
  221. * name of an object or associative array variable. *bar* is a property
  222. * name to get of the object, or the associative index to the array.
  223. * *func1*, *func2*, etc. are helper functions that are executed in the
  224. * same order as listed. The retuen value of each helper function replaces
  225. * the previous variable value.
  226. *
  227. * ------------
  228. * If-statement
  229. * ------------
  230. * <code>{if:condition:success_variable[:else:failure_variable]}</code>
  231. * *condition* is evaluated to a boolean. If it evaluates to TRUE, the
  232. * value of *success_variable* is used. Otherwise, the value of
  233. * *failure_variable* is used (defaults to an empty string if no
  234. * else-statement is specified).
  235. *
  236. * @param string $variable The variable to replace.
  237. * @param Node $data The data block to search in for a value.
  238. * @return string The variable's value if it exists, the original string
  239. * with curly brackets otherwise.
  240. * @throws \UnexpectedValueException If a helper function is not callable.
  241. */
  242. private static function replace_variable($variable, Node $data) {
  243. // If-(else-)statement
  244. if( preg_match('/^if:([^:]*):(.*?)(?::else:(.*))?$/', $variable, $matches) ) {
  245. $condition = $data->get($matches[1]);
  246. $if = $data->get($matches[2]);
  247. if( $condition )
  248. return $if;
  249. return count($matches) > 3 ? self::replace_variable($matches[3], $data) : '';
  250. }
  251. // Default: variable with optional helper functions
  252. $parts = explode(':', $variable);
  253. $name = $parts[0];
  254. $helper_functions = array_slice($parts, 1);
  255. if( strpos($name, '.') !== false ) {
  256. // Variable of the form 'foo.bar'
  257. list($variable_name, $property) = explode('.', $name, 2);
  258. $object = $data->get($variable_name);
  259. if( is_object($object) && property_exists($object, $property) ) {
  260. // Object property
  261. $value = $object->$property;
  262. } elseif( is_array($object) && isset($object[$property]) ) {
  263. // Associative array index
  264. $value = $object[$property];
  265. }
  266. }
  267. // Default: Simple variable name
  268. if( !isset($value) )
  269. $value = $data->get($name);
  270. // Don't continue if the variable name is not found in the data block
  271. if( $value !== null ) {
  272. // Apply helper functions to the variable's value iteratively
  273. foreach( $helper_functions as $func ) {
  274. if( !is_callable($func) ) {
  275. throw new \UnexpectedValueException(
  276. sprintf('Helper function "%s" is not callable.', $func)
  277. );
  278. }
  279. $value = $func($value);
  280. }
  281. return $value;
  282. }
  283. return '{'.$variable.'}';
  284. }
  285. /**
  286. * Remove all current include paths.
  287. */
  288. static function clear_include_path() {
  289. self::$include_path = array();
  290. }
  291. /**
  292. * Replace all include paths by a single new one.
  293. *
  294. * @param string $path The new path to set as root.
  295. * @uses clear_include_path()
  296. */
  297. static function set_root($path) {
  298. self::clear_include_path();
  299. self::add_root($path);
  300. }
  301. /**
  302. * Add a new include path.
  303. *
  304. * @param string $path The path to add.
  305. * @throws FileNotFoundError If the path does not exist.
  306. */
  307. static function add_root($path) {
  308. if( $path[strlen($path) - 1] != '/' )
  309. $path .= '/';
  310. if( !is_dir($path) )
  311. throw new FileNotFoundError($path, true);
  312. self::$include_path[] = $path;
  313. }
  314. }
  315. /**
  316. * Error, thrown when an error occurs during the parsing of a template file.
  317. *
  318. * @package WebBasics
  319. */
  320. class ParseError extends \RuntimeException {
  321. /**
  322. * Constructor.
  323. *
  324. * Sets an error message with the path to the template file and a line number.
  325. *
  326. * @param Template $tpl The template in which the error occurred.
  327. * @param string $message A message describing the error.
  328. * @param int $line The line number at which the error occurred.
  329. */
  330. function __construct(Template $tpl, $message, $line) {
  331. $this->message = sprintf('Parse error in file %s, line %d: %s',
  332. $tpl->get_path(), $line, $message);
  333. }
  334. }
  335. ?>