Mustache.php 24 KB

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