template.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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. * The variables of the form *{$variable}* that are used in the template
  67. * above, are examples of expressions. An expression is always enclosed in
  68. * curly brackets: *{expression}*. The grammar of all expressions that are
  69. * currently supported can be described as follows:
  70. * <code>
  71. * &lt;expression&gt; : {&lt;exp&gt;}
  72. * &lt;exp&gt; : &lt;nested_exp&gt;
  73. * | &lt;nested_exp&gt;?&lt;nested_exp&gt;:&lt;nested_exp&gt; # Conditional statement
  74. * &lt;nested_exp&gt; :
  75. * | &lt;variable&gt;
  76. * | &lt;nested_exp&gt;||&lt;nested_exp&gt; # Default value
  77. * | &lt;function&gt;(&lt;nested_exp&gt;) # Static function call
  78. * | &lt;constant&gt;
  79. * | &lt;html&gt;
  80. * &lt;variable&gt; : $&lt;name&gt; # Regular variable (escaped)
  81. * | $&lt;name&gt;.&lt;name&gt; # Object attribute or associative array value (escaped)
  82. * | $&lt;name&gt;.&lt;name&gt;() # Method call (escaped) (no arguments allowed)
  83. * | $$&lt;name&gt; # Regular variable (plain)
  84. * | $$&lt;name&gt;.&lt;name&gt; # Object attribute or associative array value (plain)
  85. * | $$&lt;name&gt;.&lt;name&gt;() # Method call (plain)
  86. * &lt;function&gt; : &lt;name&gt; # Global function
  87. * | &lt;name&gt;::&lt;name&gt; # Static class method
  88. * &lt;constant&gt; : An all-caps PHP constant: [A-Z0-9_]+
  89. * &lt;html&gt; : A string without parentheses, pipes, curly brackets or semicolons: [^()|{}:]*
  90. * &lt;name&gt; : A non-empty variable/method name consisting of [a-zA-Z0-9-_]+
  91. * </code>
  92. *
  93. * @package WebBasics
  94. */
  95. class Template extends Node {
  96. /**
  97. * Default extension of template files.
  98. *
  99. * @var array
  100. */
  101. const DEFAULT_EXTENSION = '.tpl';
  102. /**
  103. * Root directories from which template files are included.
  104. *
  105. * @var array
  106. */
  107. private static $include_path = array();
  108. /**
  109. * The path the template was found in.
  110. *
  111. * @var string
  112. */
  113. private $path;
  114. /**
  115. * The content of the template file.
  116. *
  117. * @var string
  118. */
  119. private $file_content;
  120. /**
  121. * The block structure of the template file.
  122. *
  123. * @var Node
  124. */
  125. private $root_block;
  126. /**
  127. * Create a new Template object, representing a template file.
  128. *
  129. * Template files are assumed to have the .tpl extension. If no extension
  130. * is specified, '.tpl' is appended to the filename.
  131. *
  132. * @param string $filename The path to the template file from one of the root directories.
  133. */
  134. function __construct($filename) {
  135. // Add default extension if none is found
  136. strpos($filename, '.') === false && $filename .= self::DEFAULT_EXTENSION;
  137. $look_in = count(self::$include_path) ? self::$include_path : array('.');
  138. $found = false;
  139. foreach ($look_in as $root) {
  140. $path = $root.$filename;
  141. if (file_exists($path)) {
  142. $this->path = $path;
  143. $this->file_content = file_get_contents($path);
  144. $found = true;
  145. break;
  146. }
  147. }
  148. if (!$found) {
  149. throw new \RuntimeException(
  150. sprintf("Could not find template file \"%s\", looked in folders:\n%s",
  151. $filename, implode("\n", $look_in))
  152. );
  153. }
  154. $this->parseBlocks();
  155. }
  156. /**
  157. * Get the path to the template file (including one of the include paths).
  158. *
  159. * @return string The path to the template file.
  160. */
  161. function getPath() {
  162. return $this->path;
  163. }
  164. /**
  165. * Parse the content of the template file into a tree structure of blocks
  166. * and variables.
  167. *
  168. * @throws ParseError If an {end} tag is not used properly.
  169. */
  170. private function parseBlocks() {
  171. $current = $root = new Node('block');
  172. $after = $this->file_content;
  173. $line_count = 0;
  174. while (preg_match('/(.*?)\{([^}]+)}(.*)/s', $after, $matches)) {
  175. list($before, $brackets_content, $after) = array_slice($matches, 1);
  176. $line_count += substr_count($before, "\n");
  177. // Everything before the new block belongs to its parent
  178. $html = $current->add('html')->set('content', $before);
  179. if ($brackets_content == 'end') {
  180. // {end} encountered, go one level up in the tree
  181. if ($current->isRoot())
  182. throw new ParseError($this, 'unexpected {end}', $line_count + 1);
  183. $current = $current->getParent();
  184. } elseif(substr($brackets_content, 0, 6) == 'block:') {
  185. // {block:...} encountered
  186. $block_name = substr($brackets_content, 6);
  187. // Go one level deeper into the tree
  188. $current = $current->add('block')->set('name', $block_name);
  189. } elseif (strpos($brackets_content, "\n") !== false) {
  190. // Bracket content contains newlines, so it is probably JavaScript or CSS
  191. $html->set('content', $before . '{' . $brackets_content . '}');
  192. } else {
  193. // Variable or something else
  194. $current->add('expression')->set('content', $brackets_content);
  195. }
  196. }
  197. $line_count += substr_count($after, "\n");
  198. if ($current !== $root)
  199. throw new ParseError($this, 'missing {end}', $line_count + 1);
  200. // Add the last remaining content to the root node
  201. $after && $root->add('html')->set('content', $after);
  202. $this->root_block = $root;
  203. }
  204. /**
  205. * Replace blocks and variables in the template's content.
  206. *
  207. * @return string The template's content, with replaced blocks and variables.
  208. */
  209. function render() {
  210. // Use recursion to parse all blocks from the root level
  211. return self::renderBlock($this->root_block, $this);
  212. }
  213. /**
  214. * Render a single block, recursively parsing its sub-blocks with a given data scope.
  215. *
  216. * @param Node $block The block to render.
  217. * @param Node $data The data block to search in for the variable values.
  218. * @return string The rendered block.
  219. * @uses evaluateExpression()
  220. */
  221. private static function renderBlock(Node $block, Node $data) {
  222. $html = '';
  223. foreach ($block->getChildren() as $child) {
  224. switch ($child->getName()) {
  225. case 'html':
  226. $html .= $child->get('content');
  227. break;
  228. case 'block':
  229. $block_name = $child->get('name');
  230. foreach ($data->find($block_name) as $child_data)
  231. $html .= self::renderBlock($child, $child_data);
  232. break;
  233. case 'expression':
  234. $html .= self::evaluateExpression($child->get('content'), $data);
  235. }
  236. }
  237. return $html;
  238. }
  239. /**
  240. * Evaluate a <variable> expression.
  241. *
  242. * This function is a helper for {@link evaluateExpression()}.
  243. *
  244. * @param string[] $matches Regex matches for variable pattern.
  245. * @return string The evaluation of the variable.
  246. * @param Node $data A data tree containing variable values to use.
  247. * @throws \BadMethodCallException If an error occured while calling a variable method.
  248. * @throws \OutOfBoundsException If an unexisting array key is requested.
  249. * @throws \UnexpectedValueException In some other error situations.
  250. */
  251. private static function evaluateVariable(array $matches, Node $data) {
  252. $before = $matches[1];
  253. $noescape_sign = $matches[2];
  254. $variable = $matches[3];
  255. $value = $data->get($variable);
  256. if (count($matches) == 5) {
  257. // $<name>.<name>
  258. $attribute = $matches[4];
  259. if ($value === null) {
  260. throw new \UnexpectedValueException(
  261. sprintf('Cannot get attribute "%s.%s": value is NULL', $variable, $attribute)
  262. );
  263. }
  264. $attr_error = function($error, $class='\UnexpectedValueException') use ($attribute, $variable) {
  265. throw new $class(
  266. sprintf('Cannot get attribute "%s.%s": %s', $variable, $attribute, $error)
  267. );
  268. };
  269. if (is_array($value)) {
  270. isset($value[$attribute]) || $attr_error('no such key', '\OutOfBoundsException');
  271. $value = $value[$attribute];
  272. } elseif (is_object($value)) {
  273. isset($value->$attribute) || $attr_error('no such attribute');
  274. $value = $value->$attribute;
  275. } else {
  276. $attr_error('variable is no array or object');
  277. }
  278. } elseif (count($matches) == 6) {
  279. // $<name>.<name>()
  280. $method = $matches[4];
  281. if ($value === null) {
  282. throw new \UnexpectedValueException(
  283. sprintf('Cannot call method "%s.%s()": object is NULL', $variable, $method)
  284. );
  285. }
  286. $method_error = function($error) use ($method, $variable) {
  287. throw new \BadMethodCallException(
  288. sprintf('Cannot call method "%s.%s()": %s', $variable, $method, $error)
  289. );
  290. };
  291. if (is_object($value)) {
  292. method_exists($value, $method) || $method_error('no such method');
  293. $value = $value->$method();
  294. } else {
  295. $method_error('variable is no object');
  296. }
  297. }
  298. // Escape value
  299. if (is_string($value) && !$noescape_sign)
  300. $value = self::escapeVariableValue($value);
  301. return $before . $value;
  302. }
  303. /**
  304. * Escape a variable value for displaying in HTML.
  305. *
  306. * Uses {@link http://php.net/htmlentities} with ENT_QUOTES.
  307. *
  308. * @param string $value The variable value to escape.
  309. * @return string The escaped value.
  310. */
  311. private static function escapeVariableValue($value) {
  312. return htmlspecialchars($value, ENT_QUOTES);
  313. }
  314. /**
  315. * Evaluate a conditional expression.
  316. *
  317. * This function is a helper for {@link evaluateExpression()}.
  318. *
  319. * @param string[] $matches Regex matches for conditional pattern.
  320. * @param Node $data A data tree containing variable values to use for
  321. * variable expressions.
  322. * @return string The evaluation of the condition.
  323. */
  324. private static function evaluateCondition(array $matches, Node $data) {
  325. if (self::evaluateExpression($matches[1], $data, false)) {
  326. // Condition evaluates to true: return 'if' evaluation
  327. return self::evaluateExpression($matches[2], $data, false);
  328. } elseif (count($matches) == 4) {
  329. // <nested_exp>?<nested_exp>:<nested_exp>
  330. return self::evaluateExpression($matches[3], $data, false);
  331. }
  332. // No 'else' specified: evaluation is an empty string
  333. return '';
  334. }
  335. /**
  336. * Evaluate a static function call expression.
  337. *
  338. * This function is a helper for {@link evaluateExpression()}.
  339. *
  340. * @param array $matches Regex matches for function pattern.
  341. * @param Node $data A data tree containing variable values to use for
  342. * variable expressions.
  343. * @return string The evaluation of the function call.
  344. * @throws \BadFunctionCallException If the function is undefined.
  345. */
  346. private static function evaluateFunction(array $matches, Node $data) {
  347. $function = $matches[1];
  348. $parameter = $matches[2];
  349. if (!is_callable($function)) {
  350. throw new \BadFunctionCallException(
  351. sprintf('Cannot call function "%s": function is not callable', $function)
  352. );
  353. }
  354. $parameter_value = self::evaluateExpression($parameter, $data, false);
  355. return call_user_func($function, $parameter_value);
  356. }
  357. /**
  358. * Evaluate a PHP-constant expression.
  359. *
  360. * This function is a helper for {@link evaluateExpression()}.
  361. *
  362. * @param string $constant The name of the PHP constant.
  363. * @param bool $root_level Whether the expression was enclosed in curly
  364. * brackets (FALSE for sub-expressions);
  365. * @return string The evaluation of the constant if it is defined, the
  366. * original constant name otherwise.
  367. */
  368. private static function evaluateConstant($constant, $root_level) {
  369. if (defined($constant))
  370. return constant($constant);
  371. return $root_level ? '{' . $constant . '}' : $constant;
  372. }
  373. /**
  374. * Evaluate an expression.
  375. *
  376. * The curly brackets should already have been stripped before passing an
  377. * expression to this method.
  378. *
  379. * @param string $expression The expression to evaluate.
  380. * @param Node $data A data tree containing variable values to use for
  381. * variable expressions.
  382. * @param bool $root_level Whether the expression was enclosed in curly
  383. * brackets (FALSE for sub-expressions);
  384. * @return string The evaluation of the expression if present, the
  385. * original string enclosed in curly brackets otherwise.
  386. */
  387. private static function evaluateExpression($expression, Node $data, $root_level=true) {
  388. if ($expression) {
  389. $name = '[a-zA-Z0-9-_]+';
  390. $function = "$name(?:::$name)?";
  391. if (preg_match("/^([^?]*?)\s*\?([^:]*)(?::(.*))?$/", $expression, $matches)) {
  392. // <nested_exp>?<nested_exp> | <nested_exp>?<nested_exp>:<nested_exp>
  393. return self::evaluateCondition($matches, $data);
  394. } elseif (preg_match("/^(.*?)\\$(\\$?)($name)(?:\.($name)(\(\))?)?$/", $expression, $matches)) {
  395. // $<name> | $<name>.<name> | $<name>.<name>()
  396. // | $$<name> | $$<name>.<name> | $$<name>.<name>()
  397. return self::evaluateVariable($matches, $data);
  398. } elseif (preg_match("/^($function)\((.+?)\)?$/", $expression, $matches)) {
  399. // <function>(<nested_exp>)
  400. return self::evaluateFunction($matches, $data);
  401. } elseif (preg_match("/^([A-Z0-9_]+)$/", $expression, $matches)) {
  402. // <constant>
  403. return self::evaluateConstant($expression, $root_level);
  404. } elseif (($split_at = strpos($expression, '||', 1)) !== false) {
  405. // <nested_exp>||<nested_exp>
  406. try {
  407. return self::evaluateExpression(substr($expression, 0, $split_at), $data, false);
  408. } catch(\RuntimeException $e) {
  409. return self::evaluateExpression(substr($expression, $split_at + 2), $data, false);
  410. }
  411. }
  412. }
  413. // No expression: return original string
  414. return $root_level ? '{' . $expression . '}' : $expression;
  415. }
  416. /**
  417. * Remove all current include paths.
  418. */
  419. static function clearIncludePath() {
  420. self::$include_path = array();
  421. }
  422. /**
  423. * Replace all include paths by a single new one.
  424. *
  425. * @param string $path The new path to set as root.
  426. * @uses clearIncludePath()
  427. */
  428. static function setRoot($path) {
  429. self::clearIncludePath();
  430. self::addRoot($path);
  431. }
  432. /**
  433. * Add a new include path.
  434. *
  435. * @param string $path The path to add.
  436. * @throws FileNotFoundError If the path does not exist.
  437. */
  438. static function addRoot($path) {
  439. if ($path[strlen($path) - 1] != '/')
  440. $path .= '/';
  441. if (!is_dir($path))
  442. throw new FileNotFoundError($path, true);
  443. self::$include_path[] = $path;
  444. }
  445. }
  446. /**
  447. * Error, thrown when an error occurs during the parsing of a template file.
  448. *
  449. * @package WebBasics
  450. */
  451. class ParseError extends \RuntimeException {
  452. /**
  453. * Constructor.
  454. *
  455. * Sets an error message with the path to the template file and a line number.
  456. *
  457. * @param Template $tpl The template in which the error occurred.
  458. * @param string $message A message describing the error.
  459. * @param int $line The line number at which the error occurred.
  460. */
  461. function __construct(Template $tpl, $message, $line) {
  462. $this->message = sprintf('Parse error in file %s, line %d: %s',
  463. $tpl->getPath(), $line, $message);
  464. }
  465. }
  466. ?>