Compiler.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2012 Justin Hileman
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Mustache Compiler class.
  12. *
  13. * This class is responsible for turning a Mustache token parse tree into normal PHP source code.
  14. */
  15. class Mustache_Compiler
  16. {
  17. private $sections;
  18. private $source;
  19. private $indentNextLine;
  20. private $customEscape;
  21. private $charset;
  22. /**
  23. * Compile a Mustache token parse tree into PHP source code.
  24. *
  25. * @param string $source Mustache Template source code
  26. * @param string $tree Parse tree of Mustache tokens
  27. * @param string $name Mustache Template class name
  28. * @param bool $customEscape (default: false)
  29. * @param string $charset (default: 'UTF-8')
  30. *
  31. * @return string Generated PHP source code
  32. */
  33. public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8')
  34. {
  35. $this->sections = array();
  36. $this->source = $source;
  37. $this->indentNextLine = true;
  38. $this->customEscape = $customEscape;
  39. $this->charset = $charset;
  40. return $this->writeCode($tree, $name);
  41. }
  42. /**
  43. * Helper function for walking the Mustache token parse tree.
  44. *
  45. * @throws InvalidArgumentException upon encountering unknown token types.
  46. *
  47. * @param array $tree Parse tree of Mustache tokens
  48. * @param int $level (default: 0)
  49. *
  50. * @return string Generated PHP source code
  51. */
  52. private function walk(array $tree, $level = 0)
  53. {
  54. $code = '';
  55. $level++;
  56. foreach ($tree as $node) {
  57. switch ($node[Mustache_Tokenizer::TYPE]) {
  58. case Mustache_Tokenizer::T_SECTION:
  59. $code .= $this->section(
  60. $node[Mustache_Tokenizer::NODES],
  61. $node[Mustache_Tokenizer::NAME],
  62. $node[Mustache_Tokenizer::INDEX],
  63. $node[Mustache_Tokenizer::END],
  64. $node[Mustache_Tokenizer::OTAG],
  65. $node[Mustache_Tokenizer::CTAG],
  66. $level
  67. );
  68. break;
  69. case Mustache_Tokenizer::T_INVERTED:
  70. $code .= $this->invertedSection(
  71. $node[Mustache_Tokenizer::NODES],
  72. $node[Mustache_Tokenizer::NAME],
  73. $level
  74. );
  75. break;
  76. case Mustache_Tokenizer::T_PARTIAL:
  77. case Mustache_Tokenizer::T_PARTIAL_2:
  78. $code .= $this->partial(
  79. $node[Mustache_Tokenizer::NAME],
  80. isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '',
  81. $level
  82. );
  83. break;
  84. case Mustache_Tokenizer::T_UNESCAPED:
  85. case Mustache_Tokenizer::T_UNESCAPED_2:
  86. $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level);
  87. break;
  88. case Mustache_Tokenizer::T_COMMENT:
  89. break;
  90. case Mustache_Tokenizer::T_ESCAPED:
  91. $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level);
  92. break;
  93. case Mustache_Tokenizer::T_TEXT:
  94. $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level);
  95. break;
  96. default:
  97. throw new InvalidArgumentException('Unknown node type: '.json_encode($node));
  98. }
  99. }
  100. return $code;
  101. }
  102. const KLASS = '<?php
  103. class %s extends Mustache_Template
  104. {
  105. public function renderInternal(Mustache_Context $context, $indent = \'\', $escape = false)
  106. {
  107. $buffer = \'\';
  108. %s
  109. if ($escape) {
  110. return %s;
  111. } else {
  112. return $buffer;
  113. }
  114. }
  115. %s
  116. }';
  117. /**
  118. * Generate Mustache Template class PHP source.
  119. *
  120. * @param array $tree Parse tree of Mustache tokens
  121. * @param string $name Mustache Template class name
  122. *
  123. * @return string Generated PHP source code
  124. */
  125. private function writeCode($tree, $name)
  126. {
  127. $code = $this->walk($tree);
  128. $sections = implode("\n", $this->sections);
  129. return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $this->getEscape('$buffer'), $sections);
  130. }
  131. const SECTION_CALL = '
  132. // %s section
  133. $buffer .= $this->section%s($context, $indent, $context->%s(%s));
  134. ';
  135. const SECTION = '
  136. private function section%s(Mustache_Context $context, $indent, $value) {
  137. $buffer = \'\';
  138. if (!is_string($value) && is_callable($value)) {
  139. $source = %s;
  140. $buffer .= $this->mustache
  141. ->loadLambda((string) call_user_func($value, $source)%s)
  142. ->renderInternal($context, $indent);
  143. } elseif (!empty($value)) {
  144. $values = $this->isIterable($value) ? $value : array($value);
  145. foreach ($values as $value) {
  146. $context->push($value);%s
  147. $context->pop();
  148. }
  149. }
  150. return $buffer;
  151. }';
  152. /**
  153. * Generate Mustache Template section PHP source.
  154. *
  155. * @param array $nodes Array of child tokens
  156. * @param string $id Section name
  157. * @param int $start Section start offset
  158. * @param int $end Section end offset
  159. * @param string $otag Current Mustache opening tag
  160. * @param string $ctag Current Mustache closing tag
  161. * @param int $level
  162. *
  163. * @return string Generated section PHP source code
  164. */
  165. private function section($nodes, $id, $start, $end, $otag, $ctag, $level)
  166. {
  167. $method = $this->getFindMethod($id);
  168. $id = var_export($id, true);
  169. $source = var_export(substr($this->source, $start, $end - $start), true);
  170. if ($otag !== '{{' || $ctag !== '}}') {
  171. $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
  172. } else {
  173. $delims = '';
  174. }
  175. $key = ucfirst(md5($delims."\n".$source));
  176. if (!isset($this->sections[$key])) {
  177. $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $source, $delims, $this->walk($nodes, 2));
  178. }
  179. return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id);
  180. }
  181. const INVERTED_SECTION = '
  182. // %s inverted section
  183. $value = $context->%s(%s);
  184. if (empty($value)) {
  185. %s
  186. }';
  187. /**
  188. * Generate Mustache Template inverted section PHP source.
  189. *
  190. * @param array $nodes Array of child tokens
  191. * @param string $id Section name
  192. * @param int $level
  193. *
  194. * @return string Generated inverted section PHP source code
  195. */
  196. private function invertedSection($nodes, $id, $level)
  197. {
  198. $method = $this->getFindMethod($id);
  199. $id = var_export($id, true);
  200. return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level));
  201. }
  202. const PARTIAL = '
  203. if ($partial = $this->mustache->loadPartial(%s)) {
  204. $buffer .= $partial->renderInternal($context, %s);
  205. }
  206. ';
  207. /**
  208. * Generate Mustache Template partial call PHP source.
  209. *
  210. * @param string $id Partial name
  211. * @param string $indent Whitespace indent to apply to partial
  212. * @param int $level
  213. *
  214. * @return string Generated partial call PHP source code
  215. */
  216. private function partial($id, $indent, $level)
  217. {
  218. return sprintf(
  219. $this->prepare(self::PARTIAL, $level),
  220. var_export($id, true),
  221. var_export($indent, true)
  222. );
  223. }
  224. const VARIABLE = '
  225. $value = $context->%s(%s);
  226. if (!is_string($value) && is_callable($value)) {
  227. $value = $this->mustache
  228. ->loadLambda((string) call_user_func($value))
  229. ->renderInternal($context, $indent);
  230. }
  231. $buffer .= %s%s;
  232. ';
  233. /**
  234. * Generate Mustache Template variable interpolation PHP source.
  235. *
  236. * @param string $id Variable name
  237. * @param boolean $escape Escape the variable value for output?
  238. * @param int $level
  239. *
  240. * @return string Generated variable interpolation PHP source
  241. */
  242. private function variable($id, $escape, $level)
  243. {
  244. $method = $this->getFindMethod($id);
  245. $id = ($method !== 'last') ? var_export($id, true) : '';
  246. $value = $escape ? $this->getEscape() : '$value';
  247. return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $this->flushIndent(), $value);
  248. }
  249. const LINE = '$buffer .= "\n";';
  250. const TEXT = '$buffer .= %s%s;';
  251. /**
  252. * Generate Mustache Template output Buffer call PHP source.
  253. *
  254. * @param string $text
  255. * @param int $level
  256. *
  257. * @return string Generated output Buffer call PHP source
  258. */
  259. private function text($text, $level)
  260. {
  261. if ($text === "\n") {
  262. $this->indentNextLine = true;
  263. return $this->prepare(self::LINE, $level);
  264. } else {
  265. return sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true));
  266. }
  267. }
  268. /**
  269. * Prepare PHP source code snippet for output.
  270. *
  271. * @param string $text
  272. * @param int $bonus Additional indent level (default: 0)
  273. * @param boolean $prependNewline Prepend a newline to the snippet? (default: true)
  274. *
  275. * @return string PHP source code snippet
  276. */
  277. private function prepare($text, $bonus = 0, $prependNewline = true)
  278. {
  279. $text = ($prependNewline ? "\n" : '').trim($text);
  280. if ($prependNewline) {
  281. $bonus++;
  282. }
  283. return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text);
  284. }
  285. const DEFAULT_ESCAPE = 'htmlspecialchars(%s, ENT_COMPAT, %s)';
  286. const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)';
  287. /**
  288. * Get the current escaper.
  289. *
  290. * @param string $value (default: '$value')
  291. *
  292. * @return string Either a custom callback, or an inline call to `htmlspecialchars`
  293. */
  294. private function getEscape($value = '$value')
  295. {
  296. if ($this->customEscape) {
  297. return sprintf(self::CUSTOM_ESCAPE, $value);
  298. } else {
  299. return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->charset, true));
  300. }
  301. }
  302. /**
  303. * Select the appropriate Context `find` method for a given $id.
  304. *
  305. * The return value will be one of `find`, `findDot` or `last`.
  306. *
  307. * @see Mustache_Context::find
  308. * @see Mustache_Context::findDot
  309. * @see Mustache_Context::last
  310. *
  311. * @param string $id Variable name
  312. *
  313. * @return string `find` method name
  314. */
  315. private function getFindMethod($id)
  316. {
  317. if ($id === '.') {
  318. return 'last';
  319. } elseif (strpos($id, '.') === false) {
  320. return 'find';
  321. } else {
  322. return 'findDot';
  323. }
  324. }
  325. const LINE_INDENT = '$indent . ';
  326. /**
  327. * Get the current $indent prefix to write to the buffer.
  328. *
  329. * @return string "$indent . " or ""
  330. */
  331. private function flushIndent()
  332. {
  333. if ($this->indentNextLine) {
  334. $this->indentNextLine = false;
  335. return self::LINE_INDENT;
  336. } else {
  337. return '';
  338. }
  339. }
  340. }