pquery.template.php 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. // @codeCoverageIgnoreStart
  67. }
  68. // @codeCoverageIgnoreEnd
  69. /**
  70. * Replace blocks and variables in the template's content.
  71. *
  72. * @returns string The template's content, with replaced variables.
  73. */
  74. function parse() {
  75. $lines = array('-');
  76. $index = 0;
  77. // Loop through the content character by character
  78. for( $i = 0, $l = strlen($this->content); $i < $l; $i++ ) {
  79. $c = $this->content[$i];
  80. if( $c == '{' ) {
  81. // Possible variable container found, add marker
  82. $lines[] = '+';
  83. $index++;
  84. } elseif( $c == '}' ) {
  85. // Variable container closed, add closure marker
  86. $lines[] = '-';
  87. $index++;
  88. } else {
  89. // Add character to the last line
  90. $lines[$index] .= $c;
  91. }
  92. }
  93. $line_count = 1;
  94. $block = $root = new Block;
  95. $block->children = array();
  96. $in_block = false;
  97. // Loop through the parsed lines, building the block tree
  98. foreach( $lines as $line ) {
  99. $marker = $line[0];
  100. if( $marker == '+' ) {
  101. if( strpos($line, 'block:') === 1 ) {
  102. // Block start
  103. $block = $block->add('block', array('name' => substr($line, 7)));
  104. } elseif( strpos($line, 'end') === 1 ) {
  105. // Block end
  106. if( $block->parent === null ) {
  107. return self::error('Unexpected "{end}" at line %d in template "%s".',
  108. $line_count, $this->path);
  109. }
  110. $block = $block->parent;
  111. } else {
  112. // Variable enclosure
  113. $block->add('variable', array('content' => substr($line, 1)));
  114. }
  115. } else {
  116. $block->add('', array('content' => substr($line, 1)));
  117. }
  118. // Count lines for error messages
  119. $line_count += substr_count($line, "\n");
  120. }
  121. // Use recursion to parse all blocks from the root level
  122. return self::parse_block($root, $this->data);
  123. }
  124. /**
  125. * Replace a variable name if it exists within a given data scope.
  126. *
  127. * Apply any of the following helper functions:
  128. * - Translation: <code>{_:name[:count_var_name]}</code>
  129. * - Default: <code>{var_name[:func1:func2:...]}</code>
  130. * 'var_name' can be of the form 'foo.bar'. In this case, 'foo' is the
  131. * name of an object ot associative array variable. 'bar' is a property
  132. * name to get of the object, or the associative index to the array.
  133. *
  134. * @param string $variable The variable to replace.
  135. * @param Block $data The data block to search in for the value.
  136. * @returns string The variable's value if it exists, the original string otherwise.
  137. * @todo Implement translations
  138. */
  139. static function parse_variable($variable, $data) {
  140. $parts = explode(':', $variable);
  141. $name = $parts[0];
  142. $parts = array_slice($parts, 1);
  143. switch( $name ) {
  144. case '_':
  145. return '--translation--';
  146. break;
  147. default:
  148. if( strpos($name, '.') !== false ) {
  149. list($object_name, $property) = explode('.', $name, 2);
  150. $object = $data->get($object_name);
  151. if( is_object($object) && property_exists($object, $property) ) {
  152. $value = $object->$property;
  153. } elseif( is_array($object) && isset($object[$property]) ) {
  154. $value = $object[$property];
  155. }
  156. } else {
  157. $value = $data->get($name);
  158. }
  159. // Don't continue if the variable name is not foudn in the data block
  160. if( $value === null )
  161. break;
  162. // Apply existing PHP functions to the variable's value
  163. foreach( $parts as $func ) {
  164. if( !is_callable($func) )
  165. return self::error('Function "%s" does not exist.', $func);
  166. $value = $func($value);
  167. }
  168. return $value;
  169. }
  170. return '{'.$variable.'}';
  171. }
  172. /**
  173. * Parse a single block, recursively parsing its sub-blocks with a given data scope.
  174. *
  175. * @param Block $variable The block to parse.
  176. * @param Block $data the data block to search in for the variable values.
  177. * @returns string The parsed block.
  178. * @uses parse_variable
  179. */
  180. static function parse_block($block, $data) {
  181. $content = '';
  182. foreach( $block->children as $child ) {
  183. switch( $child->name ) {
  184. case 'block':
  185. $block_name = $child->get('name');
  186. foreach( $data->find($block_name) as $block_data ) {
  187. $content .= self::parse_block($child, $block_data);
  188. }
  189. break;
  190. case 'variable':
  191. $content .= self::parse_variable($child->content, $data);
  192. break;
  193. default:
  194. $content .= $child->content;
  195. }
  196. }
  197. return $content;
  198. }
  199. /**
  200. * Replace all include paths by a single new one.
  201. *
  202. * @param str $path The path to set.
  203. * @param bool $relative Indicates whether the path is relative to the document root.
  204. */
  205. static function set_root($path, $relative=true) {
  206. self::$include_path = array();
  207. self::add_root($path, $relative);
  208. }
  209. /**
  210. * Add a new include path.
  211. *
  212. * @param str $path The path to add.
  213. * @param bool $relative Indicates whether the path is relative to the document root.
  214. */
  215. static function add_root($path, $relative=true) {
  216. $relative && $path = PQUERY_ROOT.$path;
  217. preg_match('%/$%', $path) || $path .= '/';
  218. if( !is_dir($path) )
  219. return self::error('"%s" is not a directory.', $path);
  220. self::$include_path[] = $path;
  221. }
  222. }
  223. /**
  224. * Shortcut constructor for {@link pQueryTemplate}.
  225. *
  226. * @param string $path The path to a template file.
  227. * @returns pQueryTemplate A new template instance.
  228. */
  229. function _tpl($path) {
  230. return pQuery::create('tpl', $path);
  231. }
  232. /*
  233. * Add plugin to pQuery
  234. */
  235. __p::extend('pQueryTemplate', 'tpl');
  236. /*
  237. * Set initial root to pQuery root folder
  238. */
  239. __tpl::set_root('');
  240. ?>