Mustache.php 23 KB

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