Mustache.php 22 KB

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