pquery.template.php 6.0 KB

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