PhpTemplate.php 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. <?php
  2. namespace KarmaFW\Templates;
  3. use \KarmaFW\App;
  4. class PhpTemplate
  5. {
  6. protected $tpl_path = null;
  7. protected $variables = [];
  8. protected $layout = null;
  9. protected $plugins = [];
  10. public $templates_dirs = APP_DIR . '/templates';
  11. public static function createTemplate($tpl_path=null, $variables=[], $layout=null, $templates_dirs=null)
  12. {
  13. return new PhpTemplate($tpl_path, $variables, $layout, $templates_dirs);
  14. }
  15. function __construct($tpl_path=null, $variables=[], $layout=null, $templates_dirs=null)
  16. {
  17. if (is_null($templates_dirs) && defined('TPL_DIR')) {
  18. $templates_dirs = explode(':', TPL_DIR);
  19. } else if (is_string($templates_dirs)) {
  20. $templates_dirs = explode(':', $templates_dirs);
  21. } else if (is_array($templates_dirs)) {
  22. } else {
  23. $templates_dirs = null;
  24. }
  25. $this->tpl_path = $tpl_path;
  26. $this->variables = is_array($variables) ? $variables : [];
  27. $this->layout = $layout;
  28. $this->templates_dirs = $templates_dirs;
  29. // PLUGINS
  30. $template = $this;
  31. $this->addPlugin('layout', function ($key) use ($template) {
  32. // {layout my_layout_template.tpl.php}
  33. $template->layout = $key;
  34. return '';
  35. });
  36. $this->addPlugin('\/\/', function ($key) {
  37. // {// this is a comment}
  38. return '';
  39. });
  40. $this->addPlugin('#', function ($key) {
  41. // {# this is a comment}
  42. return '';
  43. });
  44. $this->addPlugin('assign', function ($key, $value) use ($template) {
  45. // {assign var_name content of my variable}
  46. $template->assign($key, $value);
  47. return '';
  48. });
  49. $this->addPlugin('tr', function ($key) {
  50. // {tr my text in english} ==> mon texte en francais
  51. return gettext($key);
  52. });
  53. $this->addPlugin('include', function ($key) use ($template) {
  54. // {include my_template.tpl.php}
  55. $template = new PhpTemplate($template->templates_dirs, $template->variables, null, $template->templates_dirs);
  56. $templatechild_content = $template->fetch($key);
  57. return $templatechild_content;
  58. });
  59. $this->addPlugin('routeUrl', function ($key, $value=[]) {
  60. // {routeUrl login_page} ===> /login
  61. $route_name = $key;
  62. $url_args = explode(' ', $value);
  63. $url = getRouteUrl($route_name, $url_args);
  64. return $url;
  65. });
  66. $this->addPlugin('block', function ($key, $matched_expr, $begin_block_offset_start, &$content) use ($template) {
  67. // {block block_name}my html content{/block} ==> assign variable $block_name with block content
  68. $begin_block_offset_end = $begin_block_offset_start + strlen($matched_expr);
  69. $end_block_offset_start = strpos($content, '{/block}', $begin_block_offset_end);
  70. if ($end_block_offset_start) {
  71. $block = isset($template->variables[$key]) ? $template->variables[$key] : '';
  72. $block = substr($content, $begin_block_offset_end, $end_block_offset_start - $begin_block_offset_end) . $block;
  73. $template->assign($key, $block);
  74. $end_block_offset_end = $end_block_offset_start + strlen("{/block}");
  75. $content = substr($content, 0, $begin_block_offset_start) . substr($content, $end_block_offset_end);
  76. }
  77. return '';
  78. });
  79. }
  80. public function fetch($tpl=null, $extra_vars=[], $layout=null, $options=[])
  81. {
  82. $tpl_dirs = [];
  83. $ts_start = microtime(true);
  84. // user templates
  85. if (! empty($this->templates_dirs)) {
  86. foreach ($this->templates_dirs as $templates_dir) {
  87. if (is_dir($templates_dir)) {
  88. $tpl_dirs[] = $templates_dir;
  89. }
  90. }
  91. }
  92. // framework templates
  93. if (is_dir(FW_DIR . '/templates')) {
  94. $tpl_dirs[] = FW_DIR . '/templates';
  95. }
  96. if (empty($tpl_dirs)) {
  97. throw new \Exception("No Templates dir. Please define TPL_DIR with a valid directory path.", 1);
  98. }
  99. if (empty($tpl)) {
  100. $tpl = $this->tpl_path;
  101. }
  102. if (empty($tpl)) {
  103. //throw new Exception("no template specified", 1);
  104. return '';
  105. }
  106. $tpl_path = false;
  107. foreach ($tpl_dirs as $tpl_dir) {
  108. $tpl_path = $tpl_dir . '/' . $tpl;
  109. if (is_file($tpl_path)) {
  110. break;
  111. }
  112. $tpl_path = null;
  113. }
  114. if (is_null($tpl_path)) {
  115. throw new \Exception("Template not found : " . $tpl . " (dirs: " . implode(" | ", $tpl_dirs) . ")", 1);
  116. }
  117. //$tpl_vars = array_merge($this->variables, $extra_vars);
  118. //extract($tpl_vars);
  119. if (! empty($extra_vars) && is_array($extra_vars)) {
  120. $this->variables = array_merge($this->variables, $extra_vars);
  121. }
  122. extract($this->variables);
  123. if ($tpl_path) {
  124. ob_start();
  125. include($tpl_path);
  126. $content = ob_get_contents();
  127. ob_end_clean();
  128. } else {
  129. $content = '';
  130. }
  131. // TODO: voir comment bien injecter cette dependance
  132. $debugbar = App::getData('debugbar');
  133. if ($debugbar) {
  134. if (isset($debugbar['templates'])) {
  135. //$debugbar['templates']->info($tpl);
  136. $debugbar_message = $debugbar['templates']->addMessage(['tpl' => $tpl]);
  137. }
  138. }
  139. // plugins. ex: {tr English text} ==> "Texte francais"
  140. if (empty($options['no_plugins'])) {
  141. if (! empty($this->plugins)) {
  142. foreach ($this->plugins as $prefix => $callback) {
  143. if ($prefix != 'block') {
  144. preg_match_all('/{' . $prefix . ' ([^} ]+)( ([^}]+))?}/', $content, $regs, PREG_SET_ORDER);
  145. foreach($regs as $reg) {
  146. $value = isset($reg[3]) ? $reg[3] : null;
  147. $replaced = $callback($reg[1], $value);
  148. $content = str_replace($reg[0], $replaced, $content);
  149. }
  150. } else {
  151. $nb_iterations = 10;
  152. while ($nb_iterations--) {
  153. preg_match('/{' . $prefix . ' ([^}]+)}/', $content, $regs, PREG_OFFSET_CAPTURE);
  154. if (! $regs) {
  155. break;
  156. }
  157. $replaced = $callback($regs[1][0], $regs[0][0], $regs[0][1], $content);
  158. $content = str_replace($regs[0][0], $replaced, $content);
  159. }
  160. }
  161. }
  162. }
  163. // variables. ex: {$user_name} ==> John
  164. if (true) {
  165. preg_match_all('/{\$([a-zA-Z0-9._\[\]\']+)}/', $content, $regs, PREG_SET_ORDER);
  166. foreach($regs as $reg) {
  167. $var = $reg[1];
  168. $var_parts = explode(".", $var);
  169. if (count($var_parts) > 1) {
  170. // $variable.key ==> $variable['key']
  171. $var = ${ array_shift($var_parts) };
  172. foreach ($var_parts as $part) {
  173. $var = $var[ $part ];
  174. }
  175. $replaced = $var;
  176. $content = str_replace($reg[0], $replaced, $content);
  177. } else if (isset(${$var})) {
  178. // $variable
  179. $replaced = ${$var};
  180. $content = str_replace($reg[0], $replaced, $content);
  181. } else {
  182. // if variable not exists, replace with empty string
  183. $content = str_replace($reg[0], '', $content);
  184. }
  185. }
  186. }
  187. }
  188. // si pas de layout defini, on recupere celui eventuel du plugin layout (c'est a dire venant d'un marker {layout xxx} dans le template)
  189. if (is_null($layout)) {
  190. $layout = $this->layout;
  191. }
  192. $layout_old = $this->layout;
  193. $this->layout = null;
  194. $ts_end = microtime(true);
  195. $duration = $ts_end - $ts_start;
  196. if (! empty($debugbar_message)) {
  197. $debugbar['templates']->updateMessage($debugbar_message, [
  198. 'tpl' => $tpl,
  199. 'layout' => $layout_old,
  200. 'content_length' => strlen($content),
  201. 'duration' => $duration,
  202. 'duration_str' => round($duration, 5),
  203. ]);
  204. }
  205. if (empty($layout)) {
  206. return $content;
  207. } else {
  208. $extra_vars['child_content'] = $content;
  209. //$extra_vars['child_content'] = '{CONTENT OF ' . $tpl . '}';
  210. $content_layout = $this->fetch($layout, $extra_vars, null, $options);
  211. return $content_layout;
  212. }
  213. }
  214. public function display($tpl=null, $extra_vars=[], $layout=null, $options=[])
  215. {
  216. echo $this->fetch($tpl, $extra_vars, $layout, $options);
  217. }
  218. public function setAllVariables($variables=[])
  219. {
  220. $this->variables = $variables;
  221. }
  222. public function setVariable($var_name, $var_value)
  223. {
  224. $this->variables[$var_name] = $var_value;
  225. }
  226. public function getTplPath()
  227. {
  228. return $this->tpl_path;
  229. }
  230. public function setTplPath($tpl_path)
  231. {
  232. $this->tpl_path = $tpl_path;
  233. return $this;
  234. }
  235. public function assign($var_name, $var_value=null)
  236. {
  237. if (is_array($var_name)) {
  238. foreach ($var_name as $k => $v) {
  239. $this->assign($k, $v);
  240. }
  241. return $this;
  242. }
  243. $this->variables[$var_name] = $var_value;
  244. return $this;
  245. }
  246. public function addPlugin($prefix, $callback)
  247. {
  248. $this->plugins[$prefix] = $callback;
  249. }
  250. }