PageRenderTime 42ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Mustache.php

http://github.com/remiprev/pubwich
PHP | 641 lines | 315 code | 70 blank | 256 comment | 56 complexity | eea7f24a3f6e1b8c3d558695dc739ae2 MD5 | raw file
Possible License(s): LGPL-2.1
  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. public $_otag = '{{';
  16. public $_ctag = '}}';
  17. /**
  18. * Should this Mustache throw exceptions when it finds unexpected tags?
  19. *
  20. * @see self::_throwsException()
  21. */
  22. protected $_throwsExceptions = array(
  23. MustacheException::UNKNOWN_VARIABLE => false,
  24. MustacheException::UNCLOSED_SECTION => true,
  25. MustacheException::UNEXPECTED_CLOSE_SECTION => true,
  26. MustacheException::UNKNOWN_PARTIAL => false,
  27. MustacheException::UNKNOWN_PRAGMA => true,
  28. );
  29. // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8.
  30. protected $_charset = 'UTF-8';
  31. const PRAGMA_DOT_NOTATION = 'DOT-NOTATION';
  32. /**
  33. * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}}
  34. * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be
  35. * escaped while the {{{unescaped}}} tag will be escaped.
  36. *
  37. * Pragmas apply only to the current template. Partials, even those included after the
  38. * {{%UNESCAPED}} call, will need their own pragma declaration.
  39. *
  40. * This may be useful in non-HTML Mustache situations.
  41. */
  42. const PRAGMA_UNESCAPED = 'UNESCAPED';
  43. protected $_tagRegEx;
  44. protected $_template = '';
  45. protected $_context = array();
  46. protected $_partials = array();
  47. protected $_pragmas = array();
  48. protected $_pragmasImplemented = array(
  49. self::PRAGMA_DOT_NOTATION,
  50. self::PRAGMA_UNESCAPED
  51. );
  52. protected $_localPragmas;
  53. /**
  54. * Mustache class constructor.
  55. *
  56. * This method accepts a $template string and a $view object. Optionally, pass an associative
  57. * array of partials as well.
  58. *
  59. * @access public
  60. * @param string $template (default: null)
  61. * @param mixed $view (default: null)
  62. * @param array $partials (default: null)
  63. * @return void
  64. */
  65. public function __construct($template = null, $view = null, $partials = null) {
  66. if ($template !== null) $this->_template = $template;
  67. if ($partials !== null) $this->_partials = $partials;
  68. if ($view !== null) $this->_context = array($view);
  69. }
  70. /**
  71. * Mustache class clone method.
  72. *
  73. * A cloned Mustache instance should have pragmas, delimeters and root context
  74. * reset to default values.
  75. *
  76. * @access public
  77. * @return void
  78. */
  79. public function __clone() {
  80. $this->_otag = '{{';
  81. $this->_ctag = '}}';
  82. $this->_localPragmas = null;
  83. if ($keys = array_keys($this->_context)) {
  84. $last = array_pop($keys);
  85. if ($this->_context[$last] instanceof Mustache) {
  86. $this->_context[$last] =& $this;
  87. }
  88. }
  89. }
  90. /**
  91. * Render the given template and view object.
  92. *
  93. * Defaults to the template and view passed to the class constructor unless a new one is provided.
  94. * Optionally, pass an associative array of partials as well.
  95. *
  96. * @access public
  97. * @param string $template (default: null)
  98. * @param mixed $view (default: null)
  99. * @param array $partials (default: null)
  100. * @return string Rendered Mustache template.
  101. */
  102. public function render($template = null, $view = null, $partials = null) {
  103. if ($template === null) $template = $this->_template;
  104. if ($partials !== null) $this->_partials = $partials;
  105. if ($view) {
  106. $this->_context = array($view);
  107. } else if (empty($this->_context)) {
  108. $this->_context = array($this);
  109. }
  110. $template = $this->_renderPragmas($template);
  111. return $this->_renderTemplate($template, $this->_context);
  112. }
  113. /**
  114. * Wrap the render() function for string conversion.
  115. *
  116. * @access public
  117. * @return string
  118. */
  119. public function __toString() {
  120. // PHP doesn't like exceptions in __toString.
  121. // catch any exceptions and convert them to strings.
  122. try {
  123. $result = $this->render();
  124. return $result;
  125. } catch (Exception $e) {
  126. return "Error rendering mustache: " . $e->getMessage();
  127. }
  128. }
  129. /**
  130. * Internal render function, used for recursive calls.
  131. *
  132. * @access protected
  133. * @param string $template
  134. * @return string Rendered Mustache template.
  135. */
  136. protected function _renderTemplate($template) {
  137. $template = $this->_renderSection($template);
  138. return $this->_renderTags($template);
  139. }
  140. /**
  141. * Render boolean, enumerable and inverted sections.
  142. *
  143. * @access protected
  144. * @param string $template
  145. * @return string
  146. */
  147. protected function _renderSection($template) {
  148. $otag = $this->_prepareRegEx($this->_otag);
  149. $ctag = $this->_prepareRegEx($this->_ctag);
  150. $regex = '/' . $otag . '(\\^|\\#)\\s*(.+?)\\s*' . $ctag . '\\s*([\\s\\S]+?)' . $otag . '\\/\\s*\\2\\s*' . $ctag . '\\s*/m';
  151. $matches = array();
  152. while (preg_match($regex, $template, $matches, PREG_OFFSET_CAPTURE)) {
  153. $section = $matches[0][0];
  154. $offset = $matches[0][1];
  155. $type = $matches[1][0];
  156. $tag_name = trim($matches[2][0]);
  157. $content = $matches[3][0];
  158. $replace = '';
  159. $val = $this->_getVariable($tag_name);
  160. switch($type) {
  161. // inverted section
  162. case '^':
  163. if (empty($val)) {
  164. $replace .= $content;
  165. }
  166. break;
  167. // regular section
  168. case '#':
  169. if ($this->_varIsIterable($val)) {
  170. foreach ($val as $local_context) {
  171. $this->_pushContext($local_context);
  172. $replace .= $this->_renderTemplate($content);
  173. $this->_popContext();
  174. }
  175. } else if ($val) {
  176. if (is_array($val) || is_object($val)) {
  177. $this->_pushContext($val);
  178. $replace .= $this->_renderTemplate($content);
  179. $this->_popContext();
  180. } else {
  181. $replace .= $content;
  182. }
  183. }
  184. break;
  185. }
  186. $template = substr_replace($template, $replace, $offset, strlen($section));
  187. }
  188. return $template;
  189. }
  190. /**
  191. * Initialize pragmas and remove all pragma tags.
  192. *
  193. * @access protected
  194. * @param string $template
  195. * @return string
  196. */
  197. protected function _renderPragmas($template) {
  198. $this->_localPragmas = $this->_pragmas;
  199. // no pragmas
  200. if (strpos($template, $this->_otag . '%') === false) {
  201. return $template;
  202. }
  203. $otag = $this->_prepareRegEx($this->_otag);
  204. $ctag = $this->_prepareRegEx($this->_ctag);
  205. $regex = '/' . $otag . '%\\s*([\\w_-]+)((?: [\\w]+=[\\w]+)*)\\s*' . $ctag . '\\n?/';
  206. return preg_replace_callback($regex, array($this, '_renderPragma'), $template);
  207. }
  208. /**
  209. * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma.
  210. *
  211. * @access protected
  212. * @param mixed $matches
  213. * @return void
  214. * @throws MustacheException unknown pragma
  215. */
  216. protected function _renderPragma($matches) {
  217. $pragma = $matches[0];
  218. $pragma_name = $matches[1];
  219. $options_string = $matches[2];
  220. if (!in_array($pragma_name, $this->_pragmasImplemented)) {
  221. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  222. }
  223. $options = array();
  224. foreach (explode(' ', trim($options_string)) as $o) {
  225. if ($p = trim($o)) {
  226. $p = explode('=', trim($p));
  227. $options[$p[0]] = $p[1];
  228. }
  229. }
  230. if (empty($options)) {
  231. $this->_localPragmas[$pragma_name] = true;
  232. } else {
  233. $this->_localPragmas[$pragma_name] = $options;
  234. }
  235. return '';
  236. }
  237. /**
  238. * Check whether this Mustache has a specific pragma.
  239. *
  240. * @access protected
  241. * @param string $pragma_name
  242. * @return bool
  243. */
  244. protected function _hasPragma($pragma_name) {
  245. if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) {
  246. return true;
  247. } else {
  248. return false;
  249. }
  250. }
  251. /**
  252. * Return pragma options, if any.
  253. *
  254. * @access protected
  255. * @param string $pragma_name
  256. * @return mixed
  257. * @throws MustacheException Unknown pragma
  258. */
  259. protected function _getPragmaOptions($pragma_name) {
  260. if (!$this->_hasPragma()) {
  261. throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA);
  262. }
  263. return $this->_localPragmas[$pragma_name];
  264. }
  265. /**
  266. * Check whether this Mustache instance throws a given exception.
  267. *
  268. * Expects exceptions to be MustacheException error codes (i.e. class constants).
  269. *
  270. * @access protected
  271. * @param mixed $exception
  272. * @return void
  273. */
  274. protected function _throwsException($exception) {
  275. return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]);
  276. }
  277. /**
  278. * Loop through and render individual Mustache tags.
  279. *
  280. * @access protected
  281. * @param string $template
  282. * @return void
  283. */
  284. protected function _renderTags($template) {
  285. if (strpos($template, $this->_otag) === false) {
  286. return $template;
  287. }
  288. $otag = $this->_prepareRegEx($this->_otag);
  289. $ctag = $this->_prepareRegEx($this->_ctag);
  290. $this->_tagRegEx = '/' . $otag . "([#\^\/=!>\\{&])?(.+?)\\1?" . $ctag . "+/";
  291. $html = '';
  292. $matches = array();
  293. while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) {
  294. $tag = $matches[0][0];
  295. $offset = $matches[0][1];
  296. $modifier = $matches[1][0];
  297. $tag_name = trim($matches[2][0]);
  298. $html .= substr($template, 0, $offset);
  299. $html .= $this->_renderTag($modifier, $tag_name);
  300. $template = substr($template, $offset + strlen($tag));
  301. }
  302. return $html . $template;
  303. }
  304. /**
  305. * Render the named tag, given the specified modifier.
  306. *
  307. * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial)
  308. * `{` or `&` (don't escape output), or none (render escaped output).
  309. *
  310. * @access protected
  311. * @param string $modifier
  312. * @param string $tag_name
  313. * @throws MustacheException Unmatched section tag encountered.
  314. * @return string
  315. */
  316. protected function _renderTag($modifier, $tag_name) {
  317. switch ($modifier) {
  318. case '#':
  319. case '^':
  320. if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) {
  321. throw new MustacheException('Unclosed section: ' . $tag_name, MustacheException::UNCLOSED_SECTION);
  322. } else {
  323. return '';
  324. }
  325. break;
  326. case '/':
  327. if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) {
  328. throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION);
  329. } else {
  330. return '';
  331. }
  332. break;
  333. case '=':
  334. return $this->_changeDelimiter($tag_name);
  335. break;
  336. case '!':
  337. return $this->_renderComment($tag_name);
  338. break;
  339. case '>':
  340. return $this->_renderPartial($tag_name);
  341. break;
  342. case '{':
  343. case '&':
  344. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  345. return $this->_renderEscaped($tag_name);
  346. } else {
  347. return $this->_renderUnescaped($tag_name);
  348. }
  349. break;
  350. case '':
  351. default:
  352. if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) {
  353. return $this->_renderUnescaped($tag_name);
  354. } else {
  355. return $this->_renderEscaped($tag_name);
  356. }
  357. break;
  358. }
  359. }
  360. /**
  361. * Escape and return the requested tag.
  362. *
  363. * @access protected
  364. * @param string $tag_name
  365. * @return string
  366. */
  367. protected function _renderEscaped($tag_name) {
  368. return htmlentities($this->_getVariable($tag_name), null, $this->_charset);
  369. }
  370. /**
  371. * Render a comment (i.e. return an empty string).
  372. *
  373. * @access protected
  374. * @param string $tag_name
  375. * @return string
  376. */
  377. protected function _renderComment($tag_name) {
  378. return '';
  379. }
  380. /**
  381. * Return the requested tag unescaped.
  382. *
  383. * @access protected
  384. * @param string $tag_name
  385. * @return string
  386. */
  387. protected function _renderUnescaped($tag_name) {
  388. return $this->_getVariable($tag_name);
  389. }
  390. /**
  391. * Render the requested partial.
  392. *
  393. * @access protected
  394. * @param string $tag_name
  395. * @return string
  396. */
  397. protected function _renderPartial($tag_name) {
  398. $view = clone($this);
  399. return $view->render($this->_getPartial($tag_name));
  400. }
  401. /**
  402. * Change the Mustache tag delimiter. This method also replaces this object's current
  403. * tag RegEx with one using the new delimiters.
  404. *
  405. * @access protected
  406. * @param string $tag_name
  407. * @return string
  408. */
  409. protected function _changeDelimiter($tag_name) {
  410. $tags = explode(' ', $tag_name);
  411. $this->_otag = $tags[0];
  412. $this->_ctag = $tags[1];
  413. $otag = $this->_prepareRegEx($this->_otag);
  414. $ctag = $this->_prepareRegEx($this->_ctag);
  415. $this->_tagRegEx = '/' . $otag . "([#\^\/=!>\\{&])?(.+?)\\1?" . $ctag . "+/";
  416. return '';
  417. }
  418. /**
  419. * Push a local context onto the stack.
  420. *
  421. * @access protected
  422. * @param array $local_context
  423. * @return array
  424. */
  425. protected function _pushContext(&$local_context) {
  426. $new = array();
  427. $new[] =& $local_context;
  428. foreach (array_keys($this->_context) as $key) {
  429. $new[] =& $this->_context[$key];
  430. }
  431. $this->_context = $new;
  432. }
  433. /**
  434. * Remove the latest context from the stack.
  435. *
  436. * @access protected
  437. * @return void
  438. */
  439. protected function _popContext() {
  440. $new = array();
  441. $keys = array_keys($this->_context);
  442. array_shift($keys);
  443. foreach ($keys as $key) {
  444. $new[] =& $this->_context[$key];
  445. }
  446. $this->_context = $new;
  447. }
  448. /**
  449. * Get a variable from the context array.
  450. *
  451. * If the view is an array, returns the value with array key $tag_name.
  452. * If the view is an object, this will check for a public member variable
  453. * named $tag_name. If none is available, this method will execute and return
  454. * any class method named $tag_name. Failing all of the above, this method will
  455. * return an empty string.
  456. *
  457. * @access protected
  458. * @param string $tag_name
  459. * @throws MustacheException Unknown variable name.
  460. * @return string
  461. */
  462. protected function _getVariable($tag_name) {
  463. if ($this->_hasPragma(self::PRAGMA_DOT_NOTATION)) {
  464. $chunks = explode('.', $tag_name);
  465. $first = array_shift($chunks);
  466. $ret = $this->_findVariableInContext($first, $this->_context);
  467. while ($next = array_shift($chunks)) {
  468. // Slice off a chunk of context for dot notation traversal.
  469. $c = array($ret);
  470. $ret = $this->_findVariableInContext($next, $c);
  471. }
  472. return $ret;
  473. } else {
  474. return $this->_findVariableInContext($tag_name, $this->_context);
  475. }
  476. }
  477. /**
  478. * Get a variable from the context array. Internal helper used by getVariable() to abstract
  479. * variable traversal for dot notation.
  480. *
  481. * @access protected
  482. * @param string $tag_name
  483. * @param array &$context
  484. * @throws MustacheException Unknown variable name.
  485. * @return string
  486. */
  487. protected function _findVariableInContext($tag_name, &$context) {
  488. foreach ($context as $view) {
  489. if (is_object($view)) {
  490. if (isset($view->$tag_name)) {
  491. return $view->$tag_name;
  492. } else if (method_exists($view, $tag_name)) {
  493. return $view->$tag_name();
  494. }
  495. } else if (isset($view[$tag_name])) {
  496. return $view[$tag_name];
  497. }
  498. }
  499. if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) {
  500. throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE);
  501. } else {
  502. return '';
  503. }
  504. }
  505. /**
  506. * Retrieve the partial corresponding to the requested tag name.
  507. *
  508. * Silently fails (i.e. returns '') when the requested partial is not found.
  509. *
  510. * @access protected
  511. * @param string $tag_name
  512. * @throws MustacheException Unknown partial name.
  513. * @return string
  514. */
  515. protected function _getPartial($tag_name) {
  516. if (is_array($this->_partials) && isset($this->_partials[$tag_name])) {
  517. return $this->_partials[$tag_name];
  518. }
  519. if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) {
  520. throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL);
  521. } else {
  522. return '';
  523. }
  524. }
  525. /**
  526. * Check whether the given $var should be iterated (i.e. in a section context).
  527. *
  528. * @access protected
  529. * @param mixed $var
  530. * @return bool
  531. */
  532. protected function _varIsIterable($var) {
  533. return is_object($var) || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var))));
  534. }
  535. /**
  536. * Prepare a string to be used in a regular expression.
  537. *
  538. * @access protected
  539. * @param string $str
  540. * @return string
  541. */
  542. protected function _prepareRegEx($str) {
  543. $replace = array(
  544. '\\' => '\\\\', '^' => '\^', '.' => '\.', '$' => '\$', '|' => '\|', '(' => '\(',
  545. ')' => '\)', '[' => '\[', ']' => '\]', '*' => '\*', '+' => '\+', '?' => '\?',
  546. '{' => '\{', '}' => '\}', ',' => '\,'
  547. );
  548. return strtr($str, $replace);
  549. }
  550. }
  551. /**
  552. * MustacheException class.
  553. *
  554. * @extends Exception
  555. */
  556. class MustacheException extends Exception {
  557. // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found
  558. // in the current context.
  559. const UNKNOWN_VARIABLE = 0;
  560. // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed.
  561. const UNCLOSED_SECTION = 1;
  562. // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears
  563. // without a corresponding {{#section}} or {{^section}}.
  564. const UNEXPECTED_CLOSE_SECTION = 2;
  565. // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears
  566. // with no associated partial.
  567. const UNKNOWN_PARTIAL = 3;
  568. // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears
  569. // which can't be handled by this Mustache instance.
  570. const UNKNOWN_PRAGMA = 4;
  571. }