pquery.template.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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 if none is found
  55. strpos($filename, '.') === false && $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. * 'var_name' can be of the form 'foo.bar'. In this case, 'foo' is the
  129. * name of an object ot associative array variable. 'bar' is a property
  130. * name to get of the object, or the associative index to the array.
  131. *
  132. * @param string $variable The variable to replace.
  133. * @param Block $data The data block to search in for the value.
  134. * @returns string The variable's value if it exists, the original string otherwise.
  135. * @todo Implement translations
  136. */
  137. static function parse_variable($variable, $data) {
  138. $parts = explode(':', $variable);
  139. $name = $parts[0];
  140. $parts = array_slice($parts, 1);
  141. switch( $name ) {
  142. case '_':
  143. return '--translation--';
  144. break;
  145. default:
  146. if( strpos($name, '.') !== false ) {
  147. list($object_name, $property) = explode('.', $name, 2);
  148. $object = $data->get($object_name);
  149. if( is_object($object) && property_exists($object, $property) ) {
  150. $value = $object->$property;
  151. } elseif( is_array($object) && isset($object[$property]) ) {
  152. $value = $object[$property];
  153. }
  154. } else {
  155. $value = $data->get($name);
  156. }
  157. // Don't continue if the variable name is not foudn in the data block
  158. if( $value === null )
  159. break;
  160. // Apply existing PHP functions to the variable's value
  161. foreach( $parts as $func ) {
  162. if( !is_callable($func) )
  163. return self::error('Function "%s" does not exist.', $func);
  164. $value = $func($value);
  165. }
  166. return $value;
  167. }
  168. return '{'.$variable.'}';
  169. }
  170. /**
  171. * Parse a single block, recursively parsing its sub-blocks with a given data scope.
  172. *
  173. * @param Block $variable The block to parse.
  174. * @param Block $data the data block to search in for the variable values.
  175. * @returns string The parsed block.
  176. * @uses parse_variable
  177. */
  178. static function parse_block($block, $data) {
  179. $content = '';
  180. foreach( $block->children as $child ) {
  181. switch( $child->name ) {
  182. case 'block':
  183. $block_name = $child->get('name');
  184. foreach( $data->find($block_name) as $block_data ) {
  185. $content .= self::parse_block($child, $block_data);
  186. }
  187. break;
  188. case 'variable':
  189. $content .= self::parse_variable($child->content, $data);
  190. break;
  191. default:
  192. $content .= $child->content;
  193. }
  194. }
  195. return $content;
  196. }
  197. /**
  198. * Replace all include paths by a single new one.
  199. *
  200. * @param str $path The path to set.
  201. * @param bool $relative Indicates whether the path is relative to the document root.
  202. */
  203. static function set_root($path, $relative=true) {
  204. self::$include_path = array();
  205. self::add_root($path, $relative);
  206. }
  207. /**
  208. * Add a new include path.
  209. *
  210. * @param str $path The path to add.
  211. * @param bool $relative Indicates whether the path is relative to the document root.
  212. */
  213. static function add_root($path, $relative=true) {
  214. $relative && $path = PQUERY_ROOT.$path;
  215. preg_match('%/$%', $path) || $path .= '/';
  216. if( !is_dir($path) )
  217. return self::error('"%s" is not a directory.', $path);
  218. self::$include_path[] = $path;
  219. }
  220. }
  221. /**
  222. * Shortcut constructor for {@link pQueryTemplate}.
  223. *
  224. * @param string $path The path to a template file.
  225. * @returns pQueryTemplate A new template instance.
  226. */
  227. function _tpl($path) {
  228. return pQuery::create('tpl', $path);
  229. }
  230. /*
  231. * Add plugin to pQuery
  232. */
  233. __p::extend('pQueryTemplate', 'tpl');
  234. /*
  235. * Set initial root to pQuery root folder
  236. */
  237. __tpl::set_root('');
  238. ?>