Mustache.php 23 KB

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