Mustache.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. <?php
  2. /**
  3. * A Mustache implementation in PHP.
  4. *
  5. * {@link http://defunkt.github.com/mustache}
  6. *
  7. * Mustache is a framework-agnostic logic-less templating language. It enforces separation of view
  8. * logic from template files. In fact, it is not even possible to embed logic in the template.
  9. *
  10. * This is very, very rad.
  11. *
  12. * @author Justin Hileman {@link http://justinhileman.com}
  13. */
  14. class Mustache {
  15. const VERSION = '1.0.0';
  16. const SPEC_VERSION = '1.1.2';
  17. /**
  18. * Should this Mustache throw exceptions when it finds unexpected tags?
  19. *
  20. * @see self::_throwsException()
  21. */
  22. protected $_throwsExceptions = array(
  23. MustacheException::UNKNOWN_VARIABLE => false,
  24. MustacheException::UNCLOSED_SECTION => true,
  25. MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  26. MustacheException::UNKNOWN_PARTIAL => false,
  27. MustacheException::UNKNOWN_PRAGMA => true,
  28. );
  29. // Override the escaper function. Defaults to `htmlspecialchars`.
  30. protected $_escape;
  31. // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8.
  32. protected $_charset = 'UTF-8';
  33. /**
  34. * Pragmas are macro-like directives that, when invoked, change the behavior or
  35. * syntax of Mustache.
  36. *
  37. * They should be considered extremely experimental. Most likely their implementation
  38. * will change in the future.
  39. */
  40. /**
  41. * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}}
  42. * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be
  43. * escaped while the {{{unescaped}}} tag will be escaped.
  44. *
  45. * Pragmas apply only to the current template. Partials, even those included after the
  46. * {{%UNESCAPED}} call, will need their own pragma declaration.
  47. *
  48. * This may be useful in non-HTML Mustache situations.
  49. */
  50. const PRAGMA_UNESCAPED = 'UNESCAPED';
  51. /**
  52. * Constants used for section and tag RegEx
  53. */
  54. const SECTION_TYPES = '\^#\/';
  55. const TAG_TYPES = '#\^\/=!<>\\{&';
  56. protected $_otag = '{{';
  57. protected $_ctag = '}}';
  58. protected $_tagRegEx;
  59. protected $_template = '';
  60. protected $_context = array();
  61. protected $_partials = array();
  62. protected $_pragmas = array();
  63. protected $_pragmasImplemented = array(
  64. self::PRAGMA_UNESCAPED
  65. );
  66. protected $_localPragmas = array();
  67. /**
  68. * Mustache class constructor.
  69. *
  70. * This method accepts a $template string and a $view object. Optionally, pass an associative
  71. * array of partials as well.
  72. *
  73. * Passing an $options array allows overriding certain Mustache options during instantiation:
  74. *
  75. * $options = array(
  76. * // `escape` -- custom escaper callback; must be callable.
  77. * 'escape' => function($text) {
  78. * return htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
  79. * },
  80. *
  81. * // `charset` -- must be supported by `htmlspecialentities()`. defaults to 'UTF-8'
  82. * 'charset' => 'ISO-8859-1',
  83. *
  84. * // opening and closing delimiters, as an array or a space-separated string
  85. * 'delimiters' => '<% %>',
  86. *
  87. * // an array of pragmas to enable/disable
  88. * 'pragmas' => array(
  89. * Mustache::PRAGMA_UNESCAPED => true
  90. * ),
  91. *
  92. * // an array of thrown exceptions to enable/disable
  93. * 'throws_exceptions' => array(
  94. * MustacheException::UNKNOWN_VARIABLE => false,
  95. * MustacheException::UNCLOSED_SECTION => true,
  96. * MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  97. * MustacheException::UNKNOWN_PARTIAL => false,
  98. * MustacheException::UNKNOWN_PRAGMA => true,
  99. * ),
  100. * );
  101. *
  102. * @access public
  103. * @param string $template (default: null)
  104. * @param mixed $view (default: null)
  105. * @param array $partials (default: null)
  106. * @param array $options (default: array())
  107. * @return void
  108. */
  109. public function __construct($template = null, $view = null, $partials = null, array $options = null) {
  110. if ($template !== null) $this->_template = $template;
  111. if ($partials !== null) $this->_partials = $partials;
  112. if ($view !== null) $this->_context = array($view);
  113. if ($options !== null) $this->_setOptions($options);
  114. }
  115. /**
  116. * Helper function for setting options from constructor args.
  117. *
  118. * @access protected
  119. * @param array $options
  120. * @return void
  121. */
  122. protected function _setOptions(array $options) {
  123. if (isset($options['escape'])) {
  124. if (!is_callable($options['escape'])) {
  125. throw new InvalidArgumentException('Mustache constructor "escape" option must be callable');
  126. }
  127. $this->_escape = $options['escape'];
  128. }
  129. if (isset($options['charset'])) {
  130. $this->_charset = $options['charset'];
  131. }
  132. if (isset($options['delimiters'])) {
  133. $delims = $options['delimiters'];
  134. if (!is_array($delims)) {
  135. $delims = array_map('trim', explode(' ', $delims, 2));
  136. }
  137. $this->_otag = $delims[0];
  138. $this->_ctag = $delims[1];
  139. }
  140. if (isset($options['pragmas'])) {
  141. foreach ($options['pragmas'] as $pragma_name => $pragma_value) {
  142. if (!in_array($pragma_name, $this->_pragmasImplemented, true)) {
  143. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  144. }
  145. }
  146. $this->_pragmas = $options['pragmas'];
  147. }
  148. if (isset($options['throws_exceptions'])) {
  149. foreach ($options['throws_exceptions'] as $exception => $value) {
  150. $this->_throwsExceptions[$exception] = $value;
  151. }
  152. }
  153. }
  154. /**
  155. * Mustache class clone method.
  156. *
  157. * A cloned Mustache instance should have pragmas, delimeters and root context
  158. * reset to default values.
  159. *
  160. * @access public
  161. * @return void
  162. */
  163. public function __clone() {
  164. $this->_otag = '{{';
  165. $this->_ctag = '}}';
  166. $this->_localPragmas = array();
  167. if ($keys = array_keys($this->_context)) {
  168. $last = array_pop($keys);
  169. if ($this->_context[$last] instanceof Mustache) {
  170. $this->_context[$last] =& $this;
  171. }
  172. }
  173. }
  174. /**
  175. * Render the given template and view object.
  176. *
  177. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  178. * Optionally, pass an associative array of partials as well.
  179. *
  180. * @access public
  181. * @param string $template (default: null)
  182. * @param mixed $view (default: null)
  183. * @param array $partials (default: null)
  184. * @return string Rendered Mustache template.
  185. */
  186. public function render($template = null, $view = null, $partials = null) {
  187. if ($template === null) $template = $this->_template;
  188. if ($partials !== null) $this->_partials = $partials;
  189. $otag_orig = $this->_otag;
  190. $ctag_orig = $this->_ctag;
  191. if ($view) {
  192. $this->_context = array($view);
  193. } else if (empty($this->_context)) {
  194. $this->_context = array($this);
  195. }
  196. $template = $this->_renderPragmas($template);
  197. $template = $this->_renderTemplate($template);
  198. $this->_otag = $otag_orig;
  199. $this->_ctag = $ctag_orig;
  200. return $template;
  201. }
  202. /**
  203. * Wrap the render() function for string conversion.
  204. *
  205. * @access public
  206. * @return string
  207. */
  208. public function __toString() {
  209. // PHP doesn't like exceptions in __toString.
  210. // catch any exceptions and convert them to strings.
  211. try {
  212. $result = $this->render();
  213. return $result;
  214. } catch (Exception $e) {
  215. return "Error rendering mustache: " . $e->getMessage();
  216. }
  217. }
  218. /**
  219. * Internal render function, used for recursive calls.
  220. *
  221. * @access protected
  222. * @param string $template
  223. * @return string Rendered Mustache template.
  224. */
  225. protected function _renderTemplate($template) {
  226. if ($section = $this->_findSection($template)) {
  227. list($before, $type, $tag_name, $content, $after) = $section;
  228. $rendered_before = $this->_renderTags($before);
  229. $rendered_content = '';
  230. $val = $this->_getVariable($tag_name);
  231. switch($type) {
  232. // inverted section
  233. case '^':
  234. if (empty($val)) {
  235. $rendered_content = $this->_renderTemplate($content);
  236. }
  237. break;
  238. // regular section
  239. case '#':
  240. // higher order sections
  241. if ($this->_varIsCallable($val)) {
  242. $rendered_content = $this->_renderTemplate(call_user_func($val, $content));
  243. } else if ($this->_varIsIterable($val)) {
  244. foreach ($val as $local_context) {
  245. $this->_pushContext($local_context);
  246. $rendered_content .= $this->_renderTemplate($content);
  247. $this->_popContext();
  248. }
  249. } else if ($val) {
  250. if (is_array($val) || is_object($val)) {
  251. $this->_pushContext($val);
  252. $rendered_content = $this->_renderTemplate($content);
  253. $this->_popContext();
  254. } else {
  255. $rendered_content = $this->_renderTemplate($content);
  256. }
  257. }
  258. break;
  259. }
  260. return $rendered_before . $rendered_content . $this->_renderTemplate($after);
  261. }
  262. return $this->_renderTags($template);
  263. }
  264. /**
  265. * Prepare a section RegEx string for the given opening/closing tags.
  266. *
  267. * @access protected
  268. * @param string $otag
  269. * @param string $ctag
  270. * @return string
  271. */
  272. protected function _prepareSectionRegEx($otag, $ctag) {
  273. return sprintf(
  274. '/(?:(?<=\\n)[ \\t]*)?%s(?:(?P<type>[%s])(?P<tag_name>.+?)|=(?P<delims>.*?)=)%s\\n?/s',
  275. preg_quote($otag, '/'),
  276. self::SECTION_TYPES,
  277. preg_quote($ctag, '/')
  278. );
  279. }
  280. /**
  281. * Extract the first section from $template.
  282. *
  283. * @access protected
  284. * @param string $template
  285. * @return array $before, $type, $tag_name, $content and $after
  286. */
  287. protected function _findSection($template) {
  288. $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag);
  289. $section_start = null;
  290. $section_type = null;
  291. $content_start = null;
  292. $search_offset = 0;
  293. $section_stack = array();
  294. $matches = array();
  295. while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) {
  296. if (isset($matches['delims'][0])) {
  297. list($otag, $ctag) = explode(' ', $matches['delims'][0]);
  298. $regEx = $this->_prepareSectionRegEx($otag, $ctag);
  299. $search_offset = $matches[0][1] + strlen($matches[0][0]);
  300. continue;
  301. }
  302. $match = $matches[0][0];
  303. $offset = $matches[0][1];
  304. $type = $matches['type'][0];
  305. $tag_name = trim($matches['tag_name'][0]);
  306. $search_offset = $offset + strlen($match);
  307. switch ($type) {
  308. case '^':
  309. case '#':
  310. if (empty($section_stack)) {
  311. $section_start = $offset;
  312. $section_type = $type;
  313. $content_start = $search_offset;
  314. }
  315. array_push($section_stack, $tag_name);
  316. break;
  317. case '/':
  318. if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) {
  319. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  320. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  321. }
  322. }
  323. if (empty($section_stack)) {
  324. // $before, $type, $tag_name, $content, $after
  325. return array(
  326. substr($template, 0, $section_start),
  327. $section_type,
  328. $tag_name,
  329. substr($template, $content_start, $offset - $content_start),
  330. substr($template, $search_offset),
  331. );
  332. }
  333. break;
  334. }
  335. }
  336. if (!empty($section_stack)) {
  337. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  338. throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION);
  339. }
  340. }
  341. }
  342. /**
  343. * Prepare a pragma RegEx for the given opening/closing tags.
  344. *
  345. * @access protected
  346. * @param string $otag
  347. * @param string $ctag
  348. * @return string
  349. */
  350. protected function _preparePragmaRegEx($otag, $ctag) {
  351. return sprintf(
  352. '/%s%%\\s*(?P<pragma_name>[\\w_-]+)(?P<options_string>(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s',
  353. preg_quote($otag, '/'),
  354. preg_quote($ctag, '/')
  355. );
  356. }
  357. /**
  358. * Initialize pragmas and remove all pragma tags.
  359. *
  360. * @access protected
  361. * @param string $template
  362. * @return string
  363. */
  364. protected function _renderPragmas($template) {
  365. $this->_localPragmas = $this->_pragmas;
  366. // no pragmas
  367. if (strpos($template, $this->_otag . '%') === false) {
  368. return $template;
  369. }
  370. $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag);
  371. return preg_replace_callback($regEx, array($this, '_renderPragma'), $template);
  372. }
  373. /**
  374. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  375. *
  376. * @access protected
  377. * @param mixed $matches
  378. * @return void
  379. * @throws MustacheException unknown pragma
  380. */
  381. protected function _renderPragma($matches) {
  382. $pragma = $matches[0];
  383. $pragma_name = $matches['pragma_name'];
  384. $options_string = $matches['options_string'];
  385. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  386. if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
  387. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  388. } else {
  389. return '';
  390. }
  391. }
  392. $options = array();
  393. foreach (explode(' ', trim($options_string)) as $o) {
  394. if ($p = trim($o)) {
  395. $p = explode('=', $p);
  396. $options[$p[0]] = $p[1];
  397. }
  398. }
  399. if (empty($options)) {
  400. $this->_localPragmas[$pragma_name] = true;
  401. } else {
  402. $this->_localPragmas[$pragma_name] = $options;
  403. }
  404. return '';
  405. }
  406. /**
  407. * Check whether this Mustache has a specific pragma.
  408. *
  409. * @access protected
  410. * @param string $pragma_name
  411. * @return bool
  412. */
  413. protected function _hasPragma($pragma_name) {
  414. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  415. return true;
  416. } else {
  417. return false;
  418. }
  419. }
  420. /**
  421. * Return pragma options, if any.
  422. *
  423. * @access protected
  424. * @param string $pragma_name
  425. * @return mixed
  426. * @throws MustacheException Unknown pragma
  427. */
  428. protected function _getPragmaOptions($pragma_name) {
  429. if (!$this->_hasPragma($pragma_name)) {
  430. if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) {
  431. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  432. }
  433. }
  434. return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array();
  435. }
  436. /**
  437. * Check whether this Mustache instance throws a given exception.
  438. *
  439. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  440. *
  441. * @access protected
  442. * @param mixed $exception
  443. * @return void
  444. */
  445. protected function _throwsException($exception) {
  446. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  447. }
  448. /**
  449. * Prepare a tag RegEx for the given opening/closing tags.
  450. *
  451. * @access protected
  452. * @param string $otag
  453. * @param string $ctag
  454. * @return string
  455. */
  456. protected function _prepareTagRegEx($otag, $ctag, $first = false) {
  457. return sprintf(
  458. '/(?P<leading>(?:%s\\r?\\n)[ \\t]*)?%s(?P<type>[%s]?)(?P<tag_name>.+?)(?:\\2|})?%s(?P<trailing>\\s*(?:\\r?\\n|\\Z))?/s',
  459. ($first ? '\\A|' : ''),
  460. preg_quote($otag, '/'),
  461. self::TAG_TYPES,
  462. preg_quote($ctag, '/')
  463. );
  464. }
  465. /**
  466. * Loop through and render individual Mustache tags.
  467. *
  468. * @access protected
  469. * @param string $template
  470. * @return void
  471. */
  472. protected function _renderTags($template) {
  473. if (strpos($template, $this->_otag) === false) {
  474. return $template;
  475. }
  476. $first = true;
  477. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true);
  478. $html = '';
  479. $matches = array();
  480. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  481. $tag = $matches[0][0];
  482. $offset = $matches[0][1];
  483. $modifier = $matches['type'][0];
  484. $tag_name = trim($matches['tag_name'][0]);
  485. if (isset($matches['leading']) && $matches['leading'][1] > -1) {
  486. $leading = $matches['leading'][0];
  487. } else {
  488. $leading = null;
  489. }
  490. if (isset($matches['trailing']) && $matches['trailing'][1] > -1) {
  491. $trailing = $matches['trailing'][0];
  492. } else {
  493. $trailing = null;
  494. }
  495. $html .= substr($template, 0, $offset);
  496. $next_offset = $offset + strlen($tag);
  497. if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) {
  498. $next_offset++;
  499. }
  500. $template = substr($template, $next_offset);
  501. $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing);
  502. if ($first == true) {
  503. $first = false;
  504. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  505. }
  506. }
  507. return $html . $template;
  508. }
  509. /**
  510. * Render the named tag, given the specified modifier.
  511. *
  512. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  513. * `{` or `&` (don't escape output), or none (render escaped output).
  514. *
  515. * @access protected
  516. * @param string $modifier
  517. * @param string $tag_name
  518. * @param string $leading Whitespace
  519. * @param string $trailing Whitespace
  520. * @throws MustacheException Unmatched section tag encountered.
  521. * @return string
  522. */
  523. protected function _renderTag($modifier, $tag_name, $leading, $trailing) {
  524. switch ($modifier) {
  525. case '=':
  526. return $this->_changeDelimiter($tag_name, $leading, $trailing);
  527. break;
  528. case '!':
  529. return $this->_renderComment($tag_name, $leading, $trailing);
  530. break;
  531. case '>':
  532. case '<':
  533. return $this->_renderPartial($tag_name, $leading, $trailing);
  534. break;
  535. case '{':
  536. // strip the trailing } ...
  537. if ($tag_name[(strlen($tag_name) - 1)] == '}') {
  538. $tag_name = substr($tag_name, 0, -1);
  539. }
  540. case '&':
  541. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  542. return $this->_renderEscaped($tag_name, $leading, $trailing);
  543. } else {
  544. return $this->_renderUnescaped($tag_name, $leading, $trailing);
  545. }
  546. break;
  547. case '#':
  548. case '^':
  549. case '/':
  550. // remove any leftover section tags
  551. return $leading . $trailing;
  552. break;
  553. default:
  554. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  555. return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing);
  556. } else {
  557. return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing);
  558. }
  559. break;
  560. }
  561. }
  562. /**
  563. * Returns true if any of its args contains the "\r" character.
  564. *
  565. * @access protected
  566. * @param string $str
  567. * @return boolean
  568. */
  569. protected function _stringHasR($str) {
  570. foreach (func_get_args() as $arg) {
  571. if (strpos($arg, "\r") !== false) {
  572. return true;
  573. }
  574. }
  575. return false;
  576. }
  577. /**
  578. * Escape and return the requested tag.
  579. *
  580. * @access protected
  581. * @param string $tag_name
  582. * @param string $leading Whitespace
  583. * @param string $trailing Whitespace
  584. * @return string
  585. */
  586. protected function _renderEscaped($tag_name, $leading, $trailing) {
  587. $value = $this->_renderUnescaped($tag_name, '', '');
  588. if (isset($this->_escape)) {
  589. $rendered = call_user_func($this->_escape, $value);
  590. } else {
  591. $rendered = htmlentities($value, ENT_COMPAT, $this->_charset);
  592. }
  593. return $leading . $rendered . $trailing;
  594. }
  595. /**
  596. * Render a comment (i.e. return an empty string).
  597. *
  598. * @access protected
  599. * @param string $tag_name
  600. * @param string $leading Whitespace
  601. * @param string $trailing Whitespace
  602. * @return string
  603. */
  604. protected function _renderComment($tag_name, $leading, $trailing) {
  605. if ($leading !== null && $trailing !== null) {
  606. if (strpos($leading, "\n") === false) {
  607. return '';
  608. }
  609. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  610. }
  611. return $leading . $trailing;
  612. }
  613. /**
  614. * Return the requested tag unescaped.
  615. *
  616. * @access protected
  617. * @param string $tag_name
  618. * @param string $leading Whitespace
  619. * @param string $trailing Whitespace
  620. * @return string
  621. */
  622. protected function _renderUnescaped($tag_name, $leading, $trailing) {
  623. $val = $this->_getVariable($tag_name);
  624. if ($this->_varIsCallable($val)) {
  625. $val = $this->_renderTemplate(call_user_func($val));
  626. }
  627. return $leading . $val . $trailing;
  628. }
  629. /**
  630. * Render the requested partial.
  631. *
  632. * @access protected
  633. * @param string $tag_name
  634. * @param string $leading Whitespace
  635. * @param string $trailing Whitespace
  636. * @return string
  637. */
  638. protected function _renderPartial($tag_name, $leading, $trailing) {
  639. $partial = $this->_getPartial($tag_name);
  640. if ($leading !== null && $trailing !== null) {
  641. $whitespace = trim($leading, "\r\n");
  642. $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial);
  643. }
  644. $view = clone($this);
  645. if ($leading !== null && $trailing !== null) {
  646. return $leading . $view->render($partial);
  647. } else {
  648. return $leading . $view->render($partial) . $trailing;
  649. }
  650. }
  651. /**
  652. * Change the Mustache tag delimiter. This method also replaces this object's current
  653. * tag RegEx with one using the new delimiters.
  654. *
  655. * @access protected
  656. * @param string $tag_name
  657. * @param string $leading Whitespace
  658. * @param string $trailing Whitespace
  659. * @return string
  660. */
  661. protected function _changeDelimiter($tag_name, $leading, $trailing) {
  662. list($otag, $ctag) = explode(' ', $tag_name);
  663. $this->_otag = $otag;
  664. $this->_ctag = $ctag;
  665. $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag);
  666. if ($leading !== null && $trailing !== null) {
  667. if (strpos($leading, "\n") === false) {
  668. return '';
  669. }
  670. return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n";
  671. }
  672. return $leading . $trailing;
  673. }
  674. /**
  675. * Push a local context onto the stack.
  676. *
  677. * @access protected
  678. * @param array &$local_context
  679. * @return void
  680. */
  681. protected function _pushContext(&$local_context) {
  682. $new = array();
  683. $new[] =& $local_context;
  684. foreach (array_keys($this->_context) as $key) {
  685. $new[] =& $this->_context[$key];
  686. }
  687. $this->_context = $new;
  688. }
  689. /**
  690. * Remove the latest context from the stack.
  691. *
  692. * @access protected
  693. * @return void
  694. */
  695. protected function _popContext() {
  696. $new = array();
  697. $keys = array_keys($this->_context);
  698. array_shift($keys);
  699. foreach ($keys as $key) {
  700. $new[] =& $this->_context[$key];
  701. }
  702. $this->_context = $new;
  703. }
  704. /**
  705. * Get a variable from the context array.
  706. *
  707. * If the view is an array, returns the value with array key $tag_name.
  708. * If the view is an object, this will check for a public member variable
  709. * named $tag_name. If none is available, this method will execute and return
  710. * any class method named $tag_name. Failing all of the above, this method will
  711. * return an empty string.
  712. *
  713. * @access protected
  714. * @param string $tag_name
  715. * @throws MustacheException Unknown variable name.
  716. * @return string
  717. */
  718. protected function _getVariable($tag_name) {
  719. if ($tag_name === '.') {
  720. return $this->_context[0];
  721. } else if (strpos($tag_name, '.') !== false) {
  722. $chunks = explode('.', $tag_name);
  723. $first = array_shift($chunks);
  724. $ret = $this->_findVariableInContext($first, $this->_context);
  725. foreach ($chunks as $next) {
  726. // Slice off a chunk of context for dot notation traversal.
  727. $c = array($ret);
  728. $ret = $this->_findVariableInContext($next, $c);
  729. }
  730. return $ret;
  731. } else {
  732. return $this->_findVariableInContext($tag_name, $this->_context);
  733. }
  734. }
  735. /**
  736. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  737. * variable traversal for dot notation.
  738. *
  739. * @access protected
  740. * @param string $tag_name
  741. * @param array $context
  742. * @throws MustacheException Unknown variable name.
  743. * @return string
  744. */
  745. protected function _findVariableInContext($tag_name, $context) {
  746. foreach ($context as $view) {
  747. if (is_object($view)) {
  748. if (method_exists($view, $tag_name)) {
  749. return $view->$tag_name();
  750. } else if (isset($view->$tag_name)) {
  751. return $view->$tag_name;
  752. }
  753. } else if (is_array($view) && array_key_exists($tag_name, $view)) {
  754. return $view[$tag_name];
  755. }
  756. }
  757. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  758. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  759. } else {
  760. return '';
  761. }
  762. }
  763. /**
  764. * Retrieve the partial corresponding to the requested tag name.
  765. *
  766. * Silently fails (i.e. returns '') when the requested partial is not found.
  767. *
  768. * @access protected
  769. * @param string $tag_name
  770. * @throws MustacheException Unknown partial name.
  771. * @return string
  772. */
  773. protected function _getPartial($tag_name) {
  774. if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) {
  775. return $this->_partials[$tag_name];
  776. }
  777. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  778. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  779. } else {
  780. return '';
  781. }
  782. }
  783. /**
  784. * Check whether the given $var should be iterated (i.e. in a section context).
  785. *
  786. * @access protected
  787. * @param mixed $var
  788. * @return bool
  789. */
  790. protected function _varIsIterable($var) {
  791. return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  792. }
  793. /**
  794. * Higher order sections helper: tests whether the section $var is a valid callback.
  795. *
  796. * In Mustache.php, a variable is considered 'callable' if the variable is:
  797. *
  798. * 1. an anonymous function.
  799. * 2. an object and the name of a public function, i.e. `array($SomeObject, 'methodName')`
  800. * 3. a class name and the name of a public static function, i.e. `array('SomeClass', 'methodName')`
  801. *
  802. * @access protected
  803. * @param mixed $var
  804. * @return bool
  805. */
  806. protected function _varIsCallable($var) {
  807. return !is_string($var) && is_callable($var);
  808. }
  809. }
  810. /**
  811. * MustacheException class.
  812. *
  813. * @extends Exception
  814. */
  815. class MustacheException extends Exception {
  816. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  817. // in the current context.
  818. const UNKNOWN_VARIABLE = 0;
  819. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  820. const UNCLOSED_SECTION = 1;
  821. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  822. // without a corresponding {{#section}} or {{^section}}.
  823. const UNEXPECTED_CLOSE_SECTION = 2;
  824. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  825. // with no associated partial.
  826. const UNKNOWN_PARTIAL = 3;
  827. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  828. // which can't be handled by this Mustache instance.
  829. const UNKNOWN_PRAGMA = 4;
  830. }