pquery.template.php 6.8 KB

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