Mustache.php 23 KB

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