template.class.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. namespace Juju\Data;
  3. require_once(realpath(dirname(__DIR__).'/events.trait.php'));
  4. require_once('earray.class.php');
  5. use Juju\{Events, Data\EArray};
  6. use \Exception;
  7. class Template {
  8. use Events;
  9. private static $templates = [];
  10. public static $cachedir;
  11. public static $basedir = __DIR__;
  12. private static $tidy;
  13. private static $tidyConfig = [
  14. 'indent'=>true,
  15. 'tab-size'=>4,
  16. 'wrap'=>0,
  17. 'wrap-asp'=>false,
  18. 'wrap-attributes'=>false,
  19. 'wrap-jste'=>false,
  20. 'wrap-php'=>false,
  21. 'wrap-script-literals'=>false,
  22. 'wrap-sections'=>false,
  23. 'char-encoding'=>'utf8',
  24. 'newline'=>'LF',
  25. 'tidy-mark'=>true,
  26. 'merge-divs'=>false,
  27. 'merge-spans'=>false,
  28. 'logical-emphasis'=>false,
  29. 'literal-attributes'=>true
  30. ];
  31. private static $regex = [
  32. 'match'=>'/\{([^#\/?_][^}\n]*?)\}/i',
  33. 'parentmatch'=>'/\{\.\.\/([^#\/?_][^}\n]*?)\}/i',
  34. 'rawmatch'=>'/\{@([^#\/?_][^}\n]*?)\}/i',
  35. 'rawparentmatch'=>'/\{@\.\.\/([^#\/?_][^}\n]*?)\}/i',
  36. 'each'=>'/\{#each ([^}]*)\}([\S\s]*)\{\/each \1\}/i',
  37. 'exist'=>'/\{#exist ([^}]*)\}([\S\s]*)\{\/exist \1\}/i',
  38. 'existelse'=>'/\{#exist ([^}]*)\}([\S\s]*)\{#else \1\}([\S\s]*)\{\/exist \1\}/i',
  39. 'ignore'=>'/\{#ignore\}([\S\s]*)\{\/ignore\}/i',
  40. 'ignored'=>'/\{#ignored (\d+?)\}/i',
  41. 'gettext'=>"/{_([^,}]+)(?:, ?([^},]+))*\}/i",
  42. 'gettext_string'=>'/^([\'"])(.+)\1$/i',
  43. 'echo'=>'/\{=([^}]+)\}/i',
  44. 'eval'=>'/\{\?([\W\w\S\s]+)\?\}/i',
  45. 'include'=>'/{#include ([^}]+)}/i',
  46. 'define'=>'/\{#define ([^}]*)\}([\S\s]*)\{\/define \1\}/i',
  47. 'widget'=>'/{#widget ([^}]+)}/i'
  48. ];
  49. protected static $parsers;
  50. private $template;
  51. private $name;
  52. private $path;
  53. public function __construct(string $name, string $template, bool $is_file = false){
  54. if(is_null(static::$parsers)){
  55. static::$parsers = [
  56. 'ignore'=>function(&$output, &$ignored){
  57. $output = preg_replace_callback(static::$regex['ignore'], function($matches) use(&$ignored){
  58. $ignored[] = $matches[1];
  59. return '{#ignored '.(count($ignored) - 1).'}';
  60. }, $output);
  61. },
  62. 'include'=>function(&$output, &$ignored = null){
  63. while(preg_match(static::$regex['include'], $output)){
  64. $output = preg_replace_callback(static::$regex['include'], function($matches) use(&$ignored){
  65. $path = static::$basedir.'/'.$matches[1];
  66. if(file_exists($path)){
  67. $output = file_get_contents($path);
  68. if(!is_null($ignored)){
  69. static::$parsers['ignore']($output, $ignored);
  70. }
  71. return $output;
  72. }
  73. return '';
  74. }, $output);
  75. }
  76. },
  77. 'define'=>function(&$output, &$widgets){
  78. while(preg_match(static::$regex['define'], $output)){
  79. $output = preg_replace_callback(static::$regex['define'], function($matches) use(&$widgets){
  80. $name = $matches[1];
  81. if(isset($widgets[$name])){
  82. throw new \Exception("Widget {$name} is already defined");
  83. }
  84. $widgets[$name] = $matches[2];
  85. return '';
  86. }, $output);
  87. }
  88. },
  89. 'widget'=>function(&$output, $widgets){
  90. while(preg_match(static::$regex['widget'], $output)){
  91. $output = preg_replace_callback(static::$regex['widget'], function($matches) use(&$widgets){
  92. $name = $matches[1];
  93. if(!isset($widgets[$name])){
  94. throw new \Exception("Widget {$name} is not defined");
  95. }
  96. return $widgets[$name];
  97. }, $output);
  98. }
  99. },
  100. 'each'=>function(&$output){
  101. $output = preg_replace_callback(static::$regex['each'], function($matches){
  102. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ";
  103. $output .= "foreach(\$data[".var_export($matches[1], true)."] as \$item): ";
  104. $output .= "\$parent[] = \$data; \$data = \$item; ?>";
  105. $output .= static::compile($matches[2]);
  106. $output .= "<?php \$data = array_pop(\$parent);";
  107. $output .= "endforeach;endif; ?>";
  108. return $output;
  109. }, $output);
  110. },
  111. 'existelse'=>function(&$output){
  112. $output = preg_replace_callback(static::$regex['existelse'], function($matches){
  113. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  114. $output .= static::compile($matches[2]);
  115. $output .= "<?php else: ?>";
  116. $output .= static::compile($matches[3]);
  117. $output .= "<?php endif; ?>";
  118. return $output;
  119. }, $output);
  120. },
  121. 'exist'=>function(&$output){
  122. $output = preg_replace_callback(static::$regex['exist'], function($matches){
  123. $output = "<?php if(isset(\$data[".var_export($matches[1], true)."])): ?>";
  124. $output .= static::compile($matches[2]);
  125. $output .= "<?php endif; ?>";
  126. return $output;
  127. }, $output);
  128. },
  129. 'gettext'=>function(&$output){
  130. $output = preg_replace_callback(static::$regex['gettext'], function($matches){
  131. if(count($matches) > 2){
  132. $output = "<?=htmlentities(sprintf(_({$matches[1]})";
  133. foreach(array_slice($matches, 2) as $item){
  134. if(preg_match(static::$regex['gettext_string'], $item)){
  135. $output .= ", $item";
  136. }else{
  137. $output .= ", (\$data['{$item}'] ?? '')";
  138. }
  139. }
  140. }else{
  141. $output = "<?=htmlentities(_({$matches[1]}";
  142. }
  143. return "{$output})); ?>";
  144. }, $output);
  145. },
  146. 'echo'=>function(&$output){
  147. $output = preg_replace_callback(static::$regex['echo'], function($matches){
  148. return "<?= {$matches[1]}; ?>";
  149. }, $output);
  150. },
  151. 'eval'=>function(&$output){
  152. $output = preg_replace_callback(static::$regex['eval'], function($matches){
  153. return "<?php {$matches[1]}; ?>";
  154. }, $output);
  155. },
  156. 'rawmatch'=>function(&$output){
  157. $output = preg_replace_callback(static::$regex['rawmatch'], function($matches){
  158. return "<?=(\$data[".var_export($matches[1], true)."] ?? '');?>";
  159. }, $output);
  160. },
  161. 'rawparentmatch'=>function(&$output){
  162. $output = preg_replace_callback(static::$regex['rawparentmatch'], function($matches){
  163. return "<?=(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  164. }, $output);
  165. },
  166. 'match'=>function(&$output){
  167. $output = preg_replace_callback(static::$regex['match'], function($matches){
  168. return "<?=htmlentities(\$data[".var_export($matches[1], true)."] ?? '');?>";
  169. }, $output);
  170. },
  171. 'parentmatch'=>function(&$output){
  172. $output = preg_replace_callback(static::$regex['parentmatch'], function($matches){
  173. return "<?=htmlentities(\$parent[count(\$parent)-1][".var_export($matches[1], true)."] ?? '');?>";
  174. }, $output);
  175. },
  176. 'ignored'=>function(&$output, $ignored){
  177. $output = preg_replace_callback(static::$regex['ignored'], function($matches) use($ignored){
  178. return htmlentities($ignored[(int)$matches[1]] ?? '');
  179. }, $output);
  180. }
  181. ];
  182. }
  183. if(isset(static::$templates[$name])){
  184. throw new Exception("Template {$name} already exists");
  185. }
  186. if($is_file){
  187. $path = realpath($template);
  188. if(!file_exists($path)){
  189. throw new Exception("Template file {$template} doesn't exist");
  190. }
  191. $template = file_get_contents($path);
  192. }
  193. static::$parsers['include']($template);
  194. $widgets = [];
  195. static::$parsers['define']($template, $widgets);
  196. static::$parsers['widget']($template, $widgets);
  197. $this->template = $template;
  198. $this->name = $name;
  199. $this->path = static::$cachedir."/{$this->name}.".md5($this->template).'.php';
  200. static::$templates[$name] = $this;
  201. }
  202. public function __get(string $name){
  203. switch($name){
  204. case 'name':case 'template':case 'path':
  205. return $this->$name;
  206. break;
  207. default:
  208. throw new \Exception("Property {$name} doesn't exist");
  209. }
  210. }
  211. public function to_file(){
  212. file_put_contents($this->path, static::compile($this->template));
  213. }
  214. public function run(array $data) : string{
  215. $data = EArray::from($data);
  216. if($this->fire('before', $data) === false){
  217. throw new Exception("Render on template {$this->name} cancelled. Before.");
  218. }
  219. if(!file_exists($this->path)){
  220. $this->to_file();
  221. }
  222. try{
  223. $output = static::execute($this->path, $data);
  224. }catch(Exception $e){
  225. $this->to_file();
  226. $output = static::execute($this->path, $data);
  227. }
  228. if(class_exists('tidy')){
  229. if(is_null(static::$tidy)){
  230. static::$tidy = new \tidy();
  231. }
  232. $tidy = static::$tidy;
  233. $tidy->parseString($output, static::$tidyConfig);
  234. if(!$tidy->cleanRepair()){
  235. throw new \Exception($tidy->errorBuffer);
  236. }
  237. $output = "{$tidy}";
  238. }
  239. if($this->fire('after', $output) === false){
  240. throw new Exception("Render on template {$this->name} cancelled. After");
  241. }
  242. return (string)$output;
  243. }
  244. public static function from(string $name, array $data = []) : string{
  245. $template = static::get($name);
  246. if(is_null($template)){
  247. throw new Exception("Template {$name} does not exist");
  248. }
  249. return $template->run($data);
  250. }
  251. public static function get(string $name){
  252. return static::$templates[$name] ?? null;
  253. }
  254. public static function compile(string $template) : string{
  255. $ignored = [];
  256. $output = $template;
  257. // Handle {#ignore code}
  258. static::$parsers['ignore']($output, $ignored);
  259. // Handle {#include path/to/file}
  260. static::$parsers['include']($output, $ignored);
  261. // Handle {#each name}{/each}
  262. static::$parsers['each']($output);
  263. // Handle {#exist name}{#else}{/exist}
  264. static::$parsers['existelse']($output);
  265. // Handle {#exist name}{/exist}
  266. static::$parsers['exist']($output);
  267. // Handle {gettext}
  268. static::$parsers['gettext']($output);
  269. // Handle {=expression}
  270. static::$parsers['echo']($output);
  271. // Handle {? expression ?}
  272. static::$parsers['eval']($output);
  273. // Handle {@../name}
  274. static::$parsers['rawparentmatch']($output);
  275. // Handle {@name}
  276. static::$parsers['rawmatch']($output);
  277. // Handle {../name}
  278. static::$parsers['parentmatch']($output);
  279. // Handle {name}
  280. static::$parsers['match']($output);
  281. // Handle {#ignored i}
  282. static::$parsers['ignored']($output, $ignored);
  283. return $output;
  284. }
  285. public static function parse(string $template, $data) : string{
  286. $id = md5($template);
  287. if(!isset(static::$templates[$id])){
  288. new Template($id, $template);
  289. }
  290. return static::$templates[$id]->run($data);
  291. }
  292. public static function execute(string $path, $data) : string{
  293. ob_start();
  294. include($path);
  295. $output = ob_get_contents();
  296. ob_end_clean();
  297. return $output;
  298. }
  299. public static function templates(){
  300. return static::$templates;
  301. }
  302. }
  303. ?>