pquery.template.php 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <?php
  2. /**
  3. * pQuery plugin for parsing templates.
  4. *
  5. * @package pQuery
  6. */
  7. __p::load_utils('block');
  8. /**
  9. * @todo Documentation
  10. * @property string $content The template's content.
  11. */
  12. class pQueryTemplate extends pQuery implements pQueryExtension {
  13. const DEFAULT_EXTENSION = 'tpl';
  14. static $accepts = array('string' => 'open_template_file');
  15. /**
  16. * Root folders from which template files will be included.
  17. *
  18. * @var string
  19. */
  20. static $include_path = array();
  21. /**
  22. * @see pQuery::$variable_alias
  23. * @var string|array
  24. */
  25. static $variable_alias = 'content';
  26. /**
  27. * The path the template was found in.
  28. *
  29. * @var string
  30. */
  31. var $path;
  32. /**
  33. * Nested variable values.
  34. *
  35. * @var Block
  36. */
  37. var $data;
  38. /**
  39. * Constructor
  40. *
  41. * Create a new nested data block object for variable values.
  42. *
  43. * @see data
  44. */
  45. function __construct() {
  46. $this->data = new Block();
  47. }
  48. /**
  49. * Open the given template filename in the current variable.
  50. */
  51. function open_template_file() {
  52. $found = false;
  53. $filename = $this->variable;
  54. // Add default extension
  55. strpos($filename, '.') || $filename .= '.'.self::DEFAULT_EXTENSION;
  56. foreach( self::$include_path as $root ) {
  57. $path = $root.$filename;
  58. if( is_file($path) ) {
  59. $this->path = $path;
  60. $this->content = file_get_contents($path);
  61. return;
  62. }
  63. }
  64. self::error("Could not find template file \"%s\", looked in folders:\n%s",
  65. $filename, implode("\n", self::$include_path));
  66. }
  67. /**
  68. * Replace blocks and variables in the template's content.
  69. *
  70. * @returns string The template's content, with replaced variables.
  71. */
  72. function parse() {
  73. $lines = array('-');
  74. $index = 0;
  75. // Loop through the content character by character
  76. for( $i = 0, $l = strlen($this->content); $i < $l; $i++ ) {
  77. $c = $this->content[$i];
  78. if( $c == '{' ) {
  79. // Possible variable container found, add marker
  80. $lines[] = '+';
  81. $index++;
  82. } elseif( $c == '}' ) {
  83. // Variable container closed, add closure marker
  84. $lines[] = '-';
  85. $index++;
  86. } else {
  87. // Add character to the last line
  88. $lines[$index] .= $c;
  89. }
  90. }
  91. $line_count = 1;
  92. $block = $root = new Block;
  93. $block->children = array();
  94. $in_block = false;
  95. // Loop through the parsed lines, building the block tree
  96. foreach( $lines as $line ) {
  97. $marker = $line[0];
  98. if( $marker == '+' ) {
  99. if( strpos($line, 'block:') === 1 ) {
  100. // Block start
  101. $block = $block->add('block', array('name' => substr($line, 7)));
  102. } elseif( strpos($line, 'end') === 1 ) {
  103. // Block end
  104. if( $block->parent === null ) {
  105. return self::error('Unexpected "{end}" at line %d in template "%s".',
  106. $line_count, $this->path);
  107. }
  108. $block = $block->parent;
  109. } else {
  110. // Variable enclosure
  111. $block->add('variable', array('content' => substr($line, 1)));
  112. }
  113. } else {
  114. $block->add('', array('content' => substr($line, 1)));
  115. }
  116. // Count lines for error messages
  117. $line_count += substr_count($line, "\n");
  118. }
  119. // Use recursion to parse all blocks from the root level
  120. return self::parse_block($root, $this->data);
  121. }
  122. /**
  123. * Replace a variable name if it exists within a given data scope.
  124. *
  125. * Apply any of the following helper functions:
  126. * - Translation: <code>{_:name[:count_var_name]}</code>
  127. * - Default: <code>{var_name[:func1:func2:...]}</code>
  128. *
  129. * @param string $variable The variable to replace.
  130. * @param Block $data The data block to search in for the value.
  131. * @returns string The variable's value if it exists, the original string otherwise.
  132. * @todo Implement translations
  133. */
  134. static function parse_variable($variable, $data) {
  135. $parts = explode(':', $variable);
  136. $name = $parts[0];
  137. $parts = array_slice($parts, 1);
  138. switch( $name ) {
  139. case '_':
  140. return '--translation--';
  141. break;
  142. default:
  143. $value = $data->get($name);
  144. // Don't continue if the variable name is not foudn in the data block
  145. if( $value === null )
  146. break;
  147. // Apply existing PHP functions to the variable's value
  148. foreach( $parts as $func ) {
  149. if( !is_callable($func) )
  150. return self::error('Function "%s" does not exist.', $func);
  151. $value = $func($value);
  152. }
  153. return $value;
  154. }
  155. return '{'.$variable.'}';
  156. }
  157. /**
  158. * Parse a single block, recursively parsing its sub-blocks with a given data scope.
  159. *
  160. * @param Block $variable The block to parse.
  161. * @param Block $data the data block to search in for the variable values.
  162. * @returns string The parsed block.
  163. * @uses parse_variable
  164. */
  165. static function parse_block($block, $data) {
  166. $content = '';
  167. foreach( $block->children as $child ) {
  168. switch( $child->name ) {
  169. case 'block':
  170. $block_name = $child->get('name');
  171. foreach( $data->find($block_name) as $block_data ) {
  172. $content .= self::parse_block($child, $block_data);
  173. }
  174. break;
  175. case 'variable':
  176. $content .= self::parse_variable($child->content, $data);
  177. break;
  178. default:
  179. $content .= $child->content;
  180. }
  181. }
  182. return $content;
  183. }
  184. /**
  185. * Replace all include paths by a single new one.
  186. *
  187. * @param str $path The path to set.
  188. * @param bool $relative Indicates whether the path is relative to the document root.
  189. */
  190. static function set_root($path, $relative=true) {
  191. self::$include_path = array();
  192. self::add_root($path, $relative);
  193. }
  194. /**
  195. * Add a new include path.
  196. *
  197. * @param str $path The path to add.
  198. * @param bool $relative Indicates whether the path is relative to the document root.
  199. */
  200. static function add_root($path, $relative=true) {
  201. $relative && $path = SITE_ROOT.$path;
  202. preg_match('%/$%', $path) || $path .= '/';
  203. if( !is_dir($path) )
  204. return self::error('"%s" is not a directory.', $path);
  205. self::$include_path[] = $path;
  206. }
  207. }
  208. /**
  209. * Shortcut constructor for {@link pQueryTemplate}.
  210. *
  211. * @param string $path The path to a template file.
  212. * @returns pQueryTemplate A new template instance.
  213. */
  214. function _tpl($path) {
  215. return pQuery::create('tpl', $path);
  216. }
  217. /*
  218. * Add plugin to pQuery
  219. */
  220. __p::extend('pQueryTemplate', 'tpl');
  221. /*
  222. * Set initial root to pQuery root folder
  223. */
  224. __tpl::set_root('');
  225. ?>