Compiler.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. <?php
  2. /*
  3. * This file is part of Mustache.php.
  4. *
  5. * (c) 2010-2014 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 $entityFlags;
  22. private $charset;
  23. private $strictCallables;
  24. private $pragmas;
  25. /**
  26. * Compile a Mustache token parse tree into PHP source code.
  27. *
  28. * @param string $source Mustache Template source code
  29. * @param string $tree Parse tree of Mustache tokens
  30. * @param string $name Mustache Template class name
  31. * @param bool $customEscape (default: false)
  32. * @param string $charset (default: 'UTF-8')
  33. * @param bool $strictCallables (default: false)
  34. * @param int $entityFlags (default: ENT_COMPAT)
  35. *
  36. * @return string Generated PHP source code
  37. */
  38. public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8', $strictCallables = false, $entityFlags = ENT_COMPAT)
  39. {
  40. $this->pragmas = array();
  41. $this->sections = array();
  42. $this->source = $source;
  43. $this->indentNextLine = true;
  44. $this->customEscape = $customEscape;
  45. $this->entityFlags = $entityFlags;
  46. $this->charset = $charset;
  47. $this->strictCallables = $strictCallables;
  48. return $this->writeCode($tree, $name);
  49. }
  50. /**
  51. * Helper function for walking the Mustache token parse tree.
  52. *
  53. * @throws Mustache_Exception_SyntaxException upon encountering unknown token types.
  54. *
  55. * @param array $tree Parse tree of Mustache tokens
  56. * @param int $level (default: 0)
  57. *
  58. * @return string Generated PHP source code
  59. */
  60. private function walk(array $tree, $level = 0)
  61. {
  62. $code = '';
  63. $level++;
  64. foreach ($tree as $node) {
  65. switch ($node[Mustache_Tokenizer::TYPE]) {
  66. case Mustache_Tokenizer::T_PRAGMA:
  67. $this->pragmas[$node[Mustache_Tokenizer::NAME]] = true;
  68. break;
  69. case Mustache_Tokenizer::T_SECTION:
  70. $code .= $this->section(
  71. $node[Mustache_Tokenizer::NODES],
  72. $node[Mustache_Tokenizer::NAME],
  73. $node[Mustache_Tokenizer::INDEX],
  74. $node[Mustache_Tokenizer::END],
  75. $node[Mustache_Tokenizer::OTAG],
  76. $node[Mustache_Tokenizer::CTAG],
  77. $level
  78. );
  79. break;
  80. case Mustache_Tokenizer::T_INVERTED:
  81. $code .= $this->invertedSection(
  82. $node[Mustache_Tokenizer::NODES],
  83. $node[Mustache_Tokenizer::NAME],
  84. $level
  85. );
  86. break;
  87. case Mustache_Tokenizer::T_PARTIAL:
  88. case Mustache_Tokenizer::T_PARTIAL_2:
  89. $code .= $this->partial(
  90. $node[Mustache_Tokenizer::NAME],
  91. isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '',
  92. $level
  93. );
  94. break;
  95. case Mustache_Tokenizer::T_UNESCAPED:
  96. case Mustache_Tokenizer::T_UNESCAPED_2:
  97. $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level);
  98. break;
  99. case Mustache_Tokenizer::T_COMMENT:
  100. break;
  101. case Mustache_Tokenizer::T_ESCAPED:
  102. $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level);
  103. break;
  104. case Mustache_Tokenizer::T_TEXT:
  105. $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level);
  106. break;
  107. default:
  108. throw new Mustache_Exception_SyntaxException(sprintf('Unknown token type: %s', $node[Mustache_Tokenizer::TYPE]), $node);
  109. }
  110. }
  111. return $code;
  112. }
  113. const KLASS = '<?php
  114. class %s extends Mustache_Template
  115. {
  116. private $lambdaHelper;%s
  117. public function renderInternal(Mustache_Context $context, $indent = \'\')
  118. {
  119. $this->lambdaHelper = new Mustache_LambdaHelper($this->mustache, $context);
  120. $buffer = \'\';
  121. %s
  122. return $buffer;
  123. }
  124. %s
  125. }';
  126. const KLASS_NO_LAMBDAS = '<?php
  127. class %s extends Mustache_Template
  128. {%s
  129. public function renderInternal(Mustache_Context $context, $indent = \'\')
  130. {
  131. $buffer = \'\';
  132. %s
  133. return $buffer;
  134. }
  135. }';
  136. const STRICT_CALLABLE = 'protected $strictCallables = true;';
  137. /**
  138. * Generate Mustache Template class PHP source.
  139. *
  140. * @param array $tree Parse tree of Mustache tokens
  141. * @param string $name Mustache Template class name
  142. *
  143. * @return string Generated PHP source code
  144. */
  145. private function writeCode($tree, $name)
  146. {
  147. $code = $this->walk($tree);
  148. $sections = implode("\n", $this->sections);
  149. $klass = empty($this->sections) ? self::KLASS_NO_LAMBDAS : self::KLASS;
  150. $callable = $this->strictCallables ? $this->prepare(self::STRICT_CALLABLE) : '';
  151. return sprintf($this->prepare($klass, 0, false, true), $name, $callable, $code, $sections);
  152. }
  153. const SECTION_CALL = '
  154. // %s section
  155. $value = $context->%s(%s);%s
  156. $buffer .= $this->section%s($context, $indent, $value);
  157. ';
  158. const SECTION = '
  159. private function section%s(Mustache_Context $context, $indent, $value)
  160. {
  161. $buffer = \'\';
  162. if (%s) {
  163. $source = %s;
  164. $result = call_user_func($value, $source, $this->lambdaHelper);
  165. if (strpos($result, \'{{\') === false) {
  166. $buffer .= $result;
  167. } else {
  168. $buffer .= $this->mustache
  169. ->loadLambda((string) $result%s)
  170. ->renderInternal($context);
  171. }
  172. } elseif (!empty($value)) {
  173. $values = $this->isIterable($value) ? $value : array($value);
  174. foreach ($values as $value) {
  175. $context->push($value);%s
  176. $context->pop();
  177. }
  178. }
  179. return $buffer;
  180. }';
  181. /**
  182. * Generate Mustache Template section PHP source.
  183. *
  184. * @param array $nodes Array of child tokens
  185. * @param string $id Section name
  186. * @param int $start Section start offset
  187. * @param int $end Section end offset
  188. * @param string $otag Current Mustache opening tag
  189. * @param string $ctag Current Mustache closing tag
  190. * @param int $level
  191. *
  192. * @return string Generated section PHP source code
  193. */
  194. private function section($nodes, $id, $start, $end, $otag, $ctag, $level)
  195. {
  196. $filters = '';
  197. if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
  198. list($id, $filters) = $this->getFilters($id, $level);
  199. }
  200. $method = $this->getFindMethod($id);
  201. $id = var_export($id, true);
  202. $source = var_export(substr($this->source, $start, $end - $start), true);
  203. $callable = $this->getCallable();
  204. if ($otag !== '{{' || $ctag !== '}}') {
  205. $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true);
  206. } else {
  207. $delims = '';
  208. }
  209. $key = ucfirst(md5($delims."\n".$source));
  210. if (!isset($this->sections[$key])) {
  211. $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $callable, $source, $delims, $this->walk($nodes, 2));
  212. }
  213. return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $method, $id, $filters, $key);
  214. }
  215. const INVERTED_SECTION = '
  216. // %s inverted section
  217. $value = $context->%s(%s);%s
  218. if (empty($value)) {
  219. %s
  220. }';
  221. /**
  222. * Generate Mustache Template inverted section PHP source.
  223. *
  224. * @param array $nodes Array of child tokens
  225. * @param string $id Section name
  226. * @param int $level
  227. *
  228. * @return string Generated inverted section PHP source code
  229. */
  230. private function invertedSection($nodes, $id, $level)
  231. {
  232. $filters = '';
  233. if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
  234. list($id, $filters) = $this->getFilters($id, $level);
  235. }
  236. $method = $this->getFindMethod($id);
  237. $id = var_export($id, true);
  238. return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $filters, $this->walk($nodes, $level));
  239. }
  240. const PARTIAL = '
  241. if ($partial = $this->mustache->loadPartial(%s)) {
  242. $buffer .= $partial->renderInternal($context, $indent . %s);
  243. }
  244. ';
  245. /**
  246. * Generate Mustache Template partial call PHP source.
  247. *
  248. * @param string $id Partial name
  249. * @param string $indent Whitespace indent to apply to partial
  250. * @param int $level
  251. *
  252. * @return string Generated partial call PHP source code
  253. */
  254. private function partial($id, $indent, $level)
  255. {
  256. return sprintf(
  257. $this->prepare(self::PARTIAL, $level),
  258. var_export($id, true),
  259. var_export($indent, true)
  260. );
  261. }
  262. const VARIABLE = '
  263. $value = $this->resolveValue($context->%s(%s), $context, $indent);%s
  264. $buffer .= %s%s;
  265. ';
  266. /**
  267. * Generate Mustache Template variable interpolation PHP source.
  268. *
  269. * @param string $id Variable name
  270. * @param boolean $escape Escape the variable value for output?
  271. * @param int $level
  272. *
  273. * @return string Generated variable interpolation PHP source
  274. */
  275. private function variable($id, $escape, $level)
  276. {
  277. $filters = '';
  278. if (isset($this->pragmas[Mustache_Engine::PRAGMA_FILTERS])) {
  279. list($id, $filters) = $this->getFilters($id, $level);
  280. }
  281. $method = $this->getFindMethod($id);
  282. $id = ($method !== 'last') ? var_export($id, true) : '';
  283. $value = $escape ? $this->getEscape() : '$value';
  284. return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $filters, $this->flushIndent(), $value);
  285. }
  286. /**
  287. * Generate Mustache Template variable filtering PHP source.
  288. *
  289. * @param string $id Variable name
  290. * @param int $level
  291. *
  292. * @return string Generated variable filtering PHP source
  293. */
  294. private function getFilters($id, $level)
  295. {
  296. $filters = array_map('trim', explode('|', $id));
  297. $id = array_shift($filters);
  298. return array($id, $this->getFilter($filters, $level));
  299. }
  300. const FILTER = '
  301. $filter = $context->%s(%s);
  302. if (!(%s)) {
  303. throw new Mustache_Exception_UnknownFilterException(%s);
  304. }
  305. $value = call_user_func($filter, $value);%s
  306. ';
  307. /**
  308. * Generate PHP source for a single filter.
  309. *
  310. * @param array $filters
  311. * @param int $level
  312. *
  313. * @return string Generated filter PHP source
  314. */
  315. private function getFilter(array $filters, $level)
  316. {
  317. if (empty($filters)) {
  318. return '';
  319. }
  320. $name = array_shift($filters);
  321. $method = $this->getFindMethod($name);
  322. $filter = ($method !== 'last') ? var_export($name, true) : '';
  323. $callable = $this->getCallable('$filter');
  324. $msg = var_export($name, true);
  325. return sprintf($this->prepare(self::FILTER, $level), $method, $filter, $callable, $msg, $this->getFilter($filters, $level));
  326. }
  327. const LINE = '$buffer .= "\n";';
  328. const TEXT = '$buffer .= %s%s;';
  329. /**
  330. * Generate Mustache Template output Buffer call PHP source.
  331. *
  332. * @param string $text
  333. * @param int $level
  334. *
  335. * @return string Generated output Buffer call PHP source
  336. */
  337. private function text($text, $level)
  338. {
  339. $indentNextLine = (substr($text, -1) === "\n");
  340. $code = sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true));
  341. $this->indentNextLine = $indentNextLine;
  342. return $code;
  343. }
  344. /**
  345. * Prepare PHP source code snippet for output.
  346. *
  347. * @param string $text
  348. * @param int $bonus Additional indent level (default: 0)
  349. * @param boolean $prependNewline Prepend a newline to the snippet? (default: true)
  350. * @param boolean $appendNewline Append a newline to the snippet? (default: false)
  351. *
  352. * @return string PHP source code snippet
  353. */
  354. private function prepare($text, $bonus = 0, $prependNewline = true, $appendNewline = false)
  355. {
  356. $text = ($prependNewline ? "\n" : '').trim($text);
  357. if ($prependNewline) {
  358. $bonus++;
  359. }
  360. if ($appendNewline) {
  361. $text .= "\n";
  362. }
  363. return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text);
  364. }
  365. const DEFAULT_ESCAPE = 'htmlspecialchars(%s, %s, %s)';
  366. const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)';
  367. /**
  368. * Get the current escaper.
  369. *
  370. * @param string $value (default: '$value')
  371. *
  372. * @return string Either a custom callback, or an inline call to `htmlspecialchars`
  373. */
  374. private function getEscape($value = '$value')
  375. {
  376. if ($this->customEscape) {
  377. return sprintf(self::CUSTOM_ESCAPE, $value);
  378. } else {
  379. return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->entityFlags, true), var_export($this->charset, true));
  380. }
  381. }
  382. /**
  383. * Select the appropriate Context `find` method for a given $id.
  384. *
  385. * The return value will be one of `find`, `findDot` or `last`.
  386. *
  387. * @see Mustache_Context::find
  388. * @see Mustache_Context::findDot
  389. * @see Mustache_Context::last
  390. *
  391. * @param string $id Variable name
  392. *
  393. * @return string `find` method name
  394. */
  395. private function getFindMethod($id)
  396. {
  397. if ($id === '.') {
  398. return 'last';
  399. } elseif (strpos($id, '.') === false) {
  400. return 'find';
  401. } else {
  402. return 'findDot';
  403. }
  404. }
  405. const IS_CALLABLE = '!is_string(%s) && is_callable(%s)';
  406. const STRICT_IS_CALLABLE = 'is_object(%s) && is_callable(%s)';
  407. private function getCallable($variable = '$value')
  408. {
  409. $tpl = $this->strictCallables ? self::STRICT_IS_CALLABLE : self::IS_CALLABLE;
  410. return sprintf($tpl, $variable, $variable);
  411. }
  412. const LINE_INDENT = '$indent . ';
  413. /**
  414. * Get the current $indent prefix to write to the buffer.
  415. *
  416. * @return string "$indent . " or ""
  417. */
  418. private function flushIndent()
  419. {
  420. if (!$this->indentNextLine) {
  421. return '';
  422. }
  423. $this->indentNextLine = false;
  424. return self::LINE_INDENT;
  425. }
  426. }