From 015a4bf4baee2933b160107c2cc4c20b0b4a8560 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 29 Feb 2012 17:55:19 -0800 Subject: [PATCH 01/58] Rearrange codebase to prep for 2.0 development. --- phpunit.xml.dist | 12 ++++++++++++ Mustache.php => src/Mustache/Mustache.php | 0 .../Mustache/MustacheLoader.php | 0 test/{ => Mustache/Test}/MustacheCallTest.php | 0 test/{ => Mustache/Test}/MustacheExceptionTest.php | 0 .../Test}/MustacheHigherOrderSectionsTest.php | 0 test/{ => Mustache/Test}/MustacheInjectionTest.php | 0 test/{ => Mustache/Test}/MustacheLoaderTest.php | 0 .../Test}/MustacheObjectSectionTest.php | 0 test/{ => Mustache/Test}/MustachePragmaTest.php | 0 .../Test}/MustachePragmaUnescapedTest.php | 0 test/{ => Mustache/Test}/MustacheSpecTest.php | 0 test/{ => Mustache/Test}/MustacheTest.php | 0 test/phpunit.xml | 10 ---------- 14 files changed, 12 insertions(+), 10 deletions(-) create mode 100644 phpunit.xml.dist rename Mustache.php => src/Mustache/Mustache.php (100%) rename MustacheLoader.php => src/Mustache/MustacheLoader.php (100%) rename test/{ => Mustache/Test}/MustacheCallTest.php (100%) rename test/{ => Mustache/Test}/MustacheExceptionTest.php (100%) rename test/{ => Mustache/Test}/MustacheHigherOrderSectionsTest.php (100%) rename test/{ => Mustache/Test}/MustacheInjectionTest.php (100%) rename test/{ => Mustache/Test}/MustacheLoaderTest.php (100%) rename test/{ => Mustache/Test}/MustacheObjectSectionTest.php (100%) rename test/{ => Mustache/Test}/MustachePragmaTest.php (100%) rename test/{ => Mustache/Test}/MustachePragmaUnescapedTest.php (100%) rename test/{ => Mustache/Test}/MustacheSpecTest.php (100%) rename test/{ => Mustache/Test}/MustacheTest.php (100%) delete mode 100644 test/phpunit.xml diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..8863a59 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,12 @@ + + + + ./test + + + + + ./src/Mustache + + + \ No newline at end of file diff --git a/Mustache.php b/src/Mustache/Mustache.php similarity index 100% rename from Mustache.php rename to src/Mustache/Mustache.php diff --git a/MustacheLoader.php b/src/Mustache/MustacheLoader.php similarity index 100% rename from MustacheLoader.php rename to src/Mustache/MustacheLoader.php diff --git a/test/MustacheCallTest.php b/test/Mustache/Test/MustacheCallTest.php similarity index 100% rename from test/MustacheCallTest.php rename to test/Mustache/Test/MustacheCallTest.php diff --git a/test/MustacheExceptionTest.php b/test/Mustache/Test/MustacheExceptionTest.php similarity index 100% rename from test/MustacheExceptionTest.php rename to test/Mustache/Test/MustacheExceptionTest.php diff --git a/test/MustacheHigherOrderSectionsTest.php b/test/Mustache/Test/MustacheHigherOrderSectionsTest.php similarity index 100% rename from test/MustacheHigherOrderSectionsTest.php rename to test/Mustache/Test/MustacheHigherOrderSectionsTest.php diff --git a/test/MustacheInjectionTest.php b/test/Mustache/Test/MustacheInjectionTest.php similarity index 100% rename from test/MustacheInjectionTest.php rename to test/Mustache/Test/MustacheInjectionTest.php diff --git a/test/MustacheLoaderTest.php b/test/Mustache/Test/MustacheLoaderTest.php similarity index 100% rename from test/MustacheLoaderTest.php rename to test/Mustache/Test/MustacheLoaderTest.php diff --git a/test/MustacheObjectSectionTest.php b/test/Mustache/Test/MustacheObjectSectionTest.php similarity index 100% rename from test/MustacheObjectSectionTest.php rename to test/Mustache/Test/MustacheObjectSectionTest.php diff --git a/test/MustachePragmaTest.php b/test/Mustache/Test/MustachePragmaTest.php similarity index 100% rename from test/MustachePragmaTest.php rename to test/Mustache/Test/MustachePragmaTest.php diff --git a/test/MustachePragmaUnescapedTest.php b/test/Mustache/Test/MustachePragmaUnescapedTest.php similarity index 100% rename from test/MustachePragmaUnescapedTest.php rename to test/Mustache/Test/MustachePragmaUnescapedTest.php diff --git a/test/MustacheSpecTest.php b/test/Mustache/Test/MustacheSpecTest.php similarity index 100% rename from test/MustacheSpecTest.php rename to test/Mustache/Test/MustacheSpecTest.php diff --git a/test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php similarity index 100% rename from test/MustacheTest.php rename to test/Mustache/Test/MustacheTest.php diff --git a/test/phpunit.xml b/test/phpunit.xml deleted file mode 100644 index 891fa8e..0000000 --- a/test/phpunit.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - ./ - - - ../examples - ./ - - \ No newline at end of file From d2136d91b3a3ba161c61954d5a5b9a1c3919babc Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 29 Feb 2012 18:01:57 -0800 Subject: [PATCH 02/58] Initial Mustache.php 2.0 commit. --- src/Mustache/Buffer.php | 129 +++ src/Mustache/Compiler.php | 292 ++++++ src/Mustache/Context.php | 203 ++++ src/Mustache/Loader.php | 18 + src/Mustache/Loader/ArrayLoader.php | 70 ++ src/Mustache/Loader/FilesystemLoader.php | 108 +++ src/Mustache/Loader/MutableLoader.php | 24 + src/Mustache/Loader/StringLoader.php | 35 + src/Mustache/Mustache.php | 1104 ++++++---------------- src/Mustache/MustacheLoader.php | 85 -- src/Mustache/Parser.php | 80 ++ src/Mustache/Template.php | 66 ++ src/Mustache/Tokenizer.php | 262 +++++ test/bootstrap.php | 16 + test/fixtures/templates/alpha.ms | 1 + test/fixtures/templates/beta.ms | 1 + test/fixtures/templates/one.mustache | 1 + test/fixtures/templates/two.mustache | 1 + 18 files changed, 1604 insertions(+), 892 deletions(-) create mode 100644 src/Mustache/Buffer.php create mode 100644 src/Mustache/Compiler.php create mode 100644 src/Mustache/Context.php create mode 100644 src/Mustache/Loader.php create mode 100644 src/Mustache/Loader/ArrayLoader.php create mode 100644 src/Mustache/Loader/FilesystemLoader.php create mode 100644 src/Mustache/Loader/MutableLoader.php create mode 100644 src/Mustache/Loader/StringLoader.php delete mode 100644 src/Mustache/MustacheLoader.php create mode 100644 src/Mustache/Parser.php create mode 100644 src/Mustache/Template.php create mode 100644 src/Mustache/Tokenizer.php create mode 100644 test/bootstrap.php create mode 100644 test/fixtures/templates/alpha.ms create mode 100644 test/fixtures/templates/beta.ms create mode 100644 test/fixtures/templates/one.mustache create mode 100644 test/fixtures/templates/two.mustache diff --git a/src/Mustache/Buffer.php b/src/Mustache/Buffer.php new file mode 100644 index 0000000..f2fac5d --- /dev/null +++ b/src/Mustache/Buffer.php @@ -0,0 +1,129 @@ +setIndent($indent); + } + + if ($charset !== null) { + $this->charset = $charset; + } + } + + /** + * Get the current indent level. + * + * @return string + */ + public function getIndent() { + return $this->indent; + } + + /** + * Set the buffer indent level. + * + * Each line output by this buffer will be prefixed by this whitespace. This is used when rendering + * partials and Lambda sections. + * + * @param string $indent + */ + public function setIndent($indent) { + $this->indent = $indent; + } + + /** + * Get the character set used when escaping values. + * + * @return string + */ + public function getCharset() { + return $this->charset; + } + + /** + * Write a newline to the Buffer. + */ + public function writeLine() { + $this->buffer .= "\n"; + } + + /** + * Output text to the Buffer. + * + * @see \Mustache\Buffer::write + * + * @param string $text + * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) + */ + public function writeText($text, $escape = false) { + $this->write($text, true, $escape); + } + + /** + * Add output to the Buffer. + * + * @param string $text + * @param bool $indent Indent this line? (default: false) + * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) + */ + public function write($text, $indent = false, $escape = false) { + $text = (string) $text; + + if ($escape) { + $text = $this->escape($text); + } + + if ($indent) { + $this->buffer .= $this->indent . $text; + } else { + $this->buffer .= $text; + } + } + + /** + * Flush the contents of the Buffer. + * + * Resets the buffer and returns the current contents. + * + * @return string + */ + public function flush() { + $buffer = $this->buffer; + $this->buffer = ''; + + return $buffer; + } + + /** + * Helper function to escape text. + * + * Uses the Buffer's character set (default 'UTF-8', passed as the second argument to `__construct`). + * + * @see htmlspecialchars + * + * @param string $text + * + * @return string Escaped text + */ + private function escape($text) { + return htmlspecialchars($text, ENT_COMPAT, $this->charset); + } +} diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php new file mode 100644 index 0000000..3ca3f48 --- /dev/null +++ b/src/Mustache/Compiler.php @@ -0,0 +1,292 @@ +source = $source; + + return $this->writeCode($tree, $name); + } + + /** + * Helper function for walking the Mustache token parse tree. + * + * @throws \InvalidArgumentException upon encountering unknown token types. + * + * @param array $tree Parse tree of Mustache tokens + * @param int $level (default: 0) + * + * @return string Generated PHP source code; + */ + private function walk(array $tree, $level = 0) { + $code = ''; + $level++; + foreach ($tree as $node) { + switch (is_string($node) ? 'text' : $node[Tokenizer::TAG]) { + case '#': + $code .= $this->section( + $node[Tokenizer::NODES], + $node[Tokenizer::NAME], + $node[Tokenizer::INDEX], + $node[Tokenizer::END], + $node[Tokenizer::OTAG], + $node[Tokenizer::CTAG], + $level + ); + break; + + case '^': + $code .= $this->invertedSection( + $node[Tokenizer::NODES], + $node[Tokenizer::NAME], + $level + ); + break; + + case '<': + case '>': + $code .= $this->partial( + $node[Tokenizer::NAME], + isset($node[Tokenizer::INDENT]) ? $node[Tokenizer::INDENT] : '', + $level + ); + break; + + case '{': + case '&': + $code .= $this->variable($node[Tokenizer::NAME], false, $level); + break; + + case '!': + break; + + case '_v': + $code .= $this->variable($node[Tokenizer::NAME], true, $level); + break; + + + case 'text': + $code .= $this->text($node, $level); + break; + + default: + throw new \InvalidArgumentException('Unknown node type: '.json_encode($node)); + } + } + + return $code; + } + + const KLASS = 'mustache; + $buffer = new \Mustache\Buffer($indent, $mustache->getCharset()); + %s + + return $buffer->flush(); + } + }'; + + /** + * Generate Mustache Template class PHP source. + * + * @param array $tree Parse tree of Mustache tokens + * @param string $name Mustache Template class name + * + * @return string Generated PHP source code + */ + private function writeCode($tree, $name) { + return sprintf($this->prepare(self::KLASS, 0, false), $name, $this->walk($tree), $name); + } + + const SECTION = ' + // %s section + $value = $context->%s(%s); + if ($context->isCallable($value)) { + $source = %s; + $buffer->write( + $mustache + ->loadLambda((string) call_user_func($value, $source)%s) + ->renderInternal($context, $buffer->getIndent()) + ); + } elseif ($context->isTruthy($value)) { + $values = $context->isIterable($value) ? $value : array($value); + foreach ($values as $value) { + $context->push($value);%s + $context->pop(); + } + }'; + + /** + * Generate Mustache Template section PHP source. + * + * @param array $nodes Array of child tokens + * @param string $id Section name + * @param int $start Section start offset + * @param int $end Section end offset + * @param string $otag Current Mustache opening tag + * @param string $ctag Current Mustache closing tag + * @param int $level + * + * @return string Generated section PHP source code + */ + private function section($nodes, $id, $start, $end, $otag, $ctag, $level) { + $method = $this->getFindMethod($id); + $id = var_export($id, true); + $source = var_export(substr($this->source, $start, $end - $start), true); + + if ($otag !== '{{' || $ctag !== '}}') { + $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true); + } else { + $delims = ''; + } + + return sprintf($this->prepare(self::SECTION, $level), $id, $method, $id, $source, $delims, $this->walk($nodes, $level + 1)); + } + + const INVERTED_SECTION = ' + // %s inverted section + if (!$context->isTruthy($context->%s(%s))) { + %s + }'; + + /** + * Generate Mustache Template inverted section PHP source. + * + * @param array $nodes Array of child tokens + * @param string $id Section name + * @param int $level + * + * @return string Generated inverted section PHP source code + */ + private function invertedSection($nodes, $id, $level) { + $method = $this->getFindMethod($id); + $id = var_export($id, true); + + return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); + } + + const PARTIAL = '$buffer->write($mustache->loadPartial(%s)->renderInternal($context, %s));'; + + /** + * Generate Mustache Template partial call PHP source. + * + * @param string $id Partial name + * @param string $indent Whitespace indent to apply to partial + * @param int $level + * + * @return string Generated partial call PHP source code + */ + private function partial($id, $indent, $level) { + return sprintf( + $this->prepare(self::PARTIAL, $level), + var_export($id, true), + var_export($indent, true) + ); + } + + const VARIABLE = ' + $value = $context->%s(%s); + if ($context->isCallable($value)) { + $value = $mustache + ->loadLambda((string) call_user_func($value)) + ->renderInternal($context, $buffer->getIndent()); + } + $buffer->writeText($value, %s); + '; + + /** + * Generate Mustache Template variable interpolation PHP source. + * + * @param string $id Variable name + * @param boolean $escape Escape the variable value for output? + * @param int $level + * + * @return string Generated variable interpolation PHP source + */ + private function variable($id, $escape, $level) { + $method = $this->getFindMethod($id); + $id = ($method !== 'last') ? var_export($id, true) : ''; + $escape = $escape ? 'true' : 'false'; + + return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $escape); + } + + const LINE = '$buffer->writeLine();'; + const TEXT = '$buffer->writeText(%s);'; + + /** + * Generate Mustache Template output Buffer call PHP source. + * + * @param string $text + * @param int $level + * + * @return string Generated output Buffer call PHP source + */ + private function text($text, $level) { + if ($text === "\n") { + return $this->prepare(self::LINE, $level); + } else { + return sprintf($this->prepare(self::TEXT, $level), var_export($text, true)); + } + } + + /** + * Prepare PHP source code snippet for output. + * + * @param string $text + * @param int $bonus Additional indent level (default: 0) + * @param boolean $prependNewline Prepend a newline to the snippet? (default: true) + * + * @return string PHP source code snippet + */ + private function prepare($text, $bonus = 0, $prependNewline = true) { + $text = ($prependNewline ? "\n" : '').trim($text); + if ($prependNewline) { + $bonus++; + } + + return preg_replace("/\n(\t\t)?/", "\n".str_repeat("\t", $bonus), $text); + } + + /** + * Select the appropriate Context `find` method for a given $id. + * + * The return value will be one of `find`, `findDot` or `last`. + * + * @see \Mustache\Context::find + * @see \Mustache\Context::findDot + * @see \Mustache\Context::last + * + * @param string $id Variable name + * + * @return string `find` method name + */ + private function getFindMethod($id) { + if ($id === '.') { + return 'last'; + } elseif (strpos($id, '.') === false) { + return 'find'; + } else { + return 'findDot'; + } + } +} diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php new file mode 100644 index 0000000..63ee1e8 --- /dev/null +++ b/src/Mustache/Context.php @@ -0,0 +1,203 @@ +stack = array($context); + } + } + + /** + * Helper function to test whether a value is 'truthy'. + * + * @param mixed $value + * + * @return boolean True if the value is 'truthy' + */ + public function isTruthy($value) { + return !empty($value); + } + + /** + * Higher order sections helper: tests whether a value is a valid callback. + * + * In Mustache.php, a variable is considered 'callable' if the variable is: + * + * 1. An anonymous function. + * 2. An object and the name of a public function, e.g. `array($someObject, 'methodName')` + * 3. A class name and the name of a public static function, e.g. `array('SomeClass', 'methodName')` + * + * Note that this specifically excludes strings, which PHP would normally consider 'callable'. + * + * @param mixed $value + * + * @return boolean True if the value is 'callable' + */ + public function isCallable($value) { + return !is_string($value) && is_callable($value); + } + + /** + * Tests whether a value should be iterated over (e.g. in a section context). + * + * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists + * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, + * Java, Python, etc. + * + * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish + * between between a list of things (numeric, normalized array) and a set of variables to be used as section context + * (associative array). In other words, this will be iterated over: + * + * $items = array( + * array('name' => 'foo'), + * array('name' => 'bar'), + * array('name' => 'baz'), + * ); + * + * ... but this will be used as a section context block: + * + * $items = array( + * 1 => array('name' => 'foo'), + * 'banana' => array('name' => 'bar'), + * 42 => array('name' => 'baz'), + * ); + * + * @param mixed $value + * + * @return boolean True if the value is 'iterable' + */ + public function isIterable($value) { + if (is_object($value)) { + return $value instanceof \Traversable; + } elseif (is_array($value)) { + return !array_diff_key($value, array_keys(array_keys($value))); + } + + return false; + } + + /** + * Push a new Context frame onto the stack. + * + * @param mixed $value Object or array to use for context + */ + public function push($value) { + array_push($this->stack, $value); + } + + /** + * Pop the last Context frame from the stack. + * + * @return mixed Last Context frame (object or array) + */ + public function pop() { + return array_pop($this->stack); + } + + /** + * Get the last Context frame. + * + * @return mixed Last Context frame (object or array) + */ + public function last() { + return end($this->stack); + } + + /** + * Find a variable in the Context stack. + * + * Starting with the last Context frame (the context of the innermost section), and working back to the top-level + * rendering context, look for a variable with the given name: + * + * * If the Context frame is an associative array which contains the key $id, returns the value of that element. + * * If the Context frame is an object, this will check first for a public method, then a public property named + * $id. Failing both of these, it will try `__isset` and `__get` magic methods. + * * If a value named $id is not found in any Context frame, returns an empty string. + * + * @param string $id Variable name + * + * @return mixed Variable value, or '' if not found + */ + public function find($id) { + return $this->findVariableInStack($id, $this->stack); + } + + /** + * Find a 'dot notation' variable in the Context stack. + * + * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding + * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous + * result. For example, given the following context stack: + * + * $data = array( + * 'name' => 'Fred', + * 'child' => array( + * 'name' => 'Bob' + * ), + * ); + * + * ... and the Mustache following template: + * + * {{ child.name }} + * + * ... the `name` value is only searched for within the `child` value of the global Context, not within parent + * Context frames. + * + * @param string $id Dotted variable selector + * + * @return mixed Variable value, or '' if not found + */ + public function findDot($id) { + $chunks = explode('.', $id); + $first = array_shift($chunks); + $value = $this->findVariableInStack($first, $this->stack); + + foreach ($chunks as $chunk) { + if ($value === '') { + return $value; + } + + $value = $this->findVariableInStack($chunk, array($value)); + } + + return $value; + } + + /** + * Helper function to find a variable in the Context stack. + * + * @see \Mustache\Context::find + * + * @param string $id Variable name + * @param array $stack Context stack + * + * @return mixed Variable value, or '' if not found + */ + private function findVariableInStack($id, array $stack) { + for ($i = count($stack) - 1; $i >= 0; $i--) { + if (is_object($stack[$i])) { + if (method_exists($stack[$i], $id)) { + return $stack[$i]->$id(); + } elseif (isset($stack[$i]->$id)) { + return $stack[$i]->$id; + } + } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) { + return $stack[$i][$id]; + } + } + + return ''; + } +} diff --git a/src/Mustache/Loader.php b/src/Mustache/Loader.php new file mode 100644 index 0000000..57991b6 --- /dev/null +++ b/src/Mustache/Loader.php @@ -0,0 +1,18 @@ + '{{ bar }}', + * 'baz' => 'Hey {{ qux }}!' + * ); + * + * $tpl = $loader->load('foo'); // '{{ bar }}' + * + * The ArrayLoader is used internally as a partials loader by \Mustache\Mustache instance when an array of partials + * is set. It can also be used as a quick-and-dirty Template loader. + * + * @implements Loader + * @implements MutableLoader + */ +class ArrayLoader implements Loader, MutableLoader { + + /** + * ArrayLoader constructor. + * + * @param array $templates Associative array of Template source (default: array()) + */ + public function __construct(array $templates = array()) { + $this->templates = $templates; + } + + /** + * Load a Template. + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name) { + if (!isset($this->templates[$name])) { + throw new \InvalidArgumentException('Template '.$name.' not found.'); + } + + return $this->templates[$name]; + } + + /** + * Set an associative array of Template sources for this loader. + * + * @param array $templates + */ + public function setTemplates(array $templates) { + $this->templates = $templates; + } + + /** + * Set a Template source by name. + * + * @param string $name + * @param string $template Mustache Template source + */ + public function setTemplate($name, $template) { + $this->templates[$name] = $template; + } +} diff --git a/src/Mustache/Loader/FilesystemLoader.php b/src/Mustache/Loader/FilesystemLoader.php new file mode 100644 index 0000000..e510fc9 --- /dev/null +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -0,0 +1,108 @@ +load('foo'); // equivalent to `file_get_contents(__DIR__.'/views/foo.mustache'); + * + * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates: + * + * $m = new Mustache(array( + * 'loader' => new FilesystemLoader(__DIR__.'/views'), + * 'partials_loader' => new FilesystemLoader(__DIR__.'/views/partials'), + * )); + * + * @implements Loader + */ +class FilesystemLoader implements Loader { + private $baseDir; + private $extension = '.mustache'; + private $templates = array(); + + /** + * Mustache filesystem Loader constructor. + * + * Passing an $options array allows overriding certain Loader options during instantiation: + * + * $options = array( + * // The filename extension used for Mustache templates. Defaults to '.mustache' + * 'extension' => '.ms', + * ); + * + * @throws \RuntimeException if $baseDir does not exist. + * + * @param string $baseDir Base directory containing Mustache template files. + * @param array $options Array of Loader options (default: array()) + */ + public function __construct($baseDir, array $options = array()) { + $this->baseDir = rtrim(realpath($baseDir), '/'); + + if (!is_dir($this->baseDir)) { + throw new \RuntimeException('FilesystemLoader baseDir must be a directory: '.$baseDir); + } + + if (isset($options['extension'])) { + $this->extension = '.' . ltrim($options['extension'], '.'); + } + } + + /** + * Load a Template by name. + * + * $loader = new FilesystemLoader(__DIR__.'/views'); + * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name) { + if (!isset($this->templates[$name])) { + $this->templates[$name] = $this->loadFile($name); + } + + return $this->templates[$name]; + } + + /** + * Helper function for loading a Mustache file by name. + * + * @throws \InvalidArgumentException if a template file is not found. + * + * @param string $name + * + * @return string Mustache Template source + */ + private function loadFile($name) { + $fileName = $this->getFileName($name); + + if (!file_exists($fileName)) { + throw new \InvalidArgumentException('Template '.$name.' not found.'); + } + + return file_get_contents($fileName); + } + + /** + * Helper function for getting a Mustache template file name. + * + * @param string $name + * + * @return string Template file name + */ + private function getFileName($name) { + $fileName = $this->baseDir . '/' . $name; + if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) { + $fileName .= $this->extension; + } + + return $fileName; + } +} diff --git a/src/Mustache/Loader/MutableLoader.php b/src/Mustache/Loader/MutableLoader.php new file mode 100644 index 0000000..3d45a5c --- /dev/null +++ b/src/Mustache/Loader/MutableLoader.php @@ -0,0 +1,24 @@ +load('{{ foo }}'); // '{{ foo }}' + * + * This is the default Template Loader instance used by Mustache: + * + * $m = new Mustache; + * $tpl = $m->loadTemplate('{{ foo }}'); + * echo $tpl->render(array('foo' => 'bar')); // "bar" + * + * @implements Loader + */ +class StringLoader implements Loader { + + /** + * Load a Template by source. + * + * @param string $name Mustache Template source + * + * @return string Mustache Template source + */ + public function load($name) { + return $name; + } +} diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index c97cd12..98df8b0 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -1,5 +1,11 @@ false, - MustacheException::UNCLOSED_SECTION => true, - MustacheException::UNEXPECTED_CLOSE_SECTION => true, - MustacheException::UNKNOWN_PARTIAL => false, - MustacheException::UNKNOWN_PRAGMA => true, - ); + // Template cache + private $templates = array(); - // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8. - protected $_charset = 'UTF-8'; - - /** - * Pragmas are macro-like directives that, when invoked, change the behavior or - * syntax of Mustache. - * - * They should be considered extremely experimental. Most likely their implementation - * will change in the future. - */ - - /** - * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}} - * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be - * escaped while the {{{unescaped}}} tag will be escaped. - * - * Pragmas apply only to the current template. Partials, even those included after the - * {{%UNESCAPED}} call, will need their own pragma declaration. - * - * This may be useful in non-HTML Mustache situations. - */ - const PRAGMA_UNESCAPED = 'UNESCAPED'; - - /** - * Constants used for section and tag RegEx - */ - const SECTION_TYPES = '\^#\/'; - const TAG_TYPES = '#\^\/=!<>\\{&'; - - protected $_otag = '{{'; - protected $_ctag = '}}'; - - protected $_tagRegEx; - - protected $_template = ''; - protected $_context = array(); - protected $_partials = array(); - protected $_pragmas = array(); - - protected $_pragmasImplemented = array( - self::PRAGMA_UNESCAPED - ); - - protected $_localPragmas = array(); + // Environment + private $templateClassPrefix = '__Mustache_'; + private $cache = null; + private $loader; + private $partialsLoader; + private $charset = 'UTF-8'; /** * Mustache class constructor. * - * This method accepts a $template string and a $view object. Optionally, pass an associative - * array of partials as well. - * * Passing an $options array allows overriding certain Mustache options during instantiation: * * $options = array( - * // `charset` -- must be supported by `htmlspecialentities()`. defaults to 'UTF-8' + * // The class prefix for compiled templates. Defaults to '__Mustache_' + * 'template_class_prefix' => '\My\Namespace\Template\', + * + * // A cache directory for compiled templates. Mustache will not cache templates unless this is set + * 'cache' => __DIR__.'/tmp/cache/mustache', + * + * // A Mustache template loader instance. Uses a StringLoader if not specified + * 'loader' => new \Mustache\Loader\FilesystemLoader(__DIR__.'/views'), + * + * // A Mustache loader instance for partials. + * 'partials_loader' => new \Mustache\Loader\FilesystemLoader(__DIR__.'/views/partials'), + * + * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as + * // efficient or lazy as a Filesystem (or database) loader. + * 'partials' => array('foo' => file_get_contents(__DIR__.'/views/partials/foo.mustache')), + * + * // character set for `htmlspecialchars`. Defaults to 'UTF-8' * 'charset' => 'ISO-8859-1', - * - * // opening and closing delimiters, as an array or a space-separated string - * 'delimiters' => '<% %>', - * - * // an array of pragmas to enable/disable - * 'pragmas' => array( - * Mustache::PRAGMA_UNESCAPED => true - * ), - * - * // an array of thrown exceptions to enable/disable - * 'throws_exceptions' => array( - * MustacheException::UNKNOWN_VARIABLE => false, - * MustacheException::UNCLOSED_SECTION => true, - * MustacheException::UNEXPECTED_CLOSE_SECTION => true, - * MustacheException::UNKNOWN_PARTIAL => false, - * MustacheException::UNKNOWN_PRAGMA => true, - * ), * ); * - * @access public - * @param string $template (default: null) - * @param mixed $view (default: null) - * @param array $partials (default: null) * @param array $options (default: array()) - * @return void */ - public function __construct($template = null, $view = null, $partials = null, array $options = null) { - if ($template !== null) $this->_template = $template; - if ($partials !== null) $this->_partials = $partials; - if ($view !== null) $this->_context = array($view); - if ($options !== null) $this->_setOptions($options); - } + public function __construct(array $options = array()) { + if (isset($options['template_class_prefix'])) { + $this->templateClassPrefix = $options['template_class_prefix']; + } + + if (isset($options['cache'])) { + $this->cache = $options['cache']; + } + + if (isset($options['loader'])) { + $this->setLoader($options['loader']); + } + + if (isset($options['partials_loader'])) { + $this->setPartialsLoader($options['partials_loader']); + } + + if (isset($options['partials'])) { + $this->setPartials($options['partials']); + } - /** - * Helper function for setting options from constructor args. - * - * @access protected - * @param array $options - * @return void - */ - protected function _setOptions(array $options) { if (isset($options['charset'])) { - $this->_charset = $options['charset']; - } - - if (isset($options['delimiters'])) { - $delims = $options['delimiters']; - if (!is_array($delims)) { - $delims = array_map('trim', explode(' ', $delims, 2)); - } - $this->_otag = $delims[0]; - $this->_ctag = $delims[1]; - } - - if (isset($options['pragmas'])) { - foreach ($options['pragmas'] as $pragma_name => $pragma_value) { - if (!in_array($pragma_name, $this->_pragmasImplemented, true)) { - throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); - } - } - $this->_pragmas = $options['pragmas']; - } - - if (isset($options['throws_exceptions'])) { - foreach ($options['throws_exceptions'] as $exception => $value) { - $this->_throwsExceptions[$exception] = $value; - } + $this->charset = $options['charset']; } } /** - * Mustache class clone method. + * Get the current Mustache character set. * - * A cloned Mustache instance should have pragmas, delimeters and root context - * reset to default values. - * - * @access public - * @return void - */ - public function __clone() { - $this->_otag = '{{'; - $this->_ctag = '}}'; - $this->_localPragmas = array(); - - if ($keys = array_keys($this->_context)) { - $last = array_pop($keys); - if ($this->_context[$last] instanceof Mustache) { - $this->_context[$last] =& $this; - } - } - } - - /** - * Render the given template and view object. - * - * Defaults to the template and view passed to the class constructor unless a new one is provided. - * Optionally, pass an associative array of partials as well. - * - * @access public - * @param string $template (default: null) - * @param mixed $view (default: null) - * @param array $partials (default: null) - * @return string Rendered Mustache template. - */ - public function render($template = null, $view = null, $partials = null) { - if ($template === null) $template = $this->_template; - if ($partials !== null) $this->_partials = $partials; - - $otag_orig = $this->_otag; - $ctag_orig = $this->_ctag; - - if ($view) { - $this->_context = array($view); - } else if (empty($this->_context)) { - $this->_context = array($this); - } - - $template = $this->_renderPragmas($template); - $template = $this->_renderTemplate($template); - - $this->_otag = $otag_orig; - $this->_ctag = $ctag_orig; - - return $template; - } - - /** - * Wrap the render() function for string conversion. - * - * @access public * @return string */ - public function __toString() { - // PHP doesn't like exceptions in __toString. - // catch any exceptions and convert them to strings. - try { - $result = $this->render(); - return $result; - } catch (Exception $e) { - return "Error rendering mustache: " . $e->getMessage(); - } + public function getCharset() { + return $this->charset; } /** - * Internal render function, used for recursive calls. + * Set the Mustache template Loader instance. * - * @access protected - * @param string $template - * @return string Rendered Mustache template. + * @param \Mustache\Loader $loader */ - protected function _renderTemplate($template) { - if ($section = $this->_findSection($template)) { - list($before, $type, $tag_name, $content, $after) = $section; + public function setLoader(Loader $loader) { + $this->loader = $loader; + } - $rendered_before = $this->_renderTags($before); - - $rendered_content = ''; - $val = $this->_getVariable($tag_name); - switch($type) { - // inverted section - case '^': - if (empty($val)) { - $rendered_content = $this->_renderTemplate($content); - } - break; - - // regular section - case '#': - // higher order sections - if ($this->_varIsCallable($val)) { - $rendered_content = $this->_renderTemplate(call_user_func($val, $content)); - } else if ($this->_varIsIterable($val)) { - foreach ($val as $local_context) { - $this->_pushContext($local_context); - $rendered_content .= $this->_renderTemplate($content); - $this->_popContext(); - } - } else if ($val) { - if (is_array($val) || is_object($val)) { - $this->_pushContext($val); - $rendered_content = $this->_renderTemplate($content); - $this->_popContext(); - } else { - $rendered_content = $this->_renderTemplate($content); - } - } - break; - } - - return $rendered_before . $rendered_content . $this->_renderTemplate($after); + /** + * Get the current Mustache template Loader instance. + * + * If no Loader instance has been explicitly specified, this method will instantiate and return + * a StringLoader instance. + * + * @return \Mustache\Loader + */ + public function getLoader() { + if (!isset($this->loader)) { + $this->loader = new StringLoader; } - return $this->_renderTags($template); + return $this->loader; } /** - * Prepare a section RegEx string for the given opening/closing tags. + * Set the Mustache partials Loader instance. * - * @access protected - * @param string $otag - * @param string $ctag - * @return string + * @param \Mustache\Loader $partialsLoader */ - protected function _prepareSectionRegEx($otag, $ctag) { - return sprintf( - '/(?:(?<=\\n)[ \\t]*)?%s(?:(?P[%s])(?P.+?)|=(?P.*?)=)%s\\n?/s', - preg_quote($otag, '/'), - self::SECTION_TYPES, - preg_quote($ctag, '/') - ); + public function setPartialsLoader(Loader $partialsLoader) { + $this->partialsLoader = $partialsLoader; } /** - * Extract the first section from $template. + * Get the current Mustache partials Loader instance. * - * @access protected - * @param string $template - * @return array $before, $type, $tag_name, $content and $after + * If no Loader instance has been explicitly specified, this method will instantiate and return + * an ArrayLoader instance. + * + * @return \Mustache\Loader */ - protected function _findSection($template) { - $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag); + public function getPartialsLoader() { + if (!isset($this->partialsLoader)) { + $this->partialsLoader = new ArrayLoader; + } - $section_start = null; - $section_type = null; - $content_start = null; + return $this->partialsLoader; + } - $search_offset = 0; + /** + * Set partials for the current partials Loader instance. + * + * @throws \RuntimeException If the current Loader instance is immutable + * + * @param array $partials (default: array()) + */ + public function setPartials(array $partials = array()) { + $loader = $this->getPartialsLoader(); + if (!$loader instanceof MutableLoader) { + throw new \RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); + } - $section_stack = array(); - $matches = array(); - while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) { - if (isset($matches['delims'][0])) { - list($otag, $ctag) = explode(' ', $matches['delims'][0]); - $regEx = $this->_prepareSectionRegEx($otag, $ctag); - $search_offset = $matches[0][1] + strlen($matches[0][0]); - continue; - } + $loader->setTemplates($partials); + } - $match = $matches[0][0]; - $offset = $matches[0][1]; - $type = $matches['type'][0]; - $tag_name = trim($matches['tag_name'][0]); + /** + * Set the Mustache Tokenizer instance. + * + * @param \Mustache\Tokenizer $tokenizer + */ + public function setTokenizer(Tokenizer $tokenizer) { + $this->tokenizer = $tokenizer; + } - $search_offset = $offset + strlen($match); + /** + * Get the current Mustache Tokenizer instance. + * + * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return \Mustache\Tokenizer + */ + public function getTokenizer() { + if (!isset($this->tokenizer)) { + $this->tokenizer = new Tokenizer; + } - switch ($type) { - case '^': - case '#': - if (empty($section_stack)) { - $section_start = $offset; - $section_type = $type; - $content_start = $search_offset; - } - array_push($section_stack, $tag_name); - break; - case '/': - if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) { - if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) { - throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION); - } + return $this->tokenizer; + } + + /** + * Set the Mustache Parser instance. + * + * @param \Mustache\Parser $tokenizer + */ + public function setParser(Parser $parser) { + $this->parser = $parser; + } + + /** + * Get the current Mustache Parser instance. + * + * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return \Mustache\Parser + */ + public function getParser() { + if (!isset($this->parser)) { + $this->parser = new Parser; + } + + return $this->parser; + } + + /** + * Set the Mustache Compiler instance. + * + * @param \Mustache\Compiler $tokenizer + */ + public function setCompiler(Compiler $compiler) { + $this->compiler = $compiler; + } + + /** + * Get the current Mustache Compiler instance. + * + * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return \Mustache\Compiler + */ + public function getCompiler() { + if (!isset($this->compiler)) { + $this->compiler = new Compiler; + } + + return $this->compiler; + } + + /** + * Helper method to generate a Mustache template class. + * + * @param string $source + * + * @return string Mustache Template class name + */ + public function getTemplateClassName($source) { + return $this->templateClassPrefix . md5(self::VERSION . ':' . $source); + } + + /** + * Load a Mustache Template by name. + * + * @param string $name + * + * @return \Mustache\Template + */ + public function loadTemplate($name) { + return $this->loadSource($this->getLoader()->load($name)); + } + + /** + * Load a Mustache partial Template by name. + * + * This is a helper method used internally by Template instances for loading partial templates. You can most likely + * ignore it completely. + * + * @param string $name + * + * @return \Mustache\Template + */ + public function loadPartial($name) { + return $this->loadSource($this->getPartialsLoader()->load($name)); + } + + /** + * Load a Mustache lambda Template by source. + * + * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most + * likely ignore it completely. + * + * @param string $source + * @param string $delims (default: null) + * + * @return \Mustache\Template + */ + public function loadLambda($source, $delims = null) { + if ($delims !== null) { + $source = $delims . "\n" . $source; + } + + return $this->loadSource($source); + } + + /** + * Instantiate and return a Mustache Template instance by source. + * + * @see \Mustache\Mustache::loadTemplate + * @see \Mustache\Mustache::loadPartial + * @see \Mustache\Mustache::loadLambda + * + * @param string $source + * + * @return \Mustache\Template + */ + private function loadSource($source) { + $className = $this->getTemplateClassName($source); + + if (!isset($this->templates[$className])) { + if (!class_exists($className, false)) { + if ($fileName = $this->getCacheFilename($source)) { + if (!is_file($fileName)) { + $this->writeCacheFile($fileName, $this->compile($source)); } - if (empty($section_stack)) { - // $before, $type, $tag_name, $content, $after - return array( - substr($template, 0, $section_start), - $section_type, - $tag_name, - substr($template, $content_start, $offset - $content_start), - substr($template, $search_offset), - ); - } - break; - } - } - - if (!empty($section_stack)) { - if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) { - throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION); - } - } - } - - /** - * Prepare a pragma RegEx for the given opening/closing tags. - * - * @access protected - * @param string $otag - * @param string $ctag - * @return string - */ - protected function _preparePragmaRegEx($otag, $ctag) { - return sprintf( - '/%s%%\\s*(?P[\\w_-]+)(?P(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s', - preg_quote($otag, '/'), - preg_quote($ctag, '/') - ); - } - - /** - * Initialize pragmas and remove all pragma tags. - * - * @access protected - * @param string $template - * @return string - */ - protected function _renderPragmas($template) { - $this->_localPragmas = $this->_pragmas; - - // no pragmas - if (strpos($template, $this->_otag . '%') === false) { - return $template; - } - - $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag); - return preg_replace_callback($regEx, array($this, '_renderPragma'), $template); - } - - /** - * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma. - * - * @access protected - * @param mixed $matches - * @return void - * @throws MustacheException unknown pragma - */ - protected function _renderPragma($matches) { - $pragma = $matches[0]; - $pragma_name = $matches['pragma_name']; - $options_string = $matches['options_string']; - - if (!in_array($pragma_name, $this->_pragmasImplemented)) { - if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) { - throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); - } else { - return ''; - } - } - - $options = array(); - foreach (explode(' ', trim($options_string)) as $o) { - if ($p = trim($o)) { - $p = explode('=', $p); - $options[$p[0]] = $p[1]; - } - } - - if (empty($options)) { - $this->_localPragmas[$pragma_name] = true; - } else { - $this->_localPragmas[$pragma_name] = $options; - } - - return ''; - } - - /** - * Check whether this Mustache has a specific pragma. - * - * @access protected - * @param string $pragma_name - * @return bool - */ - protected function _hasPragma($pragma_name) { - if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) { - return true; - } else { - return false; - } - } - - /** - * Return pragma options, if any. - * - * @access protected - * @param string $pragma_name - * @return mixed - * @throws MustacheException Unknown pragma - */ - protected function _getPragmaOptions($pragma_name) { - if (!$this->_hasPragma($pragma_name)) { - if ($this->_throwsException(MustacheException::UNKNOWN_PRAGMA)) { - throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); - } - } - - return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array(); - } - - /** - * Check whether this Mustache instance throws a given exception. - * - * Expects exceptions to be MustacheException error codes (i.e. class constants). - * - * @access protected - * @param mixed $exception - * @return void - */ - protected function _throwsException($exception) { - return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]); - } - - /** - * Prepare a tag RegEx for the given opening/closing tags. - * - * @access protected - * @param string $otag - * @param string $ctag - * @return string - */ - protected function _prepareTagRegEx($otag, $ctag, $first = false) { - return sprintf( - '/(?P(?:%s\\r?\\n)[ \\t]*)?%s(?P[%s]?)(?P.+?)(?:\\2|})?%s(?P\\s*(?:\\r?\\n|\\Z))?/s', - ($first ? '\\A|' : ''), - preg_quote($otag, '/'), - self::TAG_TYPES, - preg_quote($ctag, '/') - ); - } - - /** - * Loop through and render individual Mustache tags. - * - * @access protected - * @param string $template - * @return void - */ - protected function _renderTags($template) { - if (strpos($template, $this->_otag) === false) { - return $template; - } - - $first = true; - $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true); - - $html = ''; - $matches = array(); - while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) { - $tag = $matches[0][0]; - $offset = $matches[0][1]; - $modifier = $matches['type'][0]; - $tag_name = trim($matches['tag_name'][0]); - - if (isset($matches['leading']) && $matches['leading'][1] > -1) { - $leading = $matches['leading'][0]; - } else { - $leading = null; - } - - if (isset($matches['trailing']) && $matches['trailing'][1] > -1) { - $trailing = $matches['trailing'][0]; - } else { - $trailing = null; - } - - $html .= substr($template, 0, $offset); - - $next_offset = $offset + strlen($tag); - if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) { - $next_offset++; - } - $template = substr($template, $next_offset); - - $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing); - - if ($first == true) { - $first = false; - $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); - } - } - - return $html . $template; - } - - /** - * Render the named tag, given the specified modifier. - * - * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial) - * `{` or `&` (don't escape output), or none (render escaped output). - * - * @access protected - * @param string $modifier - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @throws MustacheException Unmatched section tag encountered. - * @return string - */ - protected function _renderTag($modifier, $tag_name, $leading, $trailing) { - switch ($modifier) { - case '=': - return $this->_changeDelimiter($tag_name, $leading, $trailing); - break; - case '!': - return $this->_renderComment($tag_name, $leading, $trailing); - break; - case '>': - case '<': - return $this->_renderPartial($tag_name, $leading, $trailing); - break; - case '{': - // strip the trailing } ... - if ($tag_name[(strlen($tag_name) - 1)] == '}') { - $tag_name = substr($tag_name, 0, -1); - } - case '&': - if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { - return $this->_renderEscaped($tag_name, $leading, $trailing); + require_once $fileName; } else { - return $this->_renderUnescaped($tag_name, $leading, $trailing); + eval('?>'.$this->compile($source)); } - break; - case '#': - case '^': - case '/': - // remove any leftover section tags - return $leading . $trailing; - break; - default: - if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { - return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing); - } else { - return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing); - } - break; - } - } - - /** - * Returns true if any of its args contains the "\r" character. - * - * @access protected - * @param string $str - * @return boolean - */ - protected function _stringHasR($str) { - foreach (func_get_args() as $arg) { - if (strpos($arg, "\r") !== false) { - return true; } + + $this->templates[$className] = new $className($this); } - return false; + + return $this->templates[$className]; } /** - * Escape and return the requested tag. + * Helper method to tokenize a Mustache template. * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string + * @see \Mustache\Tokenizer::scan + * + * @param string $source + * + * @return array Tokens */ - protected function _renderEscaped($tag_name, $leading, $trailing) { - $rendered = htmlentities($this->_renderUnescaped($tag_name, '', ''), ENT_COMPAT, $this->_charset); - return $leading . $rendered . $trailing; + private function tokenize($source) { + return $this->getTokenizer()->scan($source); } /** - * Render a comment (i.e. return an empty string). + * Helper method to parse a Mustache template. * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string + * @see \Mustache\Parser::parse + * + * @param string $source + * + * @return array Token tree */ - protected function _renderComment($tag_name, $leading, $trailing) { - if ($leading !== null && $trailing !== null) { - if (strpos($leading, "\n") === false) { - return ''; - } - return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; - } - return $leading . $trailing; + private function parse($source) { + return $this->getParser()->parse($this->tokenize($source)); } /** - * Return the requested tag unescaped. + * Helper method to compile a Mustache template. * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string + * @see \Mustache\Compiler::compile + * + * @param string $source + * + * @return string generated Mustache template class code */ - protected function _renderUnescaped($tag_name, $leading, $trailing) { - $val = $this->_getVariable($tag_name); - - if ($this->_varIsCallable($val)) { - $val = $this->_renderTemplate(call_user_func($val)); - } - - return $leading . $val . $trailing; + private function compile($source) { + return $this->getCompiler()->compile($source, $this->parse($source), $this->getTemplateClassName($source)); } /** - * Render the requested partial. + * Helper method to generate a Mustache Template class cache filename. * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string + * @param string $source + * + * @return string Mustache Template class cache filename */ - protected function _renderPartial($tag_name, $leading, $trailing) { - $partial = $this->_getPartial($tag_name); - if ($leading !== null && $trailing !== null) { - $whitespace = trim($leading, "\r\n"); - $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial); - } - - $view = clone($this); - - if ($leading !== null && $trailing !== null) { - return $leading . $view->render($partial); - } else { - return $leading . $view->render($partial) . $trailing; + private function getCacheFilename($source) { + if ($this->cache) { + return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source)); } } /** - * Change the Mustache tag delimiter. This method also replaces this object's current - * tag RegEx with one using the new delimiters. + * Helper method to dump a generated Mustache Template subclass to the file cache. * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string + * @throws \RuntimeException if unable to write to $fileName. + * + * @param string $fileName + * @param string $source */ - protected function _changeDelimiter($tag_name, $leading, $trailing) { - list($otag, $ctag) = explode(' ', $tag_name); - $this->_otag = $otag; - $this->_ctag = $ctag; - - $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); - - if ($leading !== null && $trailing !== null) { - if (strpos($leading, "\n") === false) { - return ''; - } - return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; + private function writeCacheFile($fileName, $source) { + if (!is_dir(dirname($fileName))) { + mkdir(dirname($fileName), 0777, true); } - return $leading . $trailing; - } - /** - * Push a local context onto the stack. - * - * @access protected - * @param array &$local_context - * @return void - */ - protected function _pushContext(&$local_context) { - $new = array(); - $new[] =& $local_context; - foreach (array_keys($this->_context) as $key) { - $new[] =& $this->_context[$key]; - } - $this->_context = $new; - } + $tempFile = tempnam(dirname($fileName), basename($fileName)); + if (false !== @file_put_contents($tempFile, $source)) { + if (@rename($tempFile, $fileName)) { + chmod($fileName, 0644); - /** - * Remove the latest context from the stack. - * - * @access protected - * @return void - */ - protected function _popContext() { - $new = array(); - - $keys = array_keys($this->_context); - array_shift($keys); - foreach ($keys as $key) { - $new[] =& $this->_context[$key]; - } - $this->_context = $new; - } - - /** - * Get a variable from the context array. - * - * If the view is an array, returns the value with array key $tag_name. - * If the view is an object, this will check for a public member variable - * named $tag_name. If none is available, this method will execute and return - * any class method named $tag_name. Failing all of the above, this method will - * return an empty string. - * - * @access protected - * @param string $tag_name - * @throws MustacheException Unknown variable name. - * @return string - */ - protected function _getVariable($tag_name) { - if ($tag_name === '.') { - return $this->_context[0]; - } else if (strpos($tag_name, '.') !== false) { - $chunks = explode('.', $tag_name); - $first = array_shift($chunks); - - $ret = $this->_findVariableInContext($first, $this->_context); - foreach ($chunks as $next) { - // Slice off a chunk of context for dot notation traversal. - $c = array($ret); - $ret = $this->_findVariableInContext($next, $c); - } - return $ret; - } else { - return $this->_findVariableInContext($tag_name, $this->_context); - } - } - - /** - * Get a variable from the context array. Internal helper used by getVariable() to abstract - * variable traversal for dot notation. - * - * @access protected - * @param string $tag_name - * @param array $context - * @throws MustacheException Unknown variable name. - * @return string - */ - protected function _findVariableInContext($tag_name, $context) { - foreach ($context as $view) { - if (is_object($view)) { - if (method_exists($view, $tag_name)) { - return $view->$tag_name(); - } else if (isset($view->$tag_name)) { - return $view->$tag_name; - } - } else if (is_array($view) && array_key_exists($tag_name, $view)) { - return $view[$tag_name]; + return; } } - if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) { - throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE); - } else { - return ''; - } - } - - /** - * Retrieve the partial corresponding to the requested tag name. - * - * Silently fails (i.e. returns '') when the requested partial is not found. - * - * @access protected - * @param string $tag_name - * @throws MustacheException Unknown partial name. - * @return string - */ - protected function _getPartial($tag_name) { - if ((is_array($this->_partials) || $this->_partials instanceof ArrayAccess) && isset($this->_partials[$tag_name])) { - return $this->_partials[$tag_name]; - } - - if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) { - throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL); - } else { - return ''; - } - } - - /** - * Check whether the given $var should be iterated (i.e. in a section context). - * - * @access protected - * @param mixed $var - * @return bool - */ - protected function _varIsIterable($var) { - return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var)))); - } - - /** - * Higher order sections helper: tests whether the section $var is a valid callback. - * - * In Mustache.php, a variable is considered 'callable' if the variable is: - * - * 1. an anonymous function. - * 2. an object and the name of a public function, i.e. `array($SomeObject, 'methodName')` - * 3. a class name and the name of a public static function, i.e. `array('SomeClass', 'methodName')` - * - * @access protected - * @param mixed $var - * @return bool - */ - protected function _varIsCallable($var) { - return !is_string($var) && is_callable($var); + throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); } } - - -/** - * MustacheException class. - * - * @extends Exception - */ -class MustacheException extends Exception { - - // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found - // in the current context. - const UNKNOWN_VARIABLE = 0; - - // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed. - const UNCLOSED_SECTION = 1; - - // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears - // without a corresponding {{#section}} or {{^section}}. - const UNEXPECTED_CLOSE_SECTION = 2; - - // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears - // with no associated partial. - const UNKNOWN_PARTIAL = 3; - - // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears - // which can't be handled by this Mustache instance. - const UNKNOWN_PRAGMA = 4; - -} diff --git a/src/Mustache/MustacheLoader.php b/src/Mustache/MustacheLoader.php deleted file mode 100644 index 9c4b386..0000000 --- a/src/Mustache/MustacheLoader.php +++ /dev/null @@ -1,85 +0,0 @@ -baseDir = $baseDir; - $this->extension = $extension; - } - - /** - * @param string $offset Name of partial - * @return boolean - */ - public function offsetExists($offset) { - return (isset($this->partialsCache[$offset]) || file_exists($this->pathName($offset))); - } - - /** - * @throws InvalidArgumentException if the given partial doesn't exist - * @param string $offset Name of partial - * @return string Partial template contents - */ - public function offsetGet($offset) { - if (!$this->offsetExists($offset)) { - throw new InvalidArgumentException('Partial does not exist: ' . $offset); - } - - if (!isset($this->partialsCache[$offset])) { - $this->partialsCache[$offset] = file_get_contents($this->pathName($offset)); - } - - return $this->partialsCache[$offset]; - } - - /** - * MustacheLoader is an immutable filesystem loader. offsetSet throws a LogicException if called. - * - * @throws LogicException - * @return void - */ - public function offsetSet($offset, $value) { - throw new LogicException('Unable to set offset: MustacheLoader is an immutable ArrayAccess object.'); - } - - /** - * MustacheLoader is an immutable filesystem loader. offsetUnset throws a LogicException if called. - * - * @throws LogicException - * @return void - */ - public function offsetUnset($offset) { - throw new LogicException('Unable to unset offset: MustacheLoader is an immutable ArrayAccess object.'); - } - - /** - * An internal helper for generating path names. - * - * @param string $file Partial name - * @return string File path - */ - protected function pathName($file) { - return $this->baseDir . '/' . $file . '.' . $this->extension; - } -} diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php new file mode 100644 index 0000000..d330913 --- /dev/null +++ b/src/Mustache/Parser.php @@ -0,0 +1,80 @@ +buildTree(new \ArrayIterator($tokens)); + } + + /** + * Helper method for recursively building a parse tree. + * + * @throws \LogicException when nesting errors or mismatched section tags are encountered. + * + * @param \ArrayIterator $tokens Stream of Mustache tokens + * @param array $parent Parent token (default: null) + * + * @return array Mustache Token parse tree + */ + private function buildTree(\ArrayIterator $tokens, array $parent = null) { + $nodes = array(); + + do { + $token = $tokens->current(); + $tokens->next(); + + if ($token === null) { + continue; + } elseif (is_array($token)) { + switch ($token[Tokenizer::TAG]) { + case '#': + case '^': + $nodes[] = $this->buildTree($tokens, $token); + break; + + case '/': + if (!isset($parent)) { + throw new \LogicException('Unexpected closing tag: /'. $token[Tokenizer::NAME]); + } + + if ($token[Tokenizer::NAME] !== $parent[Tokenizer::NAME]) { + throw new \LogicException('Nesting error: ' . $parent[Tokenizer::NAME] . ' vs. ' . $token[Tokenizer::NAME]); + } + + $parent[Tokenizer::END] = $token[Tokenizer::INDEX]; + $parent[Tokenizer::NODES] = $nodes; + + return $parent; + break; + + default: + $nodes[] = $token; + break; + } + } else { + $nodes[] = $token; + } + + } while($tokens->valid()); + + if (isset($parent)) { + throw new \LogicException('Missing closing tag: ' . $parent[Tokenizer::NAME]); + } + + return $nodes; + } +} diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php new file mode 100644 index 0000000..a641593 --- /dev/null +++ b/src/Mustache/Template.php @@ -0,0 +1,66 @@ +mustache = $mustache; + } + + /** + * Mustache Template instances can be treated as a function and rendered by simply calling them: + * + * $m = new Mustache; + * $tpl = $m->loadTemplate('Hello, {{ name }}!'); + * echo $tpl(array('name' => 'World')); // "Hello, World!" + * + * @see \Mustache\Template::render + * + * @param mixed $context Array or object rendering context (default: array()) + * + * @return string Rendered template + */ + public function __invoke($context = array()) { + return $this->render($context); + } + + /** + * Render this template given the rendering context. + * + * @param mixed $context Array or object rendering context (default: array()) + * + * @return string Rendered template + */ + public function render($context = array()) { + return $this->renderInternal(new Context($context)); + } + + /** + * Internal rendering method implemented by Mustache Template concrete subclasses. + * + * This is where the magic happens :) + * + * @abstract + * + * @param \Mustache\Context $context + * + * @return string Rendered template + */ + abstract public function renderInternal(Context $context); +} diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php new file mode 100644 index 0000000..1074397 --- /dev/null +++ b/src/Mustache/Tokenizer.php @@ -0,0 +1,262 @@ + self::T_SECTION, + '^' => self::T_INVERTED, + '/' => self::T_END_SECTION, + '!' => self::T_COMMENT, + '>' => self::T_PARTIAL, + '<' => self::T_PARTIAL_2, + '=' => self::T_DELIM_CHANGE, + '_v' => self::T_ESCAPED, + '{' => self::T_UNESCAPED, + '&' => self::T_UNESCAPED_2, + ); + + // Token properties + const NODES = 'nodes'; + const TAG = 'tag'; + const NAME = 'name'; + const OTAG = 'otag'; + const CTAG = 'ctag'; + const INDEX = 'index'; + const END = 'end'; + const INDENT = 'indent'; + + private $state; + private $tagType; + private $tag; + private $buf; + private $tokens; + private $seenTag; + private $lineStart; + private $otag; + private $ctag; + + /** + * Scan and tokenize template source. + * + * @param string $text Mustache template source to tokenize + * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null) + * + * @return array Set of Mustache tokens + */ + public function scan($text, $delimiters = null) { + $this->reset(); + + if ($delimiters = trim($delimiters)) { + list($otag, $ctag) = explode(' ', $delimiters); + $this->otag = $otag; + $this->ctag = $ctag; + } + + $len = strlen($text); + for ($i = 0; $i < $len; $i++) { + switch ($this->state) { + case self::IN_TEXT: + if ($this->tagChange($this->otag, $text, $i)) { + $i--; + $this->flushBuffer(); + $this->state = self::IN_TAG_TYPE; + } else { + if ($text[$i] == "\n") { + $this->filterLine(); + } else { + $this->buffer .= $text[$i]; + } + } + break; + + case self::IN_TAG_TYPE: + $i += strlen($this->otag) - 1; + $tag = isset(self::$tagTypes[$text[$i + 1]]) ? self::$tagTypes[$text[$i + 1]] : null; + $this->tagType = $tag ? $text[$i + 1] : '_v'; + if ($this->tagType === '=') { + $i = $this->changeDelimiters($text, $i); + $this->state = self::IN_TEXT; + } else { + if ($tag) { + $i++; + } + $this->state = self::IN_TAG; + } + $this->seenTag = $i; + break; + + default: + if ($this->tagChange($this->ctag, $text, $i)) { + $this->tokens[] = array( + self::TAG => $this->tagType, + self::NAME => trim($this->buffer), + self::OTAG => $this->otag, + self::CTAG => $this->ctag, + self::INDEX => ($this->tagType == '/') ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) + ); + + $this->buffer = ''; + $i += strlen($this->ctag) - 1; + $this->state = self::IN_TEXT; + if ($this->tagType == '{') { + if ($this->ctag == '}}') { + $i++; + } else { + $this->cleanTripleStache($this->tokens[count($this->tokens) - 1]); + } + } + } else { + $this->buffer .= $text[$i]; + } + break; + } + } + + $this->filterLine(true); + + return $this->tokens; + } + + /** + * Helper function to reset tokenizer internal state. + */ + private function reset() { + $this->state = self::IN_TEXT; + $this->tagType = null; + $this->tag = null; + $this->buffer = ''; + $this->tokens = array(); + $this->seenTag = false; + $this->lineStart = 0; + $this->otag = '{{'; + $this->ctag = '}}'; + } + + /** + * Flush the current buffer to a token. + */ + private function flushBuffer() { + if (!empty($this->buffer)) { + $this->tokens[] = $this->buffer; + $this->buffer = ''; + } + } + + /** + * Test whether the current line is entirely made up of whitespace. + * + * @return boolean True if the current line is all whitespace + */ + private function lineIsWhitespace() { + $tokensCount = count($this->tokens); + for ($j = $this->lineStart; $j < $tokensCount; $j++) { + $token = $this->tokens[$j]; + if (is_array($token) && isset(self::$tagTypes[$token[self::TAG]])) { + if (self::$tagTypes[$token[self::TAG]] >= self::T_ESCAPED) { + return false; + } + } elseif (is_string($token)) { + if (preg_match('/\S/', $token)) { + return false; + } + } + } + + return true; + } + + /** + * Filter out whitespace-only lines and store indent levels for partials. + * + * @param bool $noNewLine Suppress the newline? (default: false) + */ + private function filterLine($noNewLine = false) { + $this->flushBuffer(); + if ($this->seenTag && $this->lineIsWhitespace()) { + $tokensCount = count($this->tokens); + for ($j = $this->lineStart; $j < $tokensCount; $j++) { + if (!is_array($this->tokens[$j])) { + if (isset($this->tokens[$j+1]) && is_array($this->tokens[$j+1]) && $this->tokens[$j+1][self::TAG] == '>') { + $this->tokens[$j+1][self::INDENT] = (string) $this->tokens[$j]; + } + + $this->tokens[$j] = null; + } + } + } elseif (!$noNewLine) { + $this->tokens[] = "\n"; + } + + $this->seenTag = false; + $this->lineStart = count($this->tokens); + } + + /** + * Change the current Mustache delimiters. Set new `otag` and `ctag` values. + * + * @param string $text Mustache template source + * @param int $index Current tokenizer index + * + * @return int New index value + */ + private function changeDelimiters($text, $index) { + $startIndex = strpos($text, '=', $index) + 1; + $close = '='.$this->ctag; + $closeIndex = strpos($text, $close, $index); + + list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex))); + $this->otag = $otag; + $this->ctag = $ctag; + + return $closeIndex + strlen($close) - 1; + } + + /** + * Clean up `{{{ tripleStache }}}` style tokens. + * + * @param array &$token + */ + private function cleanTripleStache(&$token) { + if (substr($token[self::NAME], -1) === '}') { + $token[self::NAME] = trim(substr($token[self::NAME], 0, -1)); + } + } + + /** + * Test whether it's time to change tags. + * + * @param string $tag Current tag name + * @param string $text Mustache template source + * @param int $index Current tokenizer index + * + * @return boolean True if this is a closing section tag + */ + private function tagChange($tag, $text, $index) { + return substr($text, $index, strlen($tag)) === $tag; + } +} diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100644 index 0000000..f022da1 --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,16 @@ + Date: Wed, 29 Feb 2012 18:02:16 -0800 Subject: [PATCH 03/58] Update `examples` for v2.0 --- examples/child_context/ChildContext.php | 6 +++--- examples/comments/Comments.php | 4 ++-- examples/complex/complex.php | 4 ++-- examples/delimiters/Delimiters.php | 4 ++-- examples/dot_notation/DotNotation.php | 12 +++--------- examples/dot_notation/dot_notation.mustache | 3 +-- examples/dot_notation/dot_notation.txt | 3 +-- examples/double_section/DoubleSection.php | 4 ++-- examples/escaped/Escaped.php | 4 ++-- .../GrandParentContext.php | 12 +++++------- examples/i18n/I18n.php | 8 ++++---- .../implicit_iterator/ImplicitIterator.php | 6 +++--- .../InvertedDoubleSection.php | 4 ++-- examples/inverted_section/InvertedSection.php | 4 ++-- .../inverted_section.mustache | 8 ++++++-- .../inverted_section/inverted_section.txt | 2 +- examples/partials/Partials.php | 8 ++------ examples/partials/partials/children.mustache | 2 ++ .../PartialsWithViewClass.php | 19 ------------------- .../partials_with_view_class.mustache | 2 -- .../partials_with_view_class.txt | 3 --- examples/pragma_unescaped/PragmaUnescaped.php | 5 ----- .../pragma_unescaped.mustache | 3 --- .../pragma_unescaped/pragma_unescaped.txt | 2 -- .../pragmas_in_partials/PragmasInPartials.php | 8 -------- .../pragmas_in_partials.mustache | 3 --- .../pragmas_in_partials.txt | 2 -- .../recursive_partials/RecursivePartials.php | 8 ++------ .../partials/child.mustache | 1 + .../SectionIteratorObjects.php | 4 ++-- .../SectionMagicObjects.php | 4 ++-- examples/section_objects/SectionObjects.php | 4 ++-- examples/sections/Sections.php | 4 ++-- examples/sections_nested/SectionsNested.php | 4 ++-- examples/simple/Simple.php | 4 ++-- examples/unescaped/Unescaped.php | 4 ++-- examples/utf8/UTF8.php | 4 ++-- examples/utf8_unescaped/UTF8Unescaped.php | 4 ++-- examples/whitespace/Whitespace.php | 10 ++-------- .../whitespace/partials/alphabet.mustache | 1 + 40 files changed, 69 insertions(+), 132 deletions(-) create mode 100644 examples/partials/partials/children.mustache delete mode 100644 examples/partials_with_view_class/PartialsWithViewClass.php delete mode 100644 examples/partials_with_view_class/partials_with_view_class.mustache delete mode 100644 examples/partials_with_view_class/partials_with_view_class.txt delete mode 100644 examples/pragma_unescaped/PragmaUnescaped.php delete mode 100644 examples/pragma_unescaped/pragma_unescaped.mustache delete mode 100644 examples/pragma_unescaped/pragma_unescaped.txt delete mode 100644 examples/pragmas_in_partials/PragmasInPartials.php delete mode 100644 examples/pragmas_in_partials/pragmas_in_partials.mustache delete mode 100644 examples/pragmas_in_partials/pragmas_in_partials.txt create mode 100644 examples/recursive_partials/partials/child.mustache create mode 100644 examples/whitespace/partials/alphabet.mustache diff --git a/examples/child_context/ChildContext.php b/examples/child_context/ChildContext.php index b652356..95eb5a6 100644 --- a/examples/child_context/ChildContext.php +++ b/examples/child_context/ChildContext.php @@ -1,13 +1,13 @@ 'child works', ); - + public $grandparent = array( 'parent' => array( 'child' => 'grandchild works', ), ); -} \ No newline at end of file +} diff --git a/examples/comments/Comments.php b/examples/comments/Comments.php index 7f028ba..6eb7da1 100644 --- a/examples/comments/Comments.php +++ b/examples/comments/Comments.php @@ -1,7 +1,7 @@ item) === 0; } -} \ No newline at end of file +} diff --git a/examples/delimiters/Delimiters.php b/examples/delimiters/Delimiters.php index be372fa..4dac04d 100644 --- a/examples/delimiters/Delimiters.php +++ b/examples/delimiters/Delimiters.php @@ -1,6 +1,6 @@ array('first' => 'Chris', 'last' => 'Firescythe'), 'age' => 24, - 'hobbies' => array('Cycling', 'Fishing'), 'hometown' => array( - 'city' => 'Cincinnati', + 'city' => 'Cincinnati', 'state' => 'OH', - ), + ) ); public $normal = 'Normal'; diff --git a/examples/dot_notation/dot_notation.mustache b/examples/dot_notation/dot_notation.mustache index 0135a2a..0566867 100644 --- a/examples/dot_notation/dot_notation.mustache +++ b/examples/dot_notation/dot_notation.mustache @@ -1,5 +1,4 @@ * {{person.name.first}} {{person.name.last}} * {{person.age}} -* {{person.hobbies.0}}, {{person.hobbies.1}} * {{person.hometown.city}}, {{person.hometown.state}} -* {{normal}} +* {{normal}} \ No newline at end of file diff --git a/examples/dot_notation/dot_notation.txt b/examples/dot_notation/dot_notation.txt index e5c1ed9..f8cf1fa 100644 --- a/examples/dot_notation/dot_notation.txt +++ b/examples/dot_notation/dot_notation.txt @@ -1,5 +1,4 @@ * Chris Firescythe * 24 -* Cycling, Fishing * Cincinnati, OH -* Normal +* Normal \ No newline at end of file diff --git a/examples/double_section/DoubleSection.php b/examples/double_section/DoubleSection.php index f9d3dbb..31fdfc5 100644 --- a/examples/double_section/DoubleSection.php +++ b/examples/double_section/DoubleSection.php @@ -1,9 +1,9 @@ "Shark"'; -} \ No newline at end of file +} diff --git a/examples/grand_parent_context/GrandParentContext.php b/examples/grand_parent_context/GrandParentContext.php index 5a59ed9..6829372 100644 --- a/examples/grand_parent_context/GrandParentContext.php +++ b/examples/grand_parent_context/GrandParentContext.php @@ -1,24 +1,22 @@ parent_contexts[] = array('parent_id' => 'parent1', 'child_contexts' => array( array('child_id' => 'parent1-child1'), array('child_id' => 'parent1-child2') )); - + $parent2 = new stdClass(); $parent2->parent_id = 'parent2'; $parent2->child_contexts = array( array('child_id' => 'parent2-child1'), array('child_id' => 'parent2-child2') ); - + $this->parent_contexts[] = $parent2; } -} \ No newline at end of file +} diff --git a/examples/i18n/I18n.php b/examples/i18n/I18n.php index 980e649..73cdd74 100644 --- a/examples/i18n/I18n.php +++ b/examples/i18n/I18n.php @@ -1,6 +1,6 @@ 'Hola.', 'My name is {{ name }}.' => 'Me llamo {{ name }}.', ); public function __trans($text) { - return isset($this->dictionary[$text]) ? $this->dictionary[$text] : $text; + return isset(self::$dictionary[$text]) ? self::$dictionary[$text] : $text; } -} \ No newline at end of file +} diff --git a/examples/implicit_iterator/ImplicitIterator.php b/examples/implicit_iterator/ImplicitIterator.php index c01fef0..d52ac58 100644 --- a/examples/implicit_iterator/ImplicitIterator.php +++ b/examples/implicit_iterator/ImplicitIterator.php @@ -1,5 +1,5 @@ {{name}}{{/repo}} -{{^repo}}No repos :({{/repo}} \ No newline at end of file +{{#repo}} + {{name}} +{{/repo}} +{{^repo}} + No repos :( +{{/repo}} \ No newline at end of file diff --git a/examples/inverted_section/inverted_section.txt b/examples/inverted_section/inverted_section.txt index 2b9ed3f..6ba5a99 100644 --- a/examples/inverted_section/inverted_section.txt +++ b/examples/inverted_section/inverted_section.txt @@ -1 +1 @@ -No repos :( \ No newline at end of file + No repos :( diff --git a/examples/partials/Partials.php b/examples/partials/Partials.php index 093257b..19f627a 100644 --- a/examples/partials/Partials.php +++ b/examples/partials/Partials.php @@ -1,13 +1,9 @@ 'federica', 'age' => 27, 'gender' => 'female'), array('name' => 'marco', 'age' => 32, 'gender' => 'male'), ); - - protected $_partials = array( - 'children' => "{{#data}}{{name}} - {{age}} - {{gender}}\n{{/data}}", - ); -} \ No newline at end of file +} diff --git a/examples/partials/partials/children.mustache b/examples/partials/partials/children.mustache new file mode 100644 index 0000000..9506a28 --- /dev/null +++ b/examples/partials/partials/children.mustache @@ -0,0 +1,2 @@ +{{#data}}{{name}} - {{age}} - {{gender}} +{{/data}} \ No newline at end of file diff --git a/examples/partials_with_view_class/PartialsWithViewClass.php b/examples/partials_with_view_class/PartialsWithViewClass.php deleted file mode 100644 index 56e0d86..0000000 --- a/examples/partials_with_view_class/PartialsWithViewClass.php +++ /dev/null @@ -1,19 +0,0 @@ -name = 'ilmich'; - $view->data = array( - array('name' => 'federica', 'age' => 27, 'gender' => 'female'), - array('name' => 'marco', 'age' => 32, 'gender' => 'male'), - ); - - $partials = array( - 'children' => "{{#data}}{{name}} - {{age}} - {{gender}}\n{{/data}}", - ); - - parent::__construct($template, $view, $partials); - } -} \ No newline at end of file diff --git a/examples/partials_with_view_class/partials_with_view_class.mustache b/examples/partials_with_view_class/partials_with_view_class.mustache deleted file mode 100644 index 037e1b3..0000000 --- a/examples/partials_with_view_class/partials_with_view_class.mustache +++ /dev/null @@ -1,2 +0,0 @@ -Children of {{name}}: -{{>children}} \ No newline at end of file diff --git a/examples/partials_with_view_class/partials_with_view_class.txt b/examples/partials_with_view_class/partials_with_view_class.txt deleted file mode 100644 index d967e15..0000000 --- a/examples/partials_with_view_class/partials_with_view_class.txt +++ /dev/null @@ -1,3 +0,0 @@ -Children of ilmich: -federica - 27 - female -marco - 32 - male diff --git a/examples/pragma_unescaped/PragmaUnescaped.php b/examples/pragma_unescaped/PragmaUnescaped.php deleted file mode 100644 index b4e0e21..0000000 --- a/examples/pragma_unescaped/PragmaUnescaped.php +++ /dev/null @@ -1,5 +0,0 @@ - Shark'; -} \ No newline at end of file diff --git a/examples/pragma_unescaped/pragma_unescaped.mustache b/examples/pragma_unescaped/pragma_unescaped.mustache deleted file mode 100644 index 76095d7..0000000 --- a/examples/pragma_unescaped/pragma_unescaped.mustache +++ /dev/null @@ -1,3 +0,0 @@ -{{%UNESCAPED}} -{{vs}} -{{{vs}}} \ No newline at end of file diff --git a/examples/pragma_unescaped/pragma_unescaped.txt b/examples/pragma_unescaped/pragma_unescaped.txt deleted file mode 100644 index 2860f61..0000000 --- a/examples/pragma_unescaped/pragma_unescaped.txt +++ /dev/null @@ -1,2 +0,0 @@ -Bear > Shark -Bear > Shark \ No newline at end of file diff --git a/examples/pragmas_in_partials/PragmasInPartials.php b/examples/pragmas_in_partials/PragmasInPartials.php deleted file mode 100644 index 7458289..0000000 --- a/examples/pragmas_in_partials/PragmasInPartials.php +++ /dev/null @@ -1,8 +0,0 @@ -'; - protected $_partials = array( - 'dinosaur' => '{{say}}' - ); -} \ No newline at end of file diff --git a/examples/pragmas_in_partials/pragmas_in_partials.mustache b/examples/pragmas_in_partials/pragmas_in_partials.mustache deleted file mode 100644 index abd6ef4..0000000 --- a/examples/pragmas_in_partials/pragmas_in_partials.mustache +++ /dev/null @@ -1,3 +0,0 @@ -{{%UNESCAPED}} -{{say}} -{{>dinosaur}} \ No newline at end of file diff --git a/examples/pragmas_in_partials/pragmas_in_partials.txt b/examples/pragmas_in_partials/pragmas_in_partials.txt deleted file mode 100644 index c8e77e3..0000000 --- a/examples/pragmas_in_partials/pragmas_in_partials.txt +++ /dev/null @@ -1,2 +0,0 @@ -< RAWR!! > -< RAWR!! > \ No newline at end of file diff --git a/examples/recursive_partials/RecursivePartials.php b/examples/recursive_partials/RecursivePartials.php index 04e8af8..b3c5f56 100644 --- a/examples/recursive_partials/RecursivePartials.php +++ b/examples/recursive_partials/RecursivePartials.php @@ -1,10 +1,6 @@ " > {{ name }}{{#child}}{{>child}}{{/child}}", - ); - +class RecursivePartials { public $name = 'George'; public $child = array( 'name' => 'Dan', @@ -13,4 +9,4 @@ class RecursivePartials extends Mustache { 'child' => false, ) ); -} \ No newline at end of file +} diff --git a/examples/recursive_partials/partials/child.mustache b/examples/recursive_partials/partials/child.mustache new file mode 100644 index 0000000..1282941 --- /dev/null +++ b/examples/recursive_partials/partials/child.mustache @@ -0,0 +1 @@ + > {{ name }}{{#child}}{{>child}}{{/child}} \ No newline at end of file diff --git a/examples/section_iterator_objects/SectionIteratorObjects.php b/examples/section_iterator_objects/SectionIteratorObjects.php index 7b65597..9a14418 100644 --- a/examples/section_iterator_objects/SectionIteratorObjects.php +++ b/examples/section_iterator_objects/SectionIteratorObjects.php @@ -1,6 +1,6 @@ _data[$key]); } -} \ No newline at end of file +} diff --git a/examples/section_objects/SectionObjects.php b/examples/section_objects/SectionObjects.php index 41b7d84..8d9f101 100644 --- a/examples/section_objects/SectionObjects.php +++ b/examples/section_objects/SectionObjects.php @@ -1,6 +1,6 @@ Shark"; -} \ No newline at end of file +} diff --git a/examples/utf8/UTF8.php b/examples/utf8/UTF8.php index 7843f53..258fa70 100644 --- a/examples/utf8/UTF8.php +++ b/examples/utf8/UTF8.php @@ -1,5 +1,5 @@ tag }}` and `{{> tag}}` and `{{>tag}}` should all be equivalent. - * - * @extends Mustache */ -class Whitespace extends Mustache { +class Whitespace { public $foo = 'alpha'; public $bar = 'beta'; @@ -30,8 +28,4 @@ class Whitespace extends Mustache { array('key with space' => 'G'), ); } - - protected $_partials = array( - 'alphabet' => " * {{.}}\n", - ); -} \ No newline at end of file +} diff --git a/examples/whitespace/partials/alphabet.mustache b/examples/whitespace/partials/alphabet.mustache new file mode 100644 index 0000000..d281c41 --- /dev/null +++ b/examples/whitespace/partials/alphabet.mustache @@ -0,0 +1 @@ + * {{.}} \ No newline at end of file From 8710e4b8a4b36dffba565b19a4e173c476518dbf Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 29 Feb 2012 18:45:38 -0800 Subject: [PATCH 04/58] Rearrange legacy tests. --- .../CallTest.php} | 0 .../Mustache/Test/Functional/ExamplesTest.php | 130 +++++++++++++++ .../HigherOrderSectionsTest.php} | 0 .../MustacheInjectionTest.php | 0 .../{ => Functional}/MustacheSpecTest.php | 0 .../ObjectSectionTest.php} | 0 .../FilesystemLoaderTest.php} | 0 test/Mustache/Test/MustacheExceptionTest.php | 152 ------------------ test/Mustache/Test/MustachePragmaTest.php | 74 --------- .../Test/MustachePragmaUnescapedTest.php | 19 --- test/fixtures/bar.mustache | 1 - test/fixtures/foo.mustache | 1 - 12 files changed, 130 insertions(+), 247 deletions(-) rename test/Mustache/Test/{MustacheCallTest.php => Functional/CallTest.php} (100%) create mode 100644 test/Mustache/Test/Functional/ExamplesTest.php rename test/Mustache/Test/{MustacheHigherOrderSectionsTest.php => Functional/HigherOrderSectionsTest.php} (100%) rename test/Mustache/Test/{ => Functional}/MustacheInjectionTest.php (100%) rename test/Mustache/Test/{ => Functional}/MustacheSpecTest.php (100%) rename test/Mustache/Test/{MustacheObjectSectionTest.php => Functional/ObjectSectionTest.php} (100%) rename test/Mustache/Test/{MustacheLoaderTest.php => Loader/FilesystemLoaderTest.php} (100%) delete mode 100644 test/Mustache/Test/MustacheExceptionTest.php delete mode 100644 test/Mustache/Test/MustachePragmaTest.php delete mode 100644 test/Mustache/Test/MustachePragmaUnescapedTest.php delete mode 100644 test/fixtures/bar.mustache delete mode 100644 test/fixtures/foo.mustache diff --git a/test/Mustache/Test/MustacheCallTest.php b/test/Mustache/Test/Functional/CallTest.php similarity index 100% rename from test/Mustache/Test/MustacheCallTest.php rename to test/Mustache/Test/Functional/CallTest.php diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php new file mode 100644 index 0000000..5635dd2 --- /dev/null +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -0,0 +1,130 @@ + $partials + )); + $this->assertEquals($expected, $mustache->loadTemplate($source)->render($context)); + } + + /** + * Data provider for testExamples method. + * + * Assumes that an `examples` directory exists inside parent directory. + * This examples directory should contain any number of subdirectories, each of which contains + * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file + * (.txt). + * + * This whole mess will be refined later to be more intuitive and less prescriptive, but it'll + * do for now. Especially since it means we can have unit tests :) + * + * @return array + */ + public function getExamples() { + $path = realpath(__DIR__.'/../../../../examples'); + $examples = array(); + + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } + + $fullpath = $path.'/'.$file; + if (is_dir($fullpath)) { + $examples[$file] = $this->loadExample($fullpath); + } + } + closedir($handle); + + return $examples; + } + + /** + * Helper method to load an example given the full path. + * + * @param string $path + * @return array arguments for testExamples + */ + private function loadExample($path) { + $context = null; + $source = null; + $partials = array(); + $expected = null; + + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + $fullpath = $path.'/'.$file; + $info = pathinfo($fullpath); + + if (is_dir($fullpath) && $info['basename'] == 'partials') { + // load partials + $partials = $this->loadPartials($fullpath); + } elseif (is_file($fullpath)) { + // load other files + switch ($info['extension']) { + case 'php': + require_once($fullpath); + $context = new $info['filename']; + break; + + case 'mustache': + $source = file_get_contents($fullpath); + break; + + case 'txt': + $expected = file_get_contents($fullpath); + break; + } + } + } + closedir($handle); + + return array($context, $source, $partials, $expected); + } + + /** + * Helper method to load partials given an example directory. + * + * @param string $path + * + * @return array $partials + */ + private function loadPartials($path) { + $partials = array(); + + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } + + $fullpath = $path.'/'.$file; + $info = pathinfo($fullpath); + + if ($info['extension'] === 'mustache') { + $partials[$info['filename']] = file_get_contents($fullpath); + } + } + closedir($handle); + + return $partials; + } +} diff --git a/test/Mustache/Test/MustacheHigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php similarity index 100% rename from test/Mustache/Test/MustacheHigherOrderSectionsTest.php rename to test/Mustache/Test/Functional/HigherOrderSectionsTest.php diff --git a/test/Mustache/Test/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php similarity index 100% rename from test/Mustache/Test/MustacheInjectionTest.php rename to test/Mustache/Test/Functional/MustacheInjectionTest.php diff --git a/test/Mustache/Test/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php similarity index 100% rename from test/Mustache/Test/MustacheSpecTest.php rename to test/Mustache/Test/Functional/MustacheSpecTest.php diff --git a/test/Mustache/Test/MustacheObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php similarity index 100% rename from test/Mustache/Test/MustacheObjectSectionTest.php rename to test/Mustache/Test/Functional/ObjectSectionTest.php diff --git a/test/Mustache/Test/MustacheLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php similarity index 100% rename from test/Mustache/Test/MustacheLoaderTest.php rename to test/Mustache/Test/Loader/FilesystemLoaderTest.php diff --git a/test/Mustache/Test/MustacheExceptionTest.php b/test/Mustache/Test/MustacheExceptionTest.php deleted file mode 100644 index 2a40223..0000000 --- a/test/Mustache/Test/MustacheExceptionTest.php +++ /dev/null @@ -1,152 +0,0 @@ -pickyMustache = new PickyMustache(); - $this->slackerMustache = new SlackerMustache(); - } - - /** - * @group interpolation - * @expectedException MustacheException - */ - public function testThrowsUnknownVariableException() { - $this->pickyMustache->render('{{not_a_variable}}'); - } - - /** - * @group sections - * @expectedException MustacheException - */ - public function testThrowsUnclosedSectionException() { - $this->pickyMustache->render('{{#unclosed}}'); - } - - /** - * @group sections - * @expectedException MustacheException - */ - public function testThrowsUnclosedInvertedSectionException() { - $this->pickyMustache->render('{{^unclosed}}'); - } - - /** - * @group sections - * @expectedException MustacheException - */ - public function testThrowsUnexpectedCloseSectionException() { - $this->pickyMustache->render('{{/unopened}}'); - } - - /** - * @group partials - * @expectedException MustacheException - */ - public function testThrowsUnknownPartialException() { - $this->pickyMustache->render('{{>impartial}}'); - } - - /** - * @group pragmas - * @expectedException MustacheException - */ - public function testThrowsUnknownPragmaException() { - $this->pickyMustache->render('{{%SWEET-MUSTACHE-BRO}}'); - } - - /** - * @group sections - */ - public function testDoesntThrowUnclosedSectionException() { - $this->assertEquals('', $this->slackerMustache->render('{{#unclosed}}')); - } - - /** - * @group sections - */ - public function testDoesntThrowUnexpectedCloseSectionException() { - $this->assertEquals('', $this->slackerMustache->render('{{/unopened}}')); - } - - /** - * @group partials - */ - public function testDoesntThrowUnknownPartialException() { - $this->assertEquals('', $this->slackerMustache->render('{{>impartial}}')); - } - - /** - * @group pragmas - * @expectedException MustacheException - */ - public function testGetPragmaOptionsThrowsExceptionsIfItThinksYouHaveAPragmaButItTurnsOutYouDont() { - $mustache = new TestableMustache(); - $mustache->testableGetPragmaOptions('PRAGMATIC'); - } - - public function testOverrideThrownExceptionsViaConstructorOptions() { - $exceptions = array( - MustacheException::UNKNOWN_VARIABLE, - MustacheException::UNCLOSED_SECTION, - MustacheException::UNEXPECTED_CLOSE_SECTION, - MustacheException::UNKNOWN_PARTIAL, - MustacheException::UNKNOWN_PRAGMA, - ); - - $one = new TestableMustache(null, null, null, array( - 'throws_exceptions' => array_fill_keys($exceptions, true) - )); - - $thrownExceptions = $one->getThrownExceptions(); - foreach ($exceptions as $exception) { - $this->assertTrue($thrownExceptions[$exception]); - } - - $two = new TestableMustache(null, null, null, array( - 'throws_exceptions' => array_fill_keys($exceptions, false) - )); - - $thrownExceptions = $two->getThrownExceptions(); - foreach ($exceptions as $exception) { - $this->assertFalse($thrownExceptions[$exception]); - } - } -} - -class PickyMustache extends Mustache { - protected $_throwsExceptions = array( - MustacheException::UNKNOWN_VARIABLE => true, - MustacheException::UNCLOSED_SECTION => true, - MustacheException::UNEXPECTED_CLOSE_SECTION => true, - MustacheException::UNKNOWN_PARTIAL => true, - MustacheException::UNKNOWN_PRAGMA => true, - ); -} - -class SlackerMustache extends Mustache { - protected $_throwsExceptions = array( - MustacheException::UNKNOWN_VARIABLE => false, - MustacheException::UNCLOSED_SECTION => false, - MustacheException::UNEXPECTED_CLOSE_SECTION => false, - MustacheException::UNKNOWN_PARTIAL => false, - MustacheException::UNKNOWN_PRAGMA => false, - ); -} - -class TestableMustache extends Mustache { - public function testableGetPragmaOptions($pragma_name) { - return $this->_getPragmaOptions($pragma_name); - } - - public function getThrownExceptions() { - return $this->_throwsExceptions; - } -} diff --git a/test/Mustache/Test/MustachePragmaTest.php b/test/Mustache/Test/MustachePragmaTest.php deleted file mode 100644 index c00441c..0000000 --- a/test/Mustache/Test/MustachePragmaTest.php +++ /dev/null @@ -1,74 +0,0 @@ -render('{{%I-HAVE-THE-GREATEST-MUSTACHE}}'); - } catch (MustacheException $e) { - $this->assertEquals(MustacheException::UNKNOWN_PRAGMA, $e->getCode(), 'Caught exception code was not MustacheException::UNKNOWN_PRAGMA'); - return; - } - - $this->fail('Mustache should have thrown an unknown pragma exception'); - } - - public function testSuppressUnknownPragmaException() { - $m = new LessWhinyMustache(); - - try { - $this->assertEquals('', $m->render('{{%I-HAVE-THE-GREATEST-MUSTACHE}}')); - } catch (MustacheException $e) { - if ($e->getCode() == MustacheException::UNKNOWN_PRAGMA) { - $this->fail('Mustache should have thrown an unknown pragma exception'); - } else { - throw $e; - } - } - } - - public function testPragmaReplace() { - $m = new Mustache(); - $this->assertEquals('', $m->render('{{%UNESCAPED}}'), 'Pragma tag not removed'); - } - - public function testPragmaReplaceMultiple() { - $m = new Mustache(); - - $this->assertEquals('', $m->render('{{% UNESCAPED }}'), 'Pragmas should allow whitespace'); - $this->assertEquals('', $m->render('{{% UNESCAPED foo=bar }}'), 'Pragmas should allow whitespace'); - $this->assertEquals('', $m->render("{{%UNESCAPED}}\n{{%UNESCAPED}}"), 'Multiple pragma tags not removed'); - $this->assertEquals(' ', $m->render('{{%UNESCAPED}} {{%UNESCAPED}}'), 'Multiple pragma tags not removed'); - } - - public function testPragmaReplaceNewline() { - $m = new Mustache(); - $this->assertEquals('', $m->render("{{%UNESCAPED}}\n"), 'Trailing newline after pragma tag not removed'); - $this->assertEquals("\n", $m->render("\n{{%UNESCAPED}}\n"), 'Too many newlines removed with pragma tag'); - $this->assertEquals("1\n23", $m->render("1\n2{{%UNESCAPED}}\n3"), 'Wrong newline removed with pragma tag'); - } - - public function testPragmaReset() { - $m = new Mustache('', array('symbol' => '>>>')); - $this->assertEquals('>>>', $m->render('{{{symbol}}}')); - $this->assertEquals('>>>', $m->render('{{%UNESCAPED}}{{symbol}}')); - $this->assertEquals('>>>', $m->render('{{{symbol}}}')); - } -} - -class LessWhinyMustache extends Mustache { - protected $_throwsExceptions = array( - MustacheException::UNKNOWN_VARIABLE => false, - MustacheException::UNCLOSED_SECTION => true, - MustacheException::UNEXPECTED_CLOSE_SECTION => true, - MustacheException::UNKNOWN_PARTIAL => false, - MustacheException::UNKNOWN_PRAGMA => false, - ); -} \ No newline at end of file diff --git a/test/Mustache/Test/MustachePragmaUnescapedTest.php b/test/Mustache/Test/MustachePragmaUnescapedTest.php deleted file mode 100644 index df6d94c..0000000 --- a/test/Mustache/Test/MustachePragmaUnescapedTest.php +++ /dev/null @@ -1,19 +0,0 @@ - 'Bear > Shark')); - - $this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{title}}')); - $this->assertEquals('Bear > Shark', $m->render('{{title}}')); - $this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{{title}}}')); - $this->assertEquals('Bear > Shark', $m->render('{{{title}}}')); - } - -} \ No newline at end of file diff --git a/test/fixtures/bar.mustache b/test/fixtures/bar.mustache deleted file mode 100644 index 139594d..0000000 --- a/test/fixtures/bar.mustache +++ /dev/null @@ -1 +0,0 @@ -{{# truthy }}{{ bar }}{{/ truthy }} \ No newline at end of file diff --git a/test/fixtures/foo.mustache b/test/fixtures/foo.mustache deleted file mode 100644 index 008c714..0000000 --- a/test/fixtures/foo.mustache +++ /dev/null @@ -1 +0,0 @@ -{{ foo }} \ No newline at end of file From 0034bf657b1250277de1e31c043f043d7d10f087 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 29 Feb 2012 18:55:33 -0800 Subject: [PATCH 05/58] Add test coverage for Mustache.php 2.0 Update legacy tests for new codebase. --- test/Mustache/Test/BufferTest.php | 90 +++ test/Mustache/Test/CompilerTest.php | 75 +++ test/Mustache/Test/ContextTest.php | 150 +++++ test/Mustache/Test/Functional/CallTest.php | 17 +- .../Mustache/Test/Functional/ExamplesTest.php | 5 +- .../Functional/HigherOrderSectionsTest.php | 95 +-- .../Test/Functional/MustacheInjectionTest.php | 206 +++---- .../Test/Functional/MustacheSpecTest.php | 132 +++-- .../Test/Functional/ObjectSectionTest.php | 52 +- test/Mustache/Test/Loader/ArrayLoaderTest.php | 43 ++ .../Test/Loader/FilesystemLoaderTest.php | 79 +-- .../Mustache/Test/Loader/StringLoaderTest.php | 18 + test/Mustache/Test/MustacheTest.php | 551 ++++-------------- test/Mustache/Test/ParserTest.php | 157 +++++ test/Mustache/Test/TemplateTest.php | 43 ++ test/Mustache/Test/TokenizerTest.php | 117 ++++ 16 files changed, 1123 insertions(+), 707 deletions(-) create mode 100644 test/Mustache/Test/BufferTest.php create mode 100644 test/Mustache/Test/CompilerTest.php create mode 100644 test/Mustache/Test/ContextTest.php create mode 100644 test/Mustache/Test/Loader/ArrayLoaderTest.php create mode 100644 test/Mustache/Test/Loader/StringLoaderTest.php create mode 100644 test/Mustache/Test/ParserTest.php create mode 100644 test/Mustache/Test/TemplateTest.php create mode 100644 test/Mustache/Test/TokenizerTest.php diff --git a/test/Mustache/Test/BufferTest.php b/test/Mustache/Test/BufferTest.php new file mode 100644 index 0000000..4fd886c --- /dev/null +++ b/test/Mustache/Test/BufferTest.php @@ -0,0 +1,90 @@ +assertEquals($indent, $buffer->getIndent()); + $this->assertEquals($charset, $buffer->getCharset()); + } + + public function getConstructorArgs() { + return array( + array('', 'UTF-8'), + array(' ', 'ISO-8859-1'), + array("\t\t\t", 'Shift_JIS'), + ); + } + + public function testWrite() { + $buffer = new Buffer; + $this->assertEquals('', $buffer->flush()); + + $buffer->writeLine(); + $buffer->writeLine(); + $buffer->writeLine(); + $this->assertEquals("\n\n\n", $buffer->flush()); + $this->assertEquals('', $buffer->flush()); + + $buffer->write('foo'); + $buffer->write('bar'); + $buffer->writeLine(); + $buffer->write('baz'); + $this->assertEquals("foobar\nbaz", $buffer->flush()); + $this->assertEquals('', $buffer->flush()); + + $indent = "\t\t"; + $buffer->setIndent($indent); + $buffer->writeText('foo'); + $buffer->writeLine(); + $buffer->writeText('bar'); + $this->assertEquals("\t\tfoo\n\t\tbar", $buffer->flush()); + $this->assertEquals('', $buffer->flush()); + } + + /** + * @dataProvider getEscapeAndIndent + */ + public function testEscapingAndIndenting($text, $escape, $indent, $whitespace, $expected) { + $buffer = new Buffer; + $buffer->setIndent($whitespace); + + $buffer->write($text, $indent, $escape); + $this->assertEquals($expected, $buffer->flush()); + } + + public function getEscapeAndIndent() { + return array( + array('> "fun & games" <', false, false, "\t", '> "fun & games" <'), + array('> "fun & games" <', true, false, "\t", '> "fun & games" <'), + array('> "fun & games" <', true, true, "\t", "\t> "fun & games" <"), + array('> "fun & games" <', false, true, "\t", "\t> \"fun & games\" <"), + ); + } + + public function testChangeIndent() { + $indent = "\t\t"; + $buffer = new Buffer($indent); + $this->assertEquals($indent, $buffer->getIndent()); + + $indent = ""; + $buffer->setIndent($indent); + $this->assertEquals($indent, $buffer->getIndent()); + + $indent = " "; + $buffer->setIndent($indent); + $this->assertEquals($indent, $buffer->getIndent()); + } + +} diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php new file mode 100644 index 0000000..c9abe1e --- /dev/null +++ b/test/Mustache/Test/CompilerTest.php @@ -0,0 +1,75 @@ +compile($source, $tree, $name); + foreach ($expected as $contains) { + $this->assertContains($contains, $compiled); + } + } + + public function getCompileValues() { + return array( + array('', array(), 'Banana', array( + "\nclass Banana extends \Mustache\Template", + '$buffer->flush();', + )), + + array('', array('TEXT'), 'Monkey', array( + "\nclass Monkey extends \Mustache\Template", + '$buffer->writeText(\'TEXT\');', + '$buffer->flush();', + )), + + array( + '', + array( + 'foo', + "\n", + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name', + ), + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => '.', + ), + "'bar'", + ), + 'Monkey', + array( + "\nclass Monkey extends \Mustache\Template", + '$buffer->writeText(\'foo\');', + '$buffer->writeLine();', + '$value = $context->find(\'name\');', + '$buffer->writeText($value, true);', + '$value = $context->last();', + '$buffer->writeText(\'\\\'bar\\\'\');', + '$buffer->flush();', + ) + ), + ); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testCompilerThrowsUnknownNodeTypeException() { + $compiler = new Compiler; + $compiler->compile('', array(array(Tokenizer::TAG => 'invalid')), 'SomeClass'); + } +} diff --git a/test/Mustache/Test/ContextTest.php b/test/Mustache/Test/ContextTest.php new file mode 100644 index 0000000..678e976 --- /dev/null +++ b/test/Mustache/Test/ContextTest.php @@ -0,0 +1,150 @@ +assertSame('', $one->find('foo')); + $this->assertSame('', $one->find('bar')); + + $two = new Context(array( + 'foo' => 'FOO', + 'bar' => '' + )); + $this->assertEquals('FOO', $two->find('foo')); + $this->assertEquals('', $two->find('bar')); + + $obj = new \StdClass; + $obj->name = 'NAME'; + $three = new Context($obj); + $this->assertSame($obj, $three->last()); + $this->assertEquals('NAME', $three->find('name')); + } + + public function testIsTruthy() { + $context = new Context; + + $this->assertTrue($context->isTruthy('string')); + $this->assertTrue($context->isTruthy(new \StdClass)); + $this->assertTrue($context->isTruthy(1)); + $this->assertTrue($context->isTruthy(array('a', 'b'))); + + $this->assertFalse($context->isTruthy(null)); + $this->assertFalse($context->isTruthy('')); + $this->assertFalse($context->isTruthy(0)); + $this->assertFalse($context->isTruthy(array())); + } + + public function testIsCallable() { + $dummy = new TestDummy; + $context = new Context; + + $this->assertTrue($context->isCallable(function() { return null; })); + $this->assertTrue($context->isCallable(array('\Mustache\Test\TestDummy', 'foo'))); + $this->assertTrue($context->isCallable(array($dummy, 'bar'))); + $this->assertTrue($context->isCallable($dummy)); + + $this->assertFalse($context->isCallable('count')); + $this->assertFalse($context->isCallable('TestDummy::foo')); + $this->assertFalse($context->isCallable(array('\Mustache\Test\TestDummy', 'name'))); + $this->assertFalse($context->isCallable(array('NotReallyAClass', 'foo'))); + $this->assertFalse($context->isCallable(array($dummy, 'name'))); + } + + /** + * @dataProvider getIterables + */ + public function testIsIterable($value, $iterable) { + $context = new Context; + $this->assertEquals($iterable, $context->isIterable($value)); + } + + public function getIterables() { + return array( + array(array(0 => 'a', 1 => 'b'), true), + array(array(0 => 'a', 2 => 'b'), false), + array(array(1 => 'a', 2 => 'b'), false), + array(array('a' => 0, 'b' => 1), false), + array('some string', false), + array(new \ArrayIterator, true), + ); + } + + public function testPushPopAndLast() { + $context = new Context; + $this->assertFalse($context->last()); + + $dummy = new TestDummy; + $context->push($dummy); + $this->assertSame($dummy, $context->last()); + $this->assertSame($dummy, $context->pop()); + $this->assertFalse($context->last()); + + $obj = new \StdClass; + $context->push($dummy); + $this->assertSame($dummy, $context->last()); + $context->push($obj); + $this->assertSame($obj, $context->last()); + $this->assertSame($obj, $context->pop()); + $this->assertSame($dummy, $context->pop()); + $this->assertFalse($context->last()); + } + + public function testFind() { + $context = new Context; + + $dummy = new TestDummy; + + $obj = new \StdClass; + $obj->name = 'obj'; + + $arr = array( + 'a' => array('b' => array('c' => 'see')), + 'b' => 'bee', + ); + + $string = 'some arbitrary string'; + + $context->push($dummy); + $this->assertEquals('dummy', $context->find('name')); + + $context->push($obj); + $this->assertEquals('obj', $context->find('name')); + + $context->pop(); + $this->assertEquals('dummy', $context->find('name')); + + $dummy->name = 'dummyer'; + $this->assertEquals('dummyer', $context->find('name')); + + $context->push($arr); + $this->assertEquals('bee', $context->find('b')); + $this->assertEquals('see', $context->findDot('a.b.c')); + + $dummy->name = 'dummy'; + + $context->push($string); + $this->assertSame($string, $context->last()); + $this->assertEquals('dummy', $context->find('name')); + $this->assertEquals('see', $context->findDot('a.b.c')); + $this->assertEquals('', $context->find('foo')); + $this->assertEquals('', $context->findDot('bar')); + } +} + +class TestDummy { + public $name = 'dummy'; + public function __invoke() {} + public static function foo() { + return ''; + } + public function bar() { + return ''; + } +} diff --git a/test/Mustache/Test/Functional/CallTest.php b/test/Mustache/Test/Functional/CallTest.php index 366d2c4..0b0c342 100644 --- a/test/Mustache/Test/Functional/CallTest.php +++ b/test/Mustache/Test/Functional/CallTest.php @@ -1,18 +1,25 @@ loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); + $foo = new ClassWithCall(); $foo->name = 'Bob'; - $template = '{{# foo }}{{ label }}: {{ name }}{{/ foo }}'; $data = array('label' => 'name', 'foo' => $foo); - $m = new Mustache($template, $data); - $this->assertEquals('name: Bob', $m->render()); + $this->assertEquals('name: Bob', $tpl->render($data)); } } diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 5635dd2..6aff929 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -4,12 +4,15 @@ namespace Mustache\Test\Functional; use Mustache\Mustache; +/** + * @group examples + * @group functional + */ class ExamplesTest extends \PHPUnit_Framework_TestCase { /** * Test everything in the `examples` directory. * - * @group examples * @dataProvider getExamples * * @param string $context diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 87e4142..680efd7 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -1,93 +1,115 @@ foo = new Foo(); + $this->mustache = new Mustache; } public function testAnonymousFunctionSectionCallback() { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - $this->markTestSkipped('Unable to test anonymous function section callbacks in PHP < 5.3'); - return; - } + $tpl = $this->mustache->loadTemplate('{{#wrapper}}{{name}}{{/wrapper}}'); - $this->foo->wrapper = function($text) { + $foo = new Foo; + $foo->name = 'Mario'; + $foo->wrapper = function($text) { return sprintf('
%s
', $text); }; - $this->assertEquals( - sprintf('
%s
', $this->foo->name), - $this->foo->render('{{#wrapper}}{{name}}{{/wrapper}}') - ); + $this->assertEquals(sprintf('
%s
', $foo->name), $tpl->render($foo)); } public function testSectionCallback() { - $this->assertEquals(sprintf('%s', $this->foo->name), $this->foo->render('{{name}}')); - $this->assertEquals(sprintf('%s', $this->foo->name), $this->foo->render('{{#wrap}}{{name}}{{/wrap}}')); + $one = $this->mustache->loadTemplate('{{name}}'); + $two = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); + + $foo = new Foo; + $foo->name = 'Luigi'; + + $this->assertEquals($foo->name, $one->render($foo)); + $this->assertEquals(sprintf('%s', $foo->name), $two->render($foo)); } public function testRuntimeSectionCallback() { - $this->foo->double_wrap = array($this->foo, 'wrapWithBoth'); - $this->assertEquals( - sprintf('%s', $this->foo->name), - $this->foo->render('{{#double_wrap}}{{name}}{{/double_wrap}}') - ); + $tpl = $this->mustache->loadTemplate('{{#double_wrap}}{{name}}{{/double_wrap}}'); + + $foo = new Foo; + $foo->double_wrap = array($foo, 'wrapWithBoth'); + + $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); } public function testStaticSectionCallback() { - $this->foo->trimmer = array(get_class($this->foo), 'staticTrim'); - $this->assertEquals($this->foo->name, $this->foo->render('{{#trimmer}} {{name}} {{/trimmer}}')); + $tpl = $this->mustache->loadTemplate('{{#trimmer}} {{name}} {{/trimmer}}'); + + $foo = new Foo; + $foo->trimmer = array(get_class($foo), 'staticTrim'); + + $this->assertEquals($foo->name, $tpl->render($foo)); } public function testViewArraySectionCallback() { + $tpl = $this->mustache->loadTemplate('{{#trim}} {{name}} {{/trim}}'); + + $foo = new Foo; + $data = array( 'name' => 'Bob', - 'trim' => array(get_class($this->foo), 'staticTrim'), + 'trim' => array(get_class($foo), 'staticTrim'), ); - $this->assertEquals($data['name'], $this->foo->render('{{#trim}} {{name}} {{/trim}}', $data)); + + $this->assertEquals($data['name'], $tpl->render($data)); } public function testViewArrayAnonymousSectionCallback() { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - $this->markTestSkipped('Unable to test anonymous function section callbacks in PHP < 5.3'); - return; - } + $tpl = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); + $data = array( 'name' => 'Bob', 'wrap' => function($text) { return sprintf('[[%s]]', $text); } ); + $this->assertEquals( sprintf('[[%s]]', $data['name']), - $this->foo->render('{{#wrap}}{{name}}{{/wrap}}', $data) + $tpl->render($data) ); } public function testMonsters() { + $tpl = $this->mustache->loadTemplate('{{#title}}{{title}} {{/title}}{{name}}'); + $frank = new Monster(); $frank->title = 'Dr.'; $frank->name = 'Frankenstein'; - $this->assertEquals('Dr. Frankenstein', $frank->render()); + $this->assertEquals('Dr. Frankenstein', $tpl->render($frank)); $dracula = new Monster(); $dracula->title = 'Count'; $dracula->name = 'Dracula'; - $this->assertEquals('Count Dracula', $dracula->render()); + $this->assertEquals('Count Dracula', $tpl->render($dracula)); } } -class Foo extends Mustache { +class Foo { public $name = 'Justin'; public $lorem = 'Lorem ipsum dolor sit amet,'; public $wrap; - public function __construct($template = null, $view = null, $partials = null) { - $this->wrap = array($this, 'wrapWithEm'); - parent::__construct($template, $view, $partials); + public function __construct() { + $this->wrap = function($text) { + return sprintf('%s', $text); + }; } public function wrapWithEm($text) { @@ -107,8 +129,7 @@ class Foo extends Mustache { } } -class Monster extends Mustache { - public $_template = '{{#title}}{{title}} {{/title}}{{name}}'; +class Monster { public $title; public $name; -} \ No newline at end of file +} diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index de74943..eec0e1c 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -1,127 +1,127 @@ '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{ a }}'; - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + public function setUp() { + $this->mustache = new Mustache; + } - public function testUnescapedInterpolationInjection() { - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{{ a }}}'; - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + // interpolation + + public function testInterpolationInjection() { + $tpl = $this->mustache->loadTemplate('{{ a }}'); + + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); + + $this->assertEquals('{{ b }}', $tpl->render($data)); + } + + public function testUnescapedInterpolationInjection() { + $tpl = $this->mustache->loadTemplate('{{{ a }}}'); + + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); + + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - // sections + // sections - public function testSectionInjection() { - $data = array( - 'a' => true, - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); - $template = '{{# a }}{{ b }}{{/ a }}'; - $output = '{{ c }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + public function testSectionInjection() { + $tpl = $this->mustache->loadTemplate('{{# a }}{{ b }}{{/ a }}'); - public function testUnescapedSectionInjection() { - $data = array( - 'a' => true, - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); - $template = '{{# a }}{{{ b }}}{{/ a }}'; - $output = '{{ c }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + $data = array( + 'a' => true, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); + + $this->assertEquals('{{ c }}', $tpl->render($data)); + } + + public function testUnescapedSectionInjection() { + $tpl = $this->mustache->loadTemplate('{{# a }}{{{ b }}}{{/ a }}'); + + $data = array( + 'a' => true, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); + + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - // partials + // partials - public function testPartialInjection() { - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{> partial }}'; - $partials = array( - 'partial' => '{{ a }}', - ); - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data, $partials)); - } + public function testPartialInjection() { + $tpl = $this->mustache->loadTemplate('{{> partial }}'); + $this->mustache->setPartials(array( + 'partial' => '{{ a }}', + )); - public function testPartialUnescapedInjection() { - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{> partial }}'; - $partials = array( - 'partial' => '{{{ a }}}', - ); - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data, $partials)); - } + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); + + $this->assertEquals('{{ b }}', $tpl->render($data)); + } + + public function testPartialUnescapedInjection() { + $tpl = $this->mustache->loadTemplate('{{> partial }}'); + $this->mustache->setPartials(array( + 'partial' => '{{{ a }}}', + )); + + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); + + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - // lambdas + // lambdas - public function testLambdaInterpolationInjection() { - $data = array( - 'a' => array($this, 'interpolationLambda'), - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); - $template = '{{ a }}'; - $output = '{{ c }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + public function testLambdaInterpolationInjection() { + $tpl = $this->mustache->loadTemplate('{{ a }}'); - public function interpolationLambda() { - return '{{ b }}'; - } + $data = array( + 'a' => function() { return '{{ b }}'; }, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); - public function testLambdaSectionInjection() { - $data = array( - 'a' => array($this, 'sectionLambda'), - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); - $template = '{{# a }}b{{/ a }}'; - $output = '{{ c }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - public function sectionLambda($content) { - return '{{ ' . $content . ' }}'; - } + public function testLambdaSectionInjection() { + $tpl = $this->mustache->loadTemplate('{{# a }}b{{/ a }}'); -} \ No newline at end of file + $data = array( + 'a' => function ($text) { return '{{ ' . $text . ' }}'; }, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); + + $this->assertEquals('{{ c }}', $tpl->render($data)); + } +} diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index d3a3413..831a029 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -1,22 +1,30 @@ markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); } } @@ -25,56 +33,72 @@ class MustacheSpecTest extends PHPUnit_Framework_TestCase { * @group comments * @dataProvider loadCommentSpec */ - public function testCommentSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function testCommentSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); + } + + public function loadCommentSpec() { + return $this->loadSpec('comments'); } /** * @group delimiters * @dataProvider loadDelimitersSpec */ - public function testDelimitersSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function testDelimitersSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); + } + + public function loadDelimitersSpec() { + return $this->loadSpec('delimiters'); } /** * @group interpolation * @dataProvider loadInterpolationSpec */ - public function testInterpolationSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function testInterpolationSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); + } + + public function loadInterpolationSpec() { + return $this->loadSpec('interpolation'); } /** + * @group inverted * @group inverted-sections * @dataProvider loadInvertedSpec */ - public function testInvertedSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function testInvertedSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); + } + + public function loadInvertedSpec() { + return $this->loadSpec('inverted'); } /** * @group lambdas * @dataProvider loadLambdasSpec */ - public function testLambdasSpec($desc, $template, $data, $partials, $expected) { - if (!version_compare(PHP_VERSION, '5.3.0', '>=')) { - $this->markTestSkipped('Unable to test Lambdas spec with PHP < 5.3.'); - } + public function testLambdasSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($this->prepareLambdasSpec($data)), $desc); + } - $data = $this->prepareLambdasSpec($data); - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function loadLambdasSpec() { + return $this->loadSpec('~lambdas'); } /** * Extract and lambdafy any 'lambda' values found in the $data array. */ - protected function prepareLambdasSpec($data) { + private function prepareLambdasSpec($data) { foreach ($data as $key => $val) { if ($key === 'lambda') { if (!isset($val['php'])) { @@ -94,42 +118,22 @@ class MustacheSpecTest extends PHPUnit_Framework_TestCase { * @group partials * @dataProvider loadPartialsSpec */ - public function testPartialsSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); + public function testPartialsSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); + } + + public function loadPartialsSpec() { + return $this->loadSpec('partials'); } /** * @group sections * @dataProvider loadSectionsSpec */ - public function testSectionsSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - public function loadCommentSpec() { - return $this->loadSpec('comments'); - } - - public function loadDelimitersSpec() { - return $this->loadSpec('delimiters'); - } - - public function loadInterpolationSpec() { - return $this->loadSpec('interpolation'); - } - - public function loadInvertedSpec() { - return $this->loadSpec('inverted'); - } - - public function loadLambdasSpec() { - return $this->loadSpec('~lambdas'); - } - - public function loadPartialsSpec() { - return $this->loadSpec('partials'); + public function testSectionsSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($data), $desc); } public function loadSectionsSpec() { @@ -144,14 +148,14 @@ class MustacheSpecTest extends PHPUnit_Framework_TestCase { * @access public * @return array */ - protected function loadSpec($name) { - $filename = dirname(__FILE__) . '/spec/specs/' . $name . '.yml'; + private function loadSpec($name) { + $filename = __DIR__ . '/../../../spec/specs/' . $name . '.yml'; if (!file_exists($filename)) { return array(); } $data = array(); - $yaml = new sfYamlParser(); + $yaml = new \sfYamlParser; $file = file_get_contents($filename); // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. @@ -160,15 +164,23 @@ class MustacheSpecTest extends PHPUnit_Framework_TestCase { } $spec = $yaml->parse($file); + foreach ($spec['tests'] as $test) { $data[] = array( $test['name'] . ': ' . $test['desc'], $test['template'], - $test['data'], isset($test['partials']) ? $test['partials'] : array(), + $test['data'], $test['expected'], ); } + return $data; } -} \ No newline at end of file + + private static function loadTemplate($source, $partials) { + self::$mustache->setPartials($partials); + + return self::$mustache->loadTemplate($source); + } +} diff --git a/test/Mustache/Test/Functional/ObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php index 82405d6..ccf1ca6 100644 --- a/test/Mustache/Test/Functional/ObjectSectionTest.php +++ b/test/Mustache/Test/Functional/ObjectSectionTest.php @@ -1,48 +1,64 @@ mustache = new Mustache; + } + public function testBasicObject() { - $alpha = new Alpha(); - $this->assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $this->assertEquals('Foo', $tpl->render(new Alpha)); } + /** + * @group magic_methods + */ public function testObjectWithGet() { - $beta = new Beta(); - $this->assertEquals('Foo', $beta->render('{{#foo}}{{name}}{{/foo}}')); + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $this->assertEquals('Foo', $tpl->render(new Beta)); } + /** + * @group magic_methods + */ public function testSectionObjectWithGet() { - $gamma = new Gamma(); - $this->assertEquals('Foo', $gamma->render('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}')); + $tpl = $this->mustache->loadTemplate('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}'); + $this->assertEquals('Foo', $tpl->render(new Gamma)); } public function testSectionObjectWithFunction() { - $alpha = new Alpha(); - $alpha->foo = new Delta(); - $this->assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $alpha = new Alpha; + $alpha->foo = new Delta; + $this->assertEquals('Foo', $tpl->render($alpha)); } } -class Alpha extends Mustache { +class Alpha { public $foo; public function __construct() { - $this->foo = new StdClass(); + $this->foo = new \StdClass(); $this->foo->name = 'Foo'; $this->foo->number = 1; } } -class Beta extends Mustache { +class Beta { protected $_data = array(); public function __construct() { - $this->_data['foo'] = new StdClass(); + $this->_data['foo'] = new \StdClass(); $this->_data['foo']->name = 'Foo'; $this->_data['foo']->number = 1; } @@ -56,7 +72,7 @@ class Beta extends Mustache { } } -class Gamma extends Mustache { +class Gamma { public $bar; public function __construct() { @@ -64,10 +80,10 @@ class Gamma extends Mustache { } } -class Delta extends Mustache { +class Delta { protected $_name = 'Foo'; public function name() { return $this->_name; } -} \ No newline at end of file +} diff --git a/test/Mustache/Test/Loader/ArrayLoaderTest.php b/test/Mustache/Test/Loader/ArrayLoaderTest.php new file mode 100644 index 0000000..eccd64d --- /dev/null +++ b/test/Mustache/Test/Loader/ArrayLoaderTest.php @@ -0,0 +1,43 @@ + 'bar' + )); + + $this->assertEquals('bar', $loader->load('foo')); + } + + public function testSetAndLoadTemplates() { + $loader = new ArrayLoader(array( + 'foo' => 'bar' + )); + $this->assertEquals('bar', $loader->load('foo')); + + $loader->setTemplate('baz', 'qux'); + $this->assertEquals('qux', $loader->load('baz')); + + $loader->setTemplates(array( + 'foo' => 'FOO', + 'baz' => 'BAZ', + )); + $this->assertEquals('FOO', $loader->load('foo')); + $this->assertEquals('BAZ', $loader->load('baz')); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testMissingTemplatesThrowExceptions() { + $loader = new ArrayLoader; + $loader->load('not_a_real_template'); + } +} diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php index 2674a0f..693527a 100644 --- a/test/Mustache/Test/Loader/FilesystemLoaderTest.php +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -1,60 +1,41 @@ assertEquals(file_get_contents(dirname(__FILE__).'/fixtures/foo.mustache'), $loader['foo']); - $this->assertEquals(file_get_contents(dirname(__FILE__).'/fixtures/bar.mustache'), $loader['bar']); +class FilesystemLoaderTest extends \PHPUnit_Framework_TestCase { + public function testConstructor() { + $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $loader = new FilesystemLoader($baseDir, array('extension' => '.ms')); + $this->assertEquals('alpha contents', $loader->load('alpha')); + $this->assertEquals('beta contents', $loader->load('beta.ms')); } - public function testMustacheUsesFilesystemLoader() { - $template = '{{> foo }} {{> bar }}'; - $data = array( - 'truthy' => true, - 'foo' => 'FOO', - 'bar' => 'BAR', - ); - $output = 'FOO BAR'; - $m = new Mustache(); - $partials = new MustacheLoader(dirname(__FILE__).'/fixtures'); - $this->assertEquals($output, $m->render($template, $data, $partials)); + public function testLoadTemplates() { + $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $loader = new FilesystemLoader($baseDir); + $this->assertEquals('one contents', $loader->load('one')); + $this->assertEquals('two contents', $loader->load('two.mustache')); } - public function testMustacheUsesDifferentLoadersToo() { - $template = '{{> foo }} {{> bar }}'; - $data = array( - 'truthy' => true, - 'foo' => 'FOO', - 'bar' => 'BAR', - ); - $output = 'FOO BAR'; - $m = new Mustache(); - $partials = new DifferentMustacheLoader(); - $this->assertEquals($output, $m->render($template, $data, $partials)); + /** + * @expectedException \RuntimeException + */ + public function testMissingBaseDirThrowsException() { + $loader = new FilesystemLoader(__DIR__.'/not_a_directory'); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testMissingTemplateThrowsException() { + $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $loader = new FilesystemLoader($baseDir); + + $loader->load('fake'); } } - -class DifferentMustacheLoader implements ArrayAccess { - protected $partials = array( - 'foo' => '{{ foo }}', - 'bar' => '{{# truthy }}{{ bar }}{{/ truthy }}', - ); - - public function offsetExists($offset) { - return isset($this->partials[$offset]); - } - - public function offsetGet($offset) { - return $this->partials[$offset]; - } - - public function offsetSet($offset, $value) {} - public function offsetUnset($offset) {} -} diff --git a/test/Mustache/Test/Loader/StringLoaderTest.php b/test/Mustache/Test/Loader/StringLoaderTest.php new file mode 100644 index 0000000..ca359e1 --- /dev/null +++ b/test/Mustache/Test/Loader/StringLoaderTest.php @@ -0,0 +1,18 @@ +assertEquals('foo', $loader->load('foo')); + $this->assertEquals('{{ bar }}', $loader->load('{{ bar }}')); + $this->assertEquals("\n{{! comment }}\n", $loader->load("\n{{! comment }}\n")); + } +} diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 0c0bb13..9883058 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -1,464 +1,147 @@ array( - array('type' => 'Natural'), - array('type' => 'Hungarian'), - array('type' => 'Dali'), - array('type' => 'English'), - array('type' => 'Imperial'), - array('type' => 'Freestyle', 'last' => 'true'), - ) - ); - $output = 'Natural, Hungarian, Dali, English, Imperial, and Freestyle'; - - $m1 = new Mustache(); - $this->assertEquals($output, $m1->render($template, $data)); - - $m2 = new Mustache($template); - $this->assertEquals($output, $m2->render(null, $data)); - - $m3 = new Mustache($template, $data); - $this->assertEquals($output, $m3->render()); - - $m4 = new Mustache(null, $data); - $this->assertEquals($output, $m4->render($template)); - } - - /** - * @dataProvider constructorOptions - */ - public function testConstructorOptions($options, $charset, $delimiters, $pragmas) { - $mustache = new MustacheExposedOptionsStub(null, null, null, $options); - $this->assertEquals($charset, $mustache->getCharset()); - $this->assertEquals($delimiters, $mustache->getDelimiters()); - $this->assertEquals($pragmas, $mustache->getPragmas()); - } - - public function constructorOptions() { - return array( - array( - array(), - 'UTF-8', - array('{{', '}}'), - array(), - ), - array( - array( - 'charset' => 'UTF-8', - 'delimiters' => '<< >>', - 'pragmas' => array(Mustache::PRAGMA_UNESCAPED => true) - ), - 'UTF-8', - array('<<', '>>'), - array(Mustache::PRAGMA_UNESCAPED => true), - ), - array( - array( - 'charset' => 'cp866', - 'delimiters' => array('[[[[', ']]]]'), - 'pragmas' => array(Mustache::PRAGMA_UNESCAPED => true) - ), - 'cp866', - array('[[[[', ']]]]'), - array(Mustache::PRAGMA_UNESCAPED => true), - ), - ); - } - - /** - * @expectedException MustacheException - */ - public function testConstructorInvalidPragmaOptionsThrowExceptions() { - $mustache = new Mustache(null, null, null, array('pragmas' => array('banana phone' => true))); - } - - /** - * Test __toString() function. - * - * @access public - * @return void - */ - public function test__toString() { - $m = new Mustache('{{first_name}} {{last_name}}', array('first_name' => 'Karl', 'last_name' => 'Marx')); - - $this->assertEquals('Karl Marx', $m->__toString()); - $this->assertEquals('Karl Marx', (string) $m); - - $m2 = $this->getMock(self::TEST_CLASS, array('render'), array()); - $m2->expects($this->once()) - ->method('render') - ->will($this->returnValue('foo')); - - $this->assertEquals('foo', $m2->render()); - } - - public function test__toStringException() { - $m = $this->getMock(self::TEST_CLASS, array('render'), array()); - $m->expects($this->once()) - ->method('render') - ->will($this->throwException(new Exception)); - - try { - $out = (string) $m; - } catch (Exception $e) { - $this->fail('__toString should catch all exceptions'); + public static function setUpBeforeClass() { + self::$tempDir = sys_get_temp_dir() . '/mustache_test'; + if (file_exists(self::$tempDir)) { + self::rmdir(self::$tempDir); } } - /** - * Test render(). - * - * @access public - * @return void - */ - public function testRender() { - $m = new Mustache(); - - $this->assertEquals('', $m->render('')); - $this->assertEquals('foo', $m->render('foo')); - $this->assertEquals('', $m->render(null)); - - $m2 = new Mustache('foo'); - $this->assertEquals('foo', $m2->render()); - - $m3 = new Mustache(''); - $this->assertEquals('', $m3->render()); - - $m3 = new Mustache(); - $this->assertEquals('', $m3->render(null)); - } - - /** - * Test render() with data. - * - * @group interpolation - */ - public function testRenderWithData() { - $m = new Mustache('{{first_name}} {{last_name}}'); - $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin'))); - $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa'))); - } - - /** - * @group partials - */ - public function testRenderWithPartials() { - $m = new Mustache('{{>stache}}', null, array('stache' => '{{first_name}} {{last_name}}')); - $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin'))); - $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa'))); - } - - /** - * @group interpolation - * @dataProvider interpolationData - */ - public function testDoubleRenderMustacheTags($template, $context, $expected) { - $m = new Mustache($template, $context); - $this->assertEquals($expected, $m->render()); - } - - public function interpolationData() { - return array( - array( - '{{#a}}{{=<% %>=}}{{b}} c<%={{ }}=%>{{/a}}', - array('a' => array(array('b' => 'Do Not Render'))), - '{{b}} c' - ), - array( - '{{#a}}{{b}}{{/a}}', - array('a' => array('b' => '{{c}}'), 'c' => 'FAIL'), - '{{c}}' - ), - ); - } - - /** - * Mustache should allow newlines (and other whitespace) in comments and all other tags. - * - * @group comments - */ - public function testNewlinesInComments() { - $m = new Mustache("{{! comment \n \t still a comment... }}"); - $this->assertEquals('', $m->render()); - } - - /** - * Mustache should return the same thing when invoked multiple times. - */ - public function testMultipleInvocations() { - $m = new Mustache('x'); - $first = $m->render(); - $second = $m->render(); - - $this->assertEquals('x', $first); - $this->assertEquals($first, $second); - } - - /** - * Mustache should return the same thing when invoked multiple times. - * - * @group interpolation - */ - public function testMultipleInvocationsWithTags() { - $m = new Mustache('{{one}} {{two}}', array('one' => 'foo', 'two' => 'bar')); - $first = $m->render(); - $second = $m->render(); - - $this->assertEquals('foo bar', $first); - $this->assertEquals($first, $second); - } - - /** - * Mustache should not use templates passed to the render() method for subsequent invocations. - */ - public function testResetTemplateForMultipleInvocations() { - $m = new Mustache('Sirve.'); - $this->assertEquals('No sirve.', $m->render('No sirve.')); - $this->assertEquals('Sirve.', $m->render()); - - $m2 = new Mustache(); - $this->assertEquals('No sirve.', $m2->render('No sirve.')); - $this->assertEquals('', $m2->render()); - } - - /** - * Test the __clone() magic function. - * - * @group examples - * @dataProvider getExamples - * - * @param string $class - * @param string $template - * @param string $output - */ - public function test__clone($class, $template, $output) { - if (isset($this->knownIssues[$class])) { - return $this->markTestSkipped($this->knownIssues[$class]); - } - - $m = new $class; - $n = clone $m; - - $n_output = $n->render($template); - - $o = clone $n; - - $this->assertEquals($m->render($template), $n_output); - $this->assertEquals($n_output, $o->render($template)); - - $this->assertNotSame($m, $n); - $this->assertNotSame($n, $o); - $this->assertNotSame($m, $o); - } - - /** - * Test everything in the `examples` directory. - * - * @group examples - * @dataProvider getExamples - * - * @param string $class - * @param string $template - * @param string $output - */ - public function testExamples($class, $template, $output) { - if (isset($this->knownIssues[$class])) { - return $this->markTestSkipped($this->knownIssues[$class]); - } - - $m = new $class; - $this->assertEquals($output, $m->render($template)); - } - - /** - * Data provider for testExamples method. - * - * Assumes that an `examples` directory exists inside parent directory. - * This examples directory should contain any number of subdirectories, each of which contains - * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file - * (.txt). - * - * This whole mess will be refined later to be more intuitive and less prescriptive, but it'll - * do for now. Especially since it means we can have unit tests :) - * - * @return array - */ - public function getExamples() { - $basedir = dirname(__FILE__) . '/../examples/'; - - $ret = array(); - - $files = new RecursiveDirectoryIterator($basedir); - while ($files->valid()) { - - if ($files->hasChildren() && $children = $files->getChildren()) { - $example = $files->getSubPathname(); - $class = null; - $template = null; - $output = null; - - foreach ($children as $file) { - if (!$file->isFile()) continue; - - $filename = $file->getPathname(); - $info = pathinfo($filename); - - if (isset($info['extension'])) { - switch($info['extension']) { - case 'php': - $class = $info['filename']; - include_once($filename); - break; - - case 'mustache': - $template = file_get_contents($filename); - break; - - case 'txt': - $output = file_get_contents($filename); - break; - } - } - } - - if (!empty($class)) { - $ret[$example] = array($class, $template, $output); - } + private static function rmdir($path) { + $path = rtrim($path, '/').'/'; + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; } - $files->next(); + $fullpath = $path.$file; + if (is_dir($fullpath)) { + self::rmdir($fullpath); + } else { + unlink($fullpath); + } } - return $ret; + + closedir($handle); + rmdir($path); + } + + public function testConstructor() { + $loader = new StringLoader; + $partialsLoader = new ArrayLoader; + $mustache = new Mustache(array( + 'template_class_prefix' => '__whot__', + 'cache' => self::$tempDir, + 'loader' => $loader, + 'partials_loader' => $partialsLoader, + 'partials' => array( + 'foo' => '{{ foo }}', + ), + 'charset' => 'ISO-8859-1', + )); + + $this->assertSame($loader, $mustache->getLoader()); + $this->assertSame($partialsLoader, $mustache->getPartialsLoader()); + $this->assertEquals('{{ foo }}', $partialsLoader->load('foo')); + $this->assertContains('__whot__', $mustache->getTemplateClassName('{{ foo }}')); + $this->assertEquals('ISO-8859-1', $mustache->getCharset()); + } + + public function testSettingServices() { + $loader = new StringLoader; + $tokenizer = new Tokenizer; + $parser = new Parser; + $compiler = new Compiler; + $mustache = new Mustache; + + $this->assertNotSame($loader, $mustache->getLoader()); + $mustache->setLoader($loader); + $this->assertSame($loader, $mustache->getLoader()); + + $this->assertNotSame($loader, $mustache->getPartialsLoader()); + $mustache->setPartialsLoader($loader); + $this->assertSame($loader, $mustache->getPartialsLoader()); + + $this->assertNotSame($tokenizer, $mustache->getTokenizer()); + $mustache->setTokenizer($tokenizer); + $this->assertSame($tokenizer, $mustache->getTokenizer()); + + $this->assertNotSame($parser, $mustache->getParser()); + $mustache->setParser($parser); + $this->assertSame($parser, $mustache->getParser()); + + $this->assertNotSame($compiler, $mustache->getCompiler()); + $mustache->setCompiler($compiler); + $this->assertSame($compiler, $mustache->getCompiler()); } /** - * @group delimiters + * @group functional */ - public function testCrazyDelimiters() { - $m = new Mustache(null, array('result' => 'success')); - $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]')); - $this->assertEquals('success', $m->render('{{=(( ))=}}(( result ))')); - $this->assertEquals('success', $m->render('{{={$ $}=}}{$ result $}')); - $this->assertEquals('success', $m->render('{{=<.. ..>=}}<.. result ..>')); - $this->assertEquals('success', $m->render('{{=^^ ^^}}^^ result ^^')); - $this->assertEquals('success', $m->render('{{=// \\\\}}// result \\\\')); + public function testCache() { + $mustache = new Mustache(array( + 'template_class_prefix' => '__whot__', + 'cache' => self::$tempDir, + )); + + $source = '{{ foo }}'; + $template = $mustache->loadTemplate($source); + $className = $mustache->getTemplateClassName($source); + $fileName = self::$tempDir . '/' . $className . '.php'; + $this->assertInstanceOf($className, $template); + $this->assertFileExists($fileName); + $this->assertContains("\nclass $className extends \Mustache\Template", file_get_contents($fileName)); } /** - * @group delimiters + * @group functional + * @expectedException \RuntimeException */ - public function testResetDelimiters() { - $m = new Mustache(null, array('result' => 'success')); - $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]')); - $this->assertEquals('success', $m->render('{{=<< >>=}}<< result >>')); - $this->assertEquals('success', $m->render('{{=<% %>=}}<% result %>')); + public function testCacheFailsThrowException() { + global $mustacheFilesystemRenameHax; + + $mustacheFilesystemRenameHax = true; + + $mustache = new Mustache(array('cache' => self::$tempDir)); + $mustache->loadTemplate('{{ foo }}'); } /** - * @group delimiters + * @expectedException \RuntimeException */ - public function testStickyDelimiters() { - $m = new Mustache(null, array('result' => 'FAIL')); - $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}{{ result }}[[={{ }}=]]')); - $this->assertEquals('{{#result}}{{/result}}', $m->render('{{=[[ ]]=}}{{#result}}{{/result}}[[={{ }}=]]')); - $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}[[#result]]{{ result }}[[/result]][[={{ }}=]]')); - $this->assertEquals('{{ result }}', $m->render('{{#result}}{{=[[ ]]=}}{{ result }}[[/result]][[^result]][[={{ }}=]][[ result ]]{{/result}}')); - } + public function testImmutablePartialsLoadersThrowException() { + $mustache = new Mustache(array( + 'partials_loader' => new StringLoader, + )); - /** - * @group sections - * @dataProvider poorlyNestedSections - * @expectedException MustacheException - */ - public function testPoorlyNestedSections($template) { - $m = new Mustache($template); - $m->render(); - } - - public function poorlyNestedSections() { - return array( - array('{{#foo}}'), - array('{{#foo}}{{/bar}}'), - array('{{#foo}}{{#bar}}{{/foo}}'), - array('{{#foo}}{{#bar}}{{/foo}}{{/bar}}'), - array('{{#foo}}{{/bar}}{{/foo}}'), - ); - } - - /** - * Ensure that Mustache doesn't double-render sections (allowing mustache injection). - * - * @group sections - */ - public function testMustacheInjection() { - $template = '{{#foo}}{{bar}}{{/foo}}'; - $view = array( - 'foo' => true, - 'bar' => '{{win}}', - 'win' => 'FAIL', - ); - - $m = new Mustache($template, $view); - $this->assertEquals('{{win}}', $m->render()); + $mustache->setPartials(array('foo' => '{{ foo }}')); } } -class MustacheExposedOptionsStub extends Mustache { - public function getPragmas() { - return $this->_pragmas; - } - public function getCharset() { - return $this->_charset; - } - public function getDelimiters() { - return array($this->_otag, $this->_ctag); - } + +// It's prob'ly best if you ignore this bit. + +namespace Mustache; + +function rename($a, $b) { + global $mustacheFilesystemRenameHax; + + return ($mustacheFilesystemRenameHax) ? false : \rename($a, $b); } diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php new file mode 100644 index 0000000..d234182 --- /dev/null +++ b/test/Mustache/Test/ParserTest.php @@ -0,0 +1,157 @@ +assertEquals($expected, $parser->parse($tokens)); + } + + public function getTokenSets() + { + return array( + array( + array(), + array() + ), + + array( + array('text'), + array('text') + ), + + array( + array(array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name' + )), + array(array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name' + )), + ), + + array( + array( + 'foo', + array( + Tokenizer::TAG => '^', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name' + ), + array( + Tokenizer::TAG => '/', + Tokenizer::INDEX => 456, + Tokenizer::NAME => 'parent' + ), + 'bar', + ), + array( + 'foo', + array( + Tokenizer::TAG => '^', + Tokenizer::NAME => 'parent', + Tokenizer::INDEX => 123, + Tokenizer::END => 456, + Tokenizer::NODES => array( + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name' + ), + ), + ), + 'bar', + ), + ), + + ); + } + + /** + * @dataProvider getBadParseTrees + * @expectedException \LogicException + */ + public function testParserThrowsExceptions($tokens) { + $parser = new Parser; + $parser->parse($tokens); + } + + public function getBadParseTrees() { + return array( + // no close + array( + array( + array( + Tokenizer::TAG => '#', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + ), + ), + + // no close inverted + array( + array( + array( + Tokenizer::TAG => '^', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + ), + ), + + // no opening inverted + array( + array( + array( + Tokenizer::TAG => '/', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + ), + ), + + // weird nesting + array( + array( + array( + Tokenizer::TAG => '#', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + array( + Tokenizer::TAG => '#', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'child' + ), + array( + Tokenizer::TAG => '/', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'parent' + ), + array( + Tokenizer::TAG => '/', + Tokenizer::INDEX => 123, + Tokenizer::NAME => 'child' + ), + ), + ), + ); + } +} diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php new file mode 100644 index 0000000..b67a25f --- /dev/null +++ b/test/Mustache/Test/TemplateTest.php @@ -0,0 +1,43 @@ +assertSame($mustache, $template->getMustache()); + } + + public function testRendering() { + $rendered = '<< wheee >>'; + $mustache = new Mustache; + $template = new TemplateStub($mustache); + $template->rendered = $rendered; + $context = new Context; + + $this->assertEquals($rendered, $template()); + $this->assertEquals($rendered, $template->render()); + $this->assertEquals($rendered, $template->renderInternal($context)); + $this->assertEquals($rendered, $template->render(array('foo' => 'bar'))); + } +} + +class TemplateStub extends Template { + public $rendered; + + public function getMustache() { + return $this->mustache; + } + + public function renderInternal(Context $context) { + return $this->rendered; + } +} diff --git a/test/Mustache/Test/TokenizerTest.php b/test/Mustache/Test/TokenizerTest.php new file mode 100644 index 0000000..53f7b4f --- /dev/null +++ b/test/Mustache/Test/TokenizerTest.php @@ -0,0 +1,117 @@ +assertSame($expected, $tokenizer->scan($text, $delimiters)); + } + + public function getTokens() { + return array( + array( + 'text', + null, + array('text'), + ), + + array( + 'text', + '<<< >>>', + array('text'), + ), + + array( + '{{ name }}', + null, + array( + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name', + Tokenizer::OTAG => '{{', + Tokenizer::CTAG => '}}', + Tokenizer::INDEX => 10, + ) + ) + ), + + array( + '{{ name }}', + '<<< >>>', + array('{{ name }}'), + ), + + array( + '<<< name >>>', + '<<< >>>', + array( + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'name', + Tokenizer::OTAG => '<<<', + Tokenizer::CTAG => '>>>', + Tokenizer::INDEX => 12, + ) + ) + ), + + array( + "{{{ a }}}\n{{# b }} \n{{= | | =}}| c ||/ b |\n|{ d }|", + null, + array( + array( + Tokenizer::TAG => '{', + Tokenizer::NAME => 'a', + Tokenizer::OTAG => '{{', + Tokenizer::CTAG => '}}', + Tokenizer::INDEX => 8, + ), + "\n", + array( + Tokenizer::TAG => '#', + Tokenizer::NAME => 'b', + Tokenizer::OTAG => '{{', + Tokenizer::CTAG => '}}', + Tokenizer::INDEX => 18, + ), + null, + array( + Tokenizer::TAG => '_v', + Tokenizer::NAME => 'c', + Tokenizer::OTAG => '|', + Tokenizer::CTAG => '|', + Tokenizer::INDEX => 37, + ), + array( + Tokenizer::TAG => '/', + Tokenizer::NAME => 'b', + Tokenizer::OTAG => '|', + Tokenizer::CTAG => '|', + Tokenizer::INDEX => 37, + ), + "\n", + array( + Tokenizer::TAG => '{', + Tokenizer::NAME => 'd', + Tokenizer::OTAG => '|', + Tokenizer::CTAG => '|', + Tokenizer::INDEX => 51, + ), + + ) + ), + + + ); + } +} From 5c4fcd0c9a0ef69d98772d20b7832b614f394365 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 29 Feb 2012 19:32:43 -0800 Subject: [PATCH 06/58] Coding standard cleanup. --- src/Mustache/Buffer.php | 6 +-- src/Mustache/Compiler.php | 2 +- src/Mustache/Context.php | 2 +- src/Mustache/Loader.php | 2 +- src/Mustache/Loader/ArrayLoader.php | 2 +- src/Mustache/Loader/FilesystemLoader.php | 2 +- src/Mustache/Loader/StringLoader.php | 2 +- src/Mustache/Mustache.php | 6 +-- src/Mustache/Parser.php | 4 +- src/Mustache/Tokenizer.php | 2 +- test/Mustache/Test/ContextTest.php | 11 +++++- .../Mustache/Test/Functional/ExamplesTest.php | 3 +- .../Functional/HigherOrderSectionsTest.php | 9 ++--- .../Test/Functional/MustacheInjectionTest.php | 8 +++- .../Test/Functional/MustacheSpecTest.php | 5 ++- test/Mustache/Test/MustacheTest.php | 39 +++++++++---------- test/bootstrap.php | 2 +- 17 files changed, 59 insertions(+), 48 deletions(-) diff --git a/src/Mustache/Buffer.php b/src/Mustache/Buffer.php index f2fac5d..45421bf 100644 --- a/src/Mustache/Buffer.php +++ b/src/Mustache/Buffer.php @@ -71,7 +71,7 @@ class Buffer { * @see \Mustache\Buffer::write * * @param string $text - * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) + * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) */ public function writeText($text, $escape = false) { $this->write($text, true, $escape); @@ -81,8 +81,8 @@ class Buffer { * Add output to the Buffer. * * @param string $text - * @param bool $indent Indent this line? (default: false) - * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) + * @param bool $indent Indent this line? (default: false) + * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) */ public function write($text, $indent = false, $escape = false) { $text = (string) $text; diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 3ca3f48..fb6213a 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -253,7 +253,7 @@ class Compiler { * Prepare PHP source code snippet for output. * * @param string $text - * @param int $bonus Additional indent level (default: 0) + * @param int $bonus Additional indent level (default: 0) * @param boolean $prependNewline Prepend a newline to the snippet? (default: true) * * @return string PHP source code snippet diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index 63ee1e8..05c9b1f 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -180,7 +180,7 @@ class Context { * * @see \Mustache\Context::find * - * @param string $id Variable name + * @param string $id Variable name * @param array $stack Context stack * * @return mixed Variable value, or '' if not found diff --git a/src/Mustache/Loader.php b/src/Mustache/Loader.php index 57991b6..06a60b1 100644 --- a/src/Mustache/Loader.php +++ b/src/Mustache/Loader.php @@ -10,7 +10,7 @@ interface Loader { /** * Load a Template by name. * - * @param string $name + * @param string $name * * @return string Mustache Template source */ diff --git a/src/Mustache/Loader/ArrayLoader.php b/src/Mustache/Loader/ArrayLoader.php index 5a62e15..0386fea 100644 --- a/src/Mustache/Loader/ArrayLoader.php +++ b/src/Mustache/Loader/ArrayLoader.php @@ -37,7 +37,7 @@ class ArrayLoader implements Loader, MutableLoader { /** * Load a Template. * - * @param string $name + * @param string $name * * @return string Mustache Template source */ diff --git a/src/Mustache/Loader/FilesystemLoader.php b/src/Mustache/Loader/FilesystemLoader.php index e510fc9..1aff730 100644 --- a/src/Mustache/Loader/FilesystemLoader.php +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -59,7 +59,7 @@ class FilesystemLoader implements Loader { * $loader = new FilesystemLoader(__DIR__.'/views'); * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; * - * @param string $name + * @param string $name * * @return string Mustache Template source */ diff --git a/src/Mustache/Loader/StringLoader.php b/src/Mustache/Loader/StringLoader.php index d27bad0..6cd85e1 100644 --- a/src/Mustache/Loader/StringLoader.php +++ b/src/Mustache/Loader/StringLoader.php @@ -25,7 +25,7 @@ class StringLoader implements Loader { /** * Load a Template by source. * - * @param string $name Mustache Template source + * @param string $name Mustache Template source * * @return string Mustache Template source */ diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 98df8b0..57fd2e9 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -19,7 +19,7 @@ use Mustache\Loader\StringLoader; * @author Justin Hileman {@link http://justinhileman.com} */ class Mustache { - const VERSION = '2.0.0-a1'; + const VERSION = '2.0.0-dev'; const SPEC_VERSION = '1.1.2'; // Template cache @@ -188,7 +188,7 @@ class Mustache { /** * Set the Mustache Parser instance. * - * @param \Mustache\Parser $tokenizer + * @param \Mustache\Parser $parser */ public function setParser(Parser $parser) { $this->parser = $parser; @@ -212,7 +212,7 @@ class Mustache { /** * Set the Mustache Compiler instance. * - * @param \Mustache\Compiler $tokenizer + * @param \Mustache\Compiler $compiler */ public function setCompiler(Compiler $compiler) { $this->compiler = $compiler; diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index d330913..4b2856f 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -12,7 +12,7 @@ class Parser { /** * Process an array of Mustache tokens and convert them into a parse tree. * - * @param array $tree Set of Mustache tokens + * @param array $tokens Set of Mustache tokens * * @return array Mustache token parse tree */ @@ -69,7 +69,7 @@ class Parser { $nodes[] = $token; } - } while($tokens->valid()); + } while ($tokens->valid()); if (isset($parent)) { throw new \LogicException('Missing closing tag: ' . $parent[Tokenizer::NAME]); diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index 1074397..b9a84ce 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -53,7 +53,7 @@ class Tokenizer { private $state; private $tagType; private $tag; - private $buf; + private $buffer; private $tokens; private $seenTag; private $lineStart; diff --git a/test/Mustache/Test/ContextTest.php b/test/Mustache/Test/ContextTest.php index 678e976..ea6d1dc 100644 --- a/test/Mustache/Test/ContextTest.php +++ b/test/Mustache/Test/ContextTest.php @@ -45,7 +45,9 @@ class ContextTest extends \PHPUnit_Framework_TestCase { $dummy = new TestDummy; $context = new Context; - $this->assertTrue($context->isCallable(function() { return null; })); + $this->assertTrue($context->isCallable(function() { + return null; + })); $this->assertTrue($context->isCallable(array('\Mustache\Test\TestDummy', 'foo'))); $this->assertTrue($context->isCallable(array($dummy, 'bar'))); $this->assertTrue($context->isCallable($dummy)); @@ -140,10 +142,15 @@ class ContextTest extends \PHPUnit_Framework_TestCase { class TestDummy { public $name = 'dummy'; - public function __invoke() {} + + public function __invoke() { + // nothing + } + public static function foo() { return ''; } + public function bar() { return ''; } diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 6aff929..1a25dbc 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -64,6 +64,7 @@ class ExamplesTest extends \PHPUnit_Framework_TestCase { * Helper method to load an example given the full path. * * @param string $path + * * @return array arguments for testExamples */ private function loadExample($path) { @@ -106,7 +107,7 @@ class ExamplesTest extends \PHPUnit_Framework_TestCase { /** * Helper method to load partials given an example directory. * - * @param string $path + * @param string $path * * @return array $partials */ diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 680efd7..b7b4790 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -40,10 +40,10 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { } public function testRuntimeSectionCallback() { - $tpl = $this->mustache->loadTemplate('{{#double_wrap}}{{name}}{{/double_wrap}}'); + $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); $foo = new Foo; - $foo->double_wrap = array($foo, 'wrapWithBoth'); + $foo->doublewrap = array($foo, 'wrapWithBoth'); $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); } @@ -80,10 +80,7 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { } ); - $this->assertEquals( - sprintf('[[%s]]', $data['name']), - $tpl->render($data) - ); + $this->assertEquals(sprintf('[[%s]]', $data['name']), $tpl->render($data)); } public function testMonsters() { diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index eec0e1c..056f660 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -105,7 +105,9 @@ class MustacheInjectionTest extends \PHPUnit_Framework_TestCase { $tpl = $this->mustache->loadTemplate('{{ a }}'); $data = array( - 'a' => function() { return '{{ b }}'; }, + 'a' => function() { + return '{{ b }}'; + }, 'b' => '{{ c }}', 'c' => 'FAIL' ); @@ -117,7 +119,9 @@ class MustacheInjectionTest extends \PHPUnit_Framework_TestCase { $tpl = $this->mustache->loadTemplate('{{# a }}b{{/ a }}'); $data = array( - 'a' => function ($text) { return '{{ ' . $text . ' }}'; }, + 'a' => function ($text) { + return '{{ ' . $text . ' }}'; + }, 'b' => '{{ c }}', 'c' => 'FAIL' ); diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 831a029..a9ece89 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -106,11 +106,14 @@ class MustacheSpecTest extends \PHPUnit_Framework_TestCase { } $func = $val['php']; - $data[$key] = function($text = null) use ($func) { return eval($func); }; + $data[$key] = function($text = null) use ($func) { + return eval($func); + }; } else if (is_array($val)) { $data[$key] = $this->prepareLambdasSpec($val); } } + return $data; } diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 9883058..f343077 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -23,26 +23,6 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { } } - private static function rmdir($path) { - $path = rtrim($path, '/').'/'; - $handle = opendir($path); - while (($file = readdir($handle)) !== false) { - if ($file == '.' || $file == '..') { - continue; - } - - $fullpath = $path.$file; - if (is_dir($fullpath)) { - self::rmdir($fullpath); - } else { - unlink($fullpath); - } - } - - closedir($handle); - rmdir($path); - } - public function testConstructor() { $loader = new StringLoader; $partialsLoader = new ArrayLoader; @@ -133,6 +113,25 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $mustache->setPartials(array('foo' => '{{ foo }}')); } + private static function rmdir($path) { + $path = rtrim($path, '/').'/'; + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } + + $fullpath = $path.$file; + if (is_dir($fullpath)) { + self::rmdir($fullpath); + } else { + unlink($fullpath); + } + } + + closedir($handle); + rmdir($path); + } } diff --git a/test/bootstrap.php b/test/bootstrap.php index f022da1..ced28b8 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -6,8 +6,8 @@ require __DIR__.'/../src/Mustache/Context.php'; require __DIR__.'/../src/Mustache/Loader.php'; require __DIR__.'/../src/Mustache/Loader/MutableLoader.php'; require __DIR__.'/../src/Mustache/Loader/ArrayLoader.php'; -require __DIR__.'/../src/Mustache/Loader/StringLoader.php'; require __DIR__.'/../src/Mustache/Loader/FilesystemLoader.php'; +require __DIR__.'/../src/Mustache/Loader/StringLoader.php'; require __DIR__.'/../src/Mustache/Mustache.php'; require __DIR__.'/../src/Mustache/Parser.php'; require __DIR__.'/../src/Mustache/Template.php'; From 96596f473ad02f617e68352dde48933143856dea Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 1 Mar 2012 05:38:53 -0800 Subject: [PATCH 07/58] Update README for 2.0-dev --- README.markdown | 51 ++++++++----------------------------------------- 1 file changed, 8 insertions(+), 43 deletions(-) diff --git a/README.markdown b/README.markdown index 989ff97..e586913 100644 --- a/README.markdown +++ b/README.markdown @@ -11,14 +11,13 @@ A quick example: ```php render('Hello {{planet}}', array('planet' => 'World!')); -// "Hello World!" +$tpl = $m->loadTemplate('Hello {{planet}}'); +echo $tpl->render(array('planet' => 'World!')); // "Hello World!" ``` -And a more in-depth example--this is the canonical Mustache template: +And a more in-depth example -- this is the canonical Mustache template: ``` Hello {{name}} @@ -29,40 +28,12 @@ Well, ${{taxed_value}}, after taxes. ``` -Along with the associated Mustache class: - -```php -value - ($this->value * 0.4); - } - - public $in_ca = true; -} -``` - - -Render it like so: - -```php -render($template); -``` - - -Here's the same thing, a different way: - -Create a view object--which could also be an associative array, but those don't do functions quite as well: +Create a view "context" object -- which could also be an associative array, but those don't do functions quite as well: ```php render($template, $chris); +$tpl = $m->loadTemplate($template); +$chris = new Chris; +echo $template->render($chris); ``` -Known Issues ------------- - - * As of Mustache spec v1.1.2, there are a couple of whitespace bugs around section tags... Despite these failing tests, this - version is actually *closer* to correct than previous releases. - - See Also -------- From 1f97e2cb5eb7ca1c29c78c5862833354d70eea2e Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 1 Mar 2012 06:27:53 -0800 Subject: [PATCH 08/58] Update `create_example` script for 2.0-dev --- bin/create_example.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/create_example.php b/bin/create_example.php index 1f0b894..0838b38 100755 --- a/bin/create_example.php +++ b/bin/create_example.php @@ -152,7 +152,7 @@ function main($example_name) { createFile($lowercase, $uppercase, "php", << Date: Thu, 1 Mar 2012 06:48:25 -0800 Subject: [PATCH 09/58] Add a Mustache Autoloader implementation. --- src/Mustache/Autoloader.php | 54 +++++++++++++++++++ test/Mustache/Test/AutoloaderTest.php | 28 ++++++++++ test/bootstrap.php | 14 +---- test/fixtures/autoloader/Mustache/Bar.php | 7 +++ test/fixtures/autoloader/Mustache/Foo.php | 7 +++ test/fixtures/autoloader/NonMustacheClass.php | 5 ++ 6 files changed, 103 insertions(+), 12 deletions(-) create mode 100644 src/Mustache/Autoloader.php create mode 100644 test/Mustache/Test/AutoloaderTest.php create mode 100644 test/fixtures/autoloader/Mustache/Bar.php create mode 100644 test/fixtures/autoloader/Mustache/Foo.php create mode 100644 test/fixtures/autoloader/NonMustacheClass.php diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php new file mode 100644 index 0000000..d50af91 --- /dev/null +++ b/src/Mustache/Autoloader.php @@ -0,0 +1,54 @@ +baseDir = rtrim($baseDir, '/') ?: __DIR__.'/..'; + } + + /** + * Register a new instance as an SPL autoloader. + * + * @param string $baseDir Mustache library base directory (default: __DIR__.'/..') + * + * @return \Mustache\Autoloader Registered Autoloader instance + */ + static public function register($baseDir = null) { + $loader = new self($baseDir); + spl_autoload_register(array($loader, 'autoload')); + + return $loader; + } + + /** + * Autoload Mustache classes. + * + * @param string $class + */ + public function autoload($class) { + if ($class[0] === '\\') { + $class = substr($class, 1); + } + + if (strpos($class, 'Mustache') !== 0) { + return; + } + + $file = sprintf('%s/%s.php', $this->baseDir, str_replace('\\', '/', $class)); + if (is_file($file)) { + require $file; + } + } +} diff --git a/test/Mustache/Test/AutoloaderTest.php b/test/Mustache/Test/AutoloaderTest.php new file mode 100644 index 0000000..81e727c --- /dev/null +++ b/test/Mustache/Test/AutoloaderTest.php @@ -0,0 +1,28 @@ +assertTrue(spl_autoload_unregister(array($loader, 'autoload'))); + } + + public function testAutoloader() { + $loader = new Autoloader(__DIR__.'/../../fixtures/autoloader'); + + $this->assertNull($loader->autoload('NonMustacheClass')); + $this->assertFalse(class_exists('NonMustacheClass')); + + $loader->autoload('Mustache\Foo'); + $this->assertTrue(class_exists('Mustache\Foo')); + + $loader->autoload('\Mustache\Bar'); + $this->assertTrue(class_exists('Mustache\Bar')); + } +} diff --git a/test/bootstrap.php b/test/bootstrap.php index ced28b8..3335550 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -1,16 +1,6 @@ Date: Thu, 1 Mar 2012 07:17:13 -0800 Subject: [PATCH 10/58] Add file header docblocks. --- src/Mustache/Autoloader.php | 9 +++++++++ src/Mustache/Buffer.php | 9 +++++++++ src/Mustache/Compiler.php | 9 +++++++++ src/Mustache/Context.php | 9 +++++++++ src/Mustache/Loader.php | 9 +++++++++ src/Mustache/Loader/ArrayLoader.php | 9 +++++++++ src/Mustache/Loader/FilesystemLoader.php | 9 +++++++++ src/Mustache/Loader/MutableLoader.php | 9 +++++++++ src/Mustache/Loader/StringLoader.php | 9 +++++++++ src/Mustache/Mustache.php | 9 +++++++++ src/Mustache/Parser.php | 9 +++++++++ src/Mustache/Template.php | 9 +++++++++ src/Mustache/Tokenizer.php | 9 +++++++++ test/Mustache/Test/AutoloaderTest.php | 9 +++++++++ test/Mustache/Test/BufferTest.php | 9 +++++++++ test/Mustache/Test/CompilerTest.php | 9 +++++++++ test/Mustache/Test/ContextTest.php | 9 +++++++++ test/Mustache/Test/Functional/CallTest.php | 9 +++++++++ test/Mustache/Test/Functional/ExamplesTest.php | 9 +++++++++ .../Mustache/Test/Functional/HigherOrderSectionsTest.php | 9 +++++++++ test/Mustache/Test/Functional/MustacheInjectionTest.php | 9 +++++++++ test/Mustache/Test/Functional/MustacheSpecTest.php | 9 +++++++++ test/Mustache/Test/Functional/ObjectSectionTest.php | 9 +++++++++ test/Mustache/Test/Loader/ArrayLoaderTest.php | 9 +++++++++ test/Mustache/Test/Loader/FilesystemLoaderTest.php | 9 +++++++++ test/Mustache/Test/Loader/StringLoaderTest.php | 9 +++++++++ test/Mustache/Test/MustacheTest.php | 9 +++++++++ test/Mustache/Test/ParserTest.php | 9 +++++++++ test/Mustache/Test/TemplateTest.php | 9 +++++++++ test/Mustache/Test/TokenizerTest.php | 9 +++++++++ test/bootstrap.php | 9 +++++++++ test/fixtures/autoloader/Mustache/Bar.php | 9 +++++++++ test/fixtures/autoloader/Mustache/Foo.php | 9 +++++++++ test/fixtures/autoloader/NonMustacheClass.php | 9 +++++++++ 34 files changed, 306 insertions(+) diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index d50af91..26ba662 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -1,5 +1,14 @@ Date: Thu, 1 Mar 2012 07:27:11 -0800 Subject: [PATCH 11/58] Clean up vendor libraries. --- .gitmodules | 9 +- .../Test/Functional/MustacheSpecTest.php | 4 +- test/bootstrap.php | 2 +- test/lib/yaml/LICENSE | 19 - test/lib/yaml/README.markdown | 15 - test/lib/yaml/doc/00-Introduction.markdown | 143 ---- test/lib/yaml/doc/01-Usage.markdown | 110 ---- test/lib/yaml/doc/02-YAML.markdown | 312 --------- test/lib/yaml/doc/A-License.markdown | 108 --- test/lib/yaml/lib/sfYaml.php | 135 ---- test/lib/yaml/lib/sfYamlDumper.php | 60 -- test/lib/yaml/lib/sfYamlInline.php | 442 ------------- test/lib/yaml/lib/sfYamlParser.php | 622 ------------------ test/lib/yaml/package.xml | 102 --- {test => vendor}/spec | 0 vendor/yaml | 1 + 16 files changed, 10 insertions(+), 2074 deletions(-) delete mode 100644 test/lib/yaml/LICENSE delete mode 100644 test/lib/yaml/README.markdown delete mode 100644 test/lib/yaml/doc/00-Introduction.markdown delete mode 100644 test/lib/yaml/doc/01-Usage.markdown delete mode 100644 test/lib/yaml/doc/02-YAML.markdown delete mode 100644 test/lib/yaml/doc/A-License.markdown delete mode 100644 test/lib/yaml/lib/sfYaml.php delete mode 100644 test/lib/yaml/lib/sfYamlDumper.php delete mode 100644 test/lib/yaml/lib/sfYamlInline.php delete mode 100644 test/lib/yaml/lib/sfYamlParser.php delete mode 100644 test/lib/yaml/package.xml rename {test => vendor}/spec (100%) create mode 160000 vendor/yaml diff --git a/.gitmodules b/.gitmodules index 81ca331..042ea4d 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ -[submodule "test/spec"] - path = test/spec - url = http://github.com/mustache/spec.git +[submodule "vendor/spec"] + path = vendor/spec + url = https://github.com/mustache/spec.git +[submodule "vendor/yaml"] + path = vendor/yaml + url = https://github.com/fabpot/yaml.git diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 7b42fe9..8fe91a9 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -33,7 +33,7 @@ class MustacheSpecTest extends \PHPUnit_Framework_TestCase { * simply to provide a 'skipped' test if the `spec` submodule isn't initialized. */ public function testSpecInitialized() { - if (!file_exists(__DIR__.'/../../../spec/specs/')) { + if (!file_exists(__DIR__.'/../../../../vendor/spec/specs/')) { $this->markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); } } @@ -161,7 +161,7 @@ class MustacheSpecTest extends \PHPUnit_Framework_TestCase { * @return array */ private function loadSpec($name) { - $filename = __DIR__ . '/../../../spec/specs/' . $name . '.yml'; + $filename = __DIR__ . '/../../../../vendor/spec/specs/' . $name . '.yml'; if (!file_exists($filename)) { return array(); } diff --git a/test/bootstrap.php b/test/bootstrap.php index ef92007..e7c9838 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -12,4 +12,4 @@ require __DIR__.'/../src/Mustache/Autoloader.php'; \Mustache\Autoloader::register(); -require __DIR__.'/lib/yaml/lib/sfYamlParser.php'; +require __DIR__.'/../vendor/yaml/lib/sfYamlParser.php'; diff --git a/test/lib/yaml/LICENSE b/test/lib/yaml/LICENSE deleted file mode 100644 index 3cef853..0000000 --- a/test/lib/yaml/LICENSE +++ /dev/null @@ -1,19 +0,0 @@ -Copyright (c) 2008-2009 Fabien Potencier - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished -to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. diff --git a/test/lib/yaml/README.markdown b/test/lib/yaml/README.markdown deleted file mode 100644 index e4f80cf..0000000 --- a/test/lib/yaml/README.markdown +++ /dev/null @@ -1,15 +0,0 @@ -Symfony YAML: A PHP library that speaks YAML -============================================ - -Symfony YAML is a PHP library that parses YAML strings and converts them to -PHP arrays. It can also converts PHP arrays to YAML strings. Its official -website is at http://components.symfony-project.org/yaml/. - -The documentation is to be found in the `doc/` directory. - -Symfony YAML is licensed under the MIT license (see LICENSE file). - -The Symfony YAML library is developed and maintained by the -[symfony](http://www.symfony-project.org/) project team. It has been extracted -from symfony to be used as a standalone library. Symfony YAML is part of the -[symfony components project](http://components.symfony-project.org/). diff --git a/test/lib/yaml/doc/00-Introduction.markdown b/test/lib/yaml/doc/00-Introduction.markdown deleted file mode 100644 index e592758..0000000 --- a/test/lib/yaml/doc/00-Introduction.markdown +++ /dev/null @@ -1,143 +0,0 @@ -Introduction -============ - -This book is about *Symfony YAML*, a PHP library part of the Symfony -Components project. Its official website is at -http://components.symfony-project.org/yaml/. - ->**SIDEBAR** ->About the Symfony Components -> ->[Symfony Components](http://components.symfony-project.org/) are ->standalone PHP classes that can be easily used in any ->PHP project. Most of the time, they have been developed as part of the ->[Symfony framework](http://www.symfony-project.org/), and decoupled from the ->main framework later on. You don't need to use the Symfony MVC framework to use ->the components. - -What is it? ------------ - -Symfony YAML is a PHP library that parses YAML strings and converts them to -PHP arrays. It can also converts PHP arrays to YAML strings. - -[YAML](http://www.yaml.org/), YAML Ain't Markup Language, is a human friendly -data serialization standard for all programming languages. YAML is a great -format for your configuration files. YAML files are as expressive as XML files -and as readable as INI files. - -### Easy to use - -There is only one archive to download, and you are ready to go. No -configuration, No installation. Drop the files in a directory and start using -it today in your projects. - -### Open-Source - -Released under the MIT license, you are free to do whatever you want, even in -a commercial environment. You are also encouraged to contribute. - - -### Used by popular Projects - -Symfony YAML was initially released as part of the symfony framework, one of -the most popular PHP web framework. It is also embedded in other popular -projects like PHPUnit or Doctrine. - -### Documented - -Symfony YAML is fully documented, with a dedicated online book, and of course -a full API documentation. - -### Fast - -One of the goal of Symfony YAML is to find the right balance between speed and -features. It supports just the needed feature to handle configuration files. - -### Unit tested - -The library is fully unit-tested. With more than 400 unit tests, the library -is stable and is already used in large projects. - -### Real Parser - -It sports a real parser and is able to parse a large subset of the YAML -specification, for all your configuration needs. It also means that the parser -is pretty robust, easy to understand, and simple enough to extend. - -### Clear error messages - -Whenever you have a syntax problem with your YAML files, the library outputs a -helpful message with the filename and the line number where the problem -occurred. It eases the debugging a lot. - -### Dump support - -It is also able to dump PHP arrays to YAML with object support, and inline -level configuration for pretty outputs. - -### Types Support - -It supports most of the YAML built-in types like dates, integers, octals, -booleans, and much more... - - -### Full merge key support - -Full support for references, aliases, and full merge key. Don't repeat -yourself by referencing common configuration bits. - -### PHP Embedding - -YAML files are dynamic. By embedding PHP code inside a YAML file, you have -even more power for your configuration files. - -Installation ------------- - -Symfony YAML can be installed by downloading the source code as a -[tar](http://github.com/fabpot/yaml/tarball/master) archive or a -[zip](http://github.com/fabpot/yaml/zipball/master) one. - -To stay up-to-date, you can also use the official Subversion -[repository](http://svn.symfony-project.com/components/yaml/). - -If you are a Git user, there is an official -[mirror](http://github.com/fabpot/yaml), which is updated every 10 minutes. - -If you prefer to install the component globally on your machine, you can use -the symfony [PEAR](http://pear.symfony-project.com/) channel server. - -Support -------- - -Support questions and enhancements can be discussed on the -[mailing-list](http://groups.google.com/group/symfony-components). - -If you find a bug, you can create a ticket at the symfony -[trac](http://trac.symfony-project.org/newticket) under the *YAML* component. - -License -------- - -The Symfony YAML component is licensed under the *MIT license*: - ->Copyright (c) 2008-2009 Fabien Potencier -> ->Permission is hereby granted, free of charge, to any person obtaining a copy ->of this software and associated documentation files (the "Software"), to deal ->in the Software without restriction, including without limitation the rights ->to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ->copies of the Software, and to permit persons to whom the Software is furnished ->to do so, subject to the following conditions: -> ->The above copyright notice and this permission notice shall be included in all ->copies or substantial portions of the Software. -> ->THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ->IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ->FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ->AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ->LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ->OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ->THE SOFTWARE. diff --git a/test/lib/yaml/doc/01-Usage.markdown b/test/lib/yaml/doc/01-Usage.markdown deleted file mode 100644 index 644cf11..0000000 --- a/test/lib/yaml/doc/01-Usage.markdown +++ /dev/null @@ -1,110 +0,0 @@ -Using Symfony YAML -================== - -The Symfony YAML library is very simple and consists of two main classes: one -to parse YAML strings (`sfYamlParser`), and the other to dump a PHP array to -a YAML string (`sfYamlDumper`). - -On top of these two core classes, the main `sfYaml` class acts as a thin -wrapper and simplifies common uses. - -Reading YAML Files ------------------- - -The `sfYamlParser::parse()` method parses a YAML string and converts it to a -PHP array: - - [php] - $yaml = new sfYamlParser(); - $value = $yaml->parse(file_get_contents('/path/to/file.yaml')); - -If an error occurs during parsing, the parser throws an exception indicating -the error type and the line in the original YAML string where the error -occurred: - - [php] - try - { - $value = $yaml->parse(file_get_contents('/path/to/file.yaml')); - } - catch (InvalidArgumentException $e) - { - // an error occurred during parsing - echo "Unable to parse the YAML string: ".$e->getMessage(); - } - ->**TIP** ->As the parser is reentrant, you can use the same parser object to load ->different YAML strings. - -When loading a YAML file, it is sometimes better to use the `sfYaml::load()` -wrapper method: - - [php] - $loader = sfYaml::load('/path/to/file.yml'); - -The `sfYaml::load()` static method takes a YAML string or a file containing -YAML. Internally, it calls the `sfYamlParser::parse()` method, but with some -added bonuses: - - * It executes the YAML file as if it was a PHP file, so that you can embed - PHP commands in YAML files; - - * When a file cannot be parsed, it automatically adds the file name to the - error message, simplifying debugging when your application is loading - several YAML files. - -Writing YAML Files ------------------- - -The `sfYamlDumper` dumps any PHP array to its YAML representation: - - [php] - $array = array('foo' => 'bar', 'bar' => array('foo' => 'bar', 'bar' => 'baz')); - - $dumper = new sfYamlDumper(); - $yaml = $dumper->dump($array); - file_put_contents('/path/to/file.yaml', $yaml); - ->**NOTE** ->Of course, the Symfony YAML dumper is not able to dump resources. Also, ->even if the dumper is able to dump PHP objects, it is to be considered ->an alpha feature. - -If you only need to dump one array, you can use the `sfYaml::dump()` static -method shortcut: - - [php] - $yaml = sfYaml::dump($array, $inline); - -The YAML format supports two kind of representation for arrays, the expanded -one, and the inline one. By default, the dumper uses the inline -representation: - - [yml] - { foo: bar, bar: { foo: bar, bar: baz } } - -The second argument of the `dump()` method customizes the level at which the -output switches from the expanded representation to the inline one: - - [php] - echo $dumper->dump($array, 1); - -- - - [yml] - foo: bar - bar: { foo: bar, bar: baz } - -- - - [php] - echo $dumper->dump($array, 2); - -- - - [yml] - foo: bar - bar: - foo: bar - bar: baz diff --git a/test/lib/yaml/doc/02-YAML.markdown b/test/lib/yaml/doc/02-YAML.markdown deleted file mode 100644 index a64c19e..0000000 --- a/test/lib/yaml/doc/02-YAML.markdown +++ /dev/null @@ -1,312 +0,0 @@ -The YAML Format -=============== - -According to the official [YAML](http://yaml.org/) website, YAML is "a human -friendly data serialization standard for all programming languages". - -Even if the YAML format can describe complex nested data structure, this -chapter only describes the minimum set of features needed to use YAML as a -configuration file format. - -YAML is a simple language that describes data. As PHP, it has a syntax for -simple types like strings, booleans, floats, or integers. But unlike PHP, it -makes a difference between arrays (sequences) and hashes (mappings). - -Scalars -------- - -The syntax for scalars is similar to the PHP syntax. - -### Strings - - [yml] - A string in YAML - -- - - [yml] - 'A singled-quoted string in YAML' - ->**TIP** ->In a single quoted string, a single quote `'` must be doubled: -> -> [yml] -> 'A single quote '' in a single-quoted string' - - [yml] - "A double-quoted string in YAML\n" - -Quoted styles are useful when a string starts or ends with one or more -relevant spaces. - ->**TIP** ->The double-quoted style provides a way to express arbitrary strings, by ->using `\` escape sequences. It is very useful when you need to embed a ->`\n` or a unicode character in a string. - -When a string contains line breaks, you can use the literal style, indicated -by the pipe (`|`), to indicate that the string will span several lines. In -literals, newlines are preserved: - - [yml] - | - \/ /| |\/| | - / / | | | |__ - -Alternatively, strings can be written with the folded style, denoted by `>`, -where each line break is replaced by a space: - - [yml] - > - This is a very long sentence - that spans several lines in the YAML - but which will be rendered as a string - without carriage returns. - ->**NOTE** ->Notice the two spaces before each line in the previous examples. They ->won't appear in the resulting PHP strings. - -### Numbers - - [yml] - # an integer - 12 - -- - - [yml] - # an octal - 014 - -- - - [yml] - # an hexadecimal - 0xC - -- - - [yml] - # a float - 13.4 - -- - - [yml] - # an exponential number - 1.2e+34 - -- - - [yml] - # infinity - .inf - -### Nulls - -Nulls in YAML can be expressed with `null` or `~`. - -### Booleans - -Booleans in YAML are expressed with `true` and `false`. - ->**NOTE** ->The symfony YAML parser also recognize `on`, `off`, `yes`, and `no` but ->it is strongly discouraged to use them as it has been removed from the ->1.2 YAML specifications. - -### Dates - -YAML uses the ISO-8601 standard to express dates: - - [yml] - 2001-12-14t21:59:43.10-05:00 - -- - - [yml] - # simple date - 2002-12-14 - -Collections ------------ - -A YAML file is rarely used to describe a simple scalar. Most of the time, it -describes a collection. A collection can be a sequence or a mapping of -elements. Both sequences and mappings are converted to PHP arrays. - -Sequences use a dash followed by a space (`- `): - - [yml] - - PHP - - Perl - - Python - -The previous YAML file is equivalent to the following PHP code: - - [php] - array('PHP', 'Perl', 'Python'); - -Mappings use a colon followed by a space (`: `) to mark each key/value pair: - - [yml] - PHP: 5.2 - MySQL: 5.1 - Apache: 2.2.20 - -which is equivalent to this PHP code: - - [php] - array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20'); - ->**NOTE** ->In a mapping, a key can be any valid scalar. - -The number of spaces between the colon and the value does not matter: - - [yml] - PHP: 5.2 - MySQL: 5.1 - Apache: 2.2.20 - -YAML uses indentation with one or more spaces to describe nested collections: - - [yml] - "symfony 1.0": - PHP: 5.0 - Propel: 1.2 - "symfony 1.2": - PHP: 5.2 - Propel: 1.3 - -The following YAML is equivalent to the following PHP code: - - [php] - array( - 'symfony 1.0' => array( - 'PHP' => 5.0, - 'Propel' => 1.2, - ), - 'symfony 1.2' => array( - 'PHP' => 5.2, - 'Propel' => 1.3, - ), - ); - -There is one important thing you need to remember when using indentation in a -YAML file: *Indentation must be done with one or more spaces, but never with -tabulations*. - -You can nest sequences and mappings as you like: - - [yml] - 'Chapter 1': - - Introduction - - Event Types - 'Chapter 2': - - Introduction - - Helpers - -YAML can also use flow styles for collections, using explicit indicators -rather than indentation to denote scope. - -A sequence can be written as a comma separated list within square brackets -(`[]`): - - [yml] - [PHP, Perl, Python] - -A mapping can be written as a comma separated list of key/values within curly -braces (`{}`): - - [yml] - { PHP: 5.2, MySQL: 5.1, Apache: 2.2.20 } - -You can mix and match styles to achieve a better readability: - - [yml] - 'Chapter 1': [Introduction, Event Types] - 'Chapter 2': [Introduction, Helpers] - -- - - [yml] - "symfony 1.0": { PHP: 5.0, Propel: 1.2 } - "symfony 1.2": { PHP: 5.2, Propel: 1.3 } - -Comments --------- - -Comments can be added in YAML by prefixing them with a hash mark (`#`): - - [yml] - # Comment on a line - "symfony 1.0": { PHP: 5.0, Propel: 1.2 } # Comment at the end of a line - "symfony 1.2": { PHP: 5.2, Propel: 1.3 } - ->**NOTE** ->Comments are simply ignored by the YAML parser and do not need to be ->indented according to the current level of nesting in a collection. - -Dynamic YAML files ------------------- - -In symfony, a YAML file can contain PHP code that is evaluated just before the -parsing occurs: - - [php] - 1.0: - version: - 1.1: - version: "" - -Be careful to not mess up with the indentation. Keep in mind the following -simple tips when adding PHP code to a YAML file: - - * The `` statements must always start the line or be embedded in a - value. - - * If a `` statement ends a line, you need to explicitly output a new - line ("\n"). - -
- -A Full Length Example ---------------------- - -The following example illustrates most YAML notations explained in this -document: - - [yml] - "symfony 1.0": - end_of_maintainance: 2010-01-01 - is_stable: true - release_manager: "Grégoire Hubert" - description: > - This stable version is the right choice for projects - that need to be maintained for a long period of time. - latest_beta: ~ - latest_minor: 1.0.20 - supported_orms: [Propel] - archives: { source: [zip, tgz], sandbox: [zip, tgz] } - - "symfony 1.2": - end_of_maintainance: 2008-11-01 - is_stable: true - release_manager: 'Fabian Lange' - description: > - This stable version is the right choice - if you start a new project today. - latest_beta: null - latest_minor: 1.2.5 - supported_orms: - - Propel - - Doctrine - archives: - source: - - zip - - tgz - sandbox: - - zip - - tgz diff --git a/test/lib/yaml/doc/A-License.markdown b/test/lib/yaml/doc/A-License.markdown deleted file mode 100644 index 49cdd7c..0000000 --- a/test/lib/yaml/doc/A-License.markdown +++ /dev/null @@ -1,108 +0,0 @@ -Appendix A - License -==================== - -Attribution-Share Alike 3.0 Unported License --------------------------------------------- - -THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS CREATIVE COMMONS PUBLIC LICENSE ("CCPL" OR "LICENSE"). THE WORK IS PROTECTED BY COPYRIGHT AND/OR OTHER APPLICABLE LAW. ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED. - -BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED HERE, YOU ACCEPT AND AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE. TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN CONSIDERATION OF YOUR ACCEPTANCE OF SUCH TERMS AND CONDITIONS. - -1. Definitions - - a. **"Adaptation"** means a work based upon the Work, or upon the Work and other pre-existing works, such as a translation, adaptation, derivative work, arrangement of music or other alterations of a literary or artistic work, or phonogram or performance and includes cinematographic adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a work that constitutes a Collection will not be considered an Adaptation for the purpose of this License. For the avoidance of doubt, where the Work is a musical work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an Adaptation for the purpose of this License. - - b. **"Collection"** means a collection of literary or artistic works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other works or subject matter other than works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent works in themselves, which together are assembled into a collective whole. A work that constitutes a Collection will not be considered an Adaptation (as defined below) for the purposes of this License. - - c. **"Creative Commons Compatible License"** means a license that is listed at http://creativecommons.org/compatiblelicenses that has been approved by Creative Commons as being essentially equivalent to this License, including, at a minimum, because that license: (i) contains terms that have the same purpose, meaning and effect as the License Elements of this License; and, (ii) explicitly permits the relicensing of adaptations of works made available under that license under this License or a Creative Commons jurisdiction license with the same License Elements as this License. - - d. **"Distribute"** means to make available to the public the original and copies of the Work or Adaptation, as appropriate, through sale or other transfer of ownership. - - e. **"License Elements"** means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. - - f. **"Licensor"** means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. - - g. **"Original Author"** means, in the case of a literary or artistic work, the individual, individuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast. - - h. **"Work"** means the literary and/or artistic work offered under the terms of this License including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other work of the same nature; a dramatic or dramatico-musical work; a choreographic work or entertainment in dumb show; a musical composition with or without words; a cinematographic work to which are assimilated works expressed by a process analogous to cinematography; a work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic work to which are assimilated works expressed by a process analogous to photography; a work of applied art; an illustration, map, plan, sketch or three-dimensional work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable work; or a work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic work. - - i. **"You"** means an individual or entity exercising rights under this License who has not previously violated the terms of this License with respect to the Work, or who has received express permission from the Licensor to exercise rights under this License despite a previous violation. - - j. **"Publicly Perform"** means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images. - - k. **"Reproduce"** means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium. - -2. Fair Dealing Rights - - Nothing in this License is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws. - -3. License Grant - - Subject to the terms and conditions of this License, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below: - - a. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; - - b. to create and Reproduce Adaptations provided that any such Adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "The original work was translated from English to Spanish," or a modification could indicate "The original work has been modified."; - - c. to Distribute and Publicly Perform the Work including as incorporated in Collections; and, - - d. to Distribute and Publicly Perform Adaptations. - - e. For the avoidance of doubt: - - i. **Non-waivable Compulsory License Schemes**. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme cannot be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; - - ii. **Waivable Compulsory License Schemes**. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor waives the exclusive right to collect such royalties for any exercise by You of the rights granted under this License; and, - - iii. **Voluntary License Schemes**. The Licensor waives the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this License. - - The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved. - -4. Restrictions - - The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: - - a. You may Distribute or Publicly Perform the Work only under the terms of this License. You must include a copy of, or the Uniform Resource Identifier (URI) for, this License with every copy of the Work You Distribute or Publicly Perform. You may not offer or impose any terms on the Work that restrict the terms of this License or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the License. You may not sublicense the Work. You must keep intact all notices that refer to this License and to the disclaimer of warranties with every copy of the Work You Distribute or Publicly Perform. When You Distribute or Publicly Perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the License. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this License. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(c), as requested. If You create an Adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the Adaptation any credit as required by Section 4(c), as requested. - - b. You may Distribute or Publicly Perform an Adaptation only under the terms of: (i) this License; (ii) a later version of this License with the same License Elements as this License; (iii) a Creative Commons jurisdiction license (either this or a later license version) that contains the same License Elements as this License (e.g., Attribution-ShareAlike 3.0 US)); (iv) a Creative Commons Compatible License. If you license the Adaptation under one of the licenses mentioned in (iv), you must comply with the terms of that license. If you license the Adaptation under the terms of any of the licenses mentioned in (i), (ii) or (iii) (the "Applicable License"), you must comply with the terms of the Applicable License generally and the following provisions: (I) You must include a copy of, or the URI for, the Applicable License with every copy of each Adaptation You Distribute or Publicly Perform; (II) You may not offer or impose any terms on the Adaptation that restrict the terms of the Applicable License or the ability of the recipient of the Adaptation to exercise the rights granted to that recipient under the terms of the Applicable License; (III) You must keep intact all notices that refer to the Applicable License and to the disclaimer of warranties with every copy of the Work as included in the Adaptation You Distribute or Publicly Perform; (IV) when You Distribute or Publicly Perform the Adaptation, You may not impose any effective technological measures on the Adaptation that restrict the ability of a recipient of the Adaptation from You to exercise the rights granted to that recipient under the terms of the Applicable License. This Section 4(b) applies to the Adaptation as incorporated in a Collection, but this does not require the Collection apart from the Adaptation itself to be made subject to the terms of the Applicable License. - - c. If You Distribute, or Publicly Perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("Attribution Parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reasonably practicable, the URI, if any, that Licensor specifies to be associated with the Work, unless such URI does not refer to the copyright notice or licensing information for the Work; and (iv) , consistent with Ssection 3(b), in the case of an Adaptation, a credit identifying the use of the Work in the Adaptation (e.g., "French translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(c) may be implemented in any reasonable manner; provided, however, that in the case of a Adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the Adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this License, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or Attribution Parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or Attribution Parties. - - d. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, Distribute or Publicly Perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this License (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this License (right to make Adaptations) but not otherwise. - -5. Representations, Warranties and Disclaimer - - UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS-IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTIBILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU. - -6. Limitation on Liability - - EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -7. Termination - - a. This License and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this License. Individuals or entities who have received Adaptations or Collections from You under this License, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this License. - - b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this License (or any other license that has been, or is required to be, granted under the terms of this License), and this License will continue in full force and effect unless terminated as stated above. - -8. Miscellaneous - - a. Each time You Distribute or Publicly Perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this License. - - b. Each time You Distribute or Publicly Perform an Adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this License. - - c. If any provision of this License is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this License, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. - - d. No term or provision of this License shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent. - - e. This License constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This License may not be modified without the mutual written agreement of the Licensor and You. - - f. The rights granted under, and the subject matter referenced, in this License were drafted utilizing the terminology of the Berne Convention for the Protection of Literary and Artistic Works (as amended on September 28, 1979), the Rome Convention of 1961, the WIPO Copyright Treaty of 1996, the WIPO Performances and Phonograms Treaty of 1996 and the Universal Copyright Convention (as revised on July 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the License terms are sought to be enforced according to the corresponding provisions of the implementation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this License, such additional rights are deemed to be included in the License; this License is not intended to restrict the license of any rights under applicable law. - ->**SIDEBAR** ->Creative Commons Notice -> ->Creative Commons is not a party to this License, and makes no warranty whatsoever in connection with the Work. Creative Commons will not be liable to You or any party on any legal theory for any damages whatsoever, including without limitation any general, special, incidental or consequential damages arising in connection to this license. Notwithstanding the foregoing two (2) sentences, if Creative Commons has expressly identified itself as the Licensor hereunder, it shall have all rights and obligations of Licensor. -> ->Except for the limited purpose of indicating to the public that the Work is licensed under the CCPL, Creative Commons does not authorize the use by either party of the trademark "Creative Commons" or any related trademark or logo of Creative Commons without the prior written consent of Creative Commons. Any permitted use will be in compliance with Creative Commons' then-current trademark usage guidelines, as may be published on its website or otherwise made available upon request from time to time. For the avoidance of doubt, this trademark restriction does not form part of the License. -> ->Creative Commons may be contacted at http://creativecommons.org/. diff --git a/test/lib/yaml/lib/sfYaml.php b/test/lib/yaml/lib/sfYaml.php deleted file mode 100644 index 1d89ccc..0000000 --- a/test/lib/yaml/lib/sfYaml.php +++ /dev/null @@ -1,135 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -/** - * sfYaml offers convenience methods to load and dump YAML. - * - * @package symfony - * @subpackage yaml - * @author Fabien Potencier - * @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $ - */ -class sfYaml -{ - static protected - $spec = '1.2'; - - /** - * Sets the YAML specification version to use. - * - * @param string $version The YAML specification version - */ - static public function setSpecVersion($version) - { - if (!in_array($version, array('1.1', '1.2'))) - { - throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); - } - - self::$spec = $version; - } - - /** - * Gets the YAML specification version to use. - * - * @return string The YAML specification version - */ - static public function getSpecVersion() - { - return self::$spec; - } - - /** - * Loads YAML into a PHP array. - * - * The load method, when supplied with a YAML stream (string or file), - * will do its best to convert YAML in a file into a PHP array. - * - * Usage: - * - * $array = sfYaml::load('config.yml'); - * print_r($array); - * - * - * @param string $input Path of YAML file or string containing YAML - * - * @return array The YAML converted to a PHP array - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public static function load($input) - { - $file = ''; - - // if input is a file, process it - if (strpos($input, "\n") === false && is_file($input)) - { - $file = $input; - - ob_start(); - $retval = include($input); - $content = ob_get_clean(); - - // if an array is returned by the config file assume it's in plain php form else in YAML - $input = is_array($retval) ? $retval : $content; - } - - // if an array is returned by the config file assume it's in plain php form else in YAML - if (is_array($input)) - { - return $input; - } - - require_once dirname(__FILE__).'/sfYamlParser.php'; - - $yaml = new sfYamlParser(); - - try - { - $ret = $yaml->parse($input); - } - catch (Exception $e) - { - throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); - } - - return $ret; - } - - /** - * Dumps a PHP array to a YAML string. - * - * The dump method, when supplied with an array, will do its best - * to convert the array into friendly YAML. - * - * @param array $array PHP array - * @param integer $inline The level where you switch to inline YAML - * - * @return string A YAML string representing the original PHP array - */ - public static function dump($array, $inline = 2) - { - require_once dirname(__FILE__).'/sfYamlDumper.php'; - - $yaml = new sfYamlDumper(); - - return $yaml->dump($array, $inline); - } -} - -/** - * Wraps echo to automatically provide a newline. - * - * @param string $string The string to echo with new line - */ -function echoln($string) -{ - echo $string."\n"; -} diff --git a/test/lib/yaml/lib/sfYamlDumper.php b/test/lib/yaml/lib/sfYamlDumper.php deleted file mode 100644 index 0ada2b3..0000000 --- a/test/lib/yaml/lib/sfYamlDumper.php +++ /dev/null @@ -1,60 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -require_once(dirname(__FILE__).'/sfYamlInline.php'); - -/** - * sfYamlDumper dumps PHP variables to YAML strings. - * - * @package symfony - * @subpackage yaml - * @author Fabien Potencier - * @version SVN: $Id: sfYamlDumper.class.php 10575 2008-08-01 13:08:42Z nicolas $ - */ -class sfYamlDumper -{ - /** - * Dumps a PHP value to YAML. - * - * @param mixed $input The PHP value - * @param integer $inline The level where you switch to inline YAML - * @param integer $indent The level o indentation indentation (used internally) - * - * @return string The YAML representation of the PHP value - */ - public function dump($input, $inline = 0, $indent = 0) - { - $output = ''; - $prefix = $indent ? str_repeat(' ', $indent) : ''; - - if ($inline <= 0 || !is_array($input) || empty($input)) - { - $output .= $prefix.sfYamlInline::dump($input); - } - else - { - $isAHash = array_keys($input) !== range(0, count($input) - 1); - - foreach ($input as $key => $value) - { - $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); - - $output .= sprintf('%s%s%s%s', - $prefix, - $isAHash ? sfYamlInline::dump($key).':' : '-', - $willBeInlined ? ' ' : "\n", - $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) - ).($willBeInlined ? "\n" : ''); - } - } - - return $output; - } -} diff --git a/test/lib/yaml/lib/sfYamlInline.php b/test/lib/yaml/lib/sfYamlInline.php deleted file mode 100644 index a88cbb3..0000000 --- a/test/lib/yaml/lib/sfYamlInline.php +++ /dev/null @@ -1,442 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -require_once dirname(__FILE__).'/sfYaml.php'; - -/** - * sfYamlInline implements a YAML parser/dumper for the YAML inline syntax. - * - * @package symfony - * @subpackage yaml - * @author Fabien Potencier - * @version SVN: $Id: sfYamlInline.class.php 16177 2009-03-11 08:32:48Z fabien $ - */ -class sfYamlInline -{ - const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; - - /** - * Convert a YAML string to a PHP array. - * - * @param string $value A YAML string - * - * @return array A PHP array representing the YAML string - */ - static public function load($value) - { - $value = trim($value); - - if (0 == strlen($value)) - { - return ''; - } - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) - { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('ASCII'); - } - - switch ($value[0]) - { - case '[': - $result = self::parseSequence($value); - break; - case '{': - $result = self::parseMapping($value); - break; - default: - $result = self::parseScalar($value); - } - - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } - - return $result; - } - - /** - * Dumps a given PHP variable to a YAML string. - * - * @param mixed $value The PHP variable to convert - * - * @return string The YAML string representing the PHP array - */ - static public function dump($value) - { - if ('1.1' === sfYaml::getSpecVersion()) - { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); - } - else - { - $trueValues = array('true'); - $falseValues = array('false'); - } - - switch (true) - { - case is_resource($value): - throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); - case is_object($value): - return '!!php/object:'.serialize($value); - case is_array($value): - return self::dumpArray($value); - case null === $value: - return 'null'; - case true === $value: - return 'true'; - case false === $value: - return 'false'; - case ctype_digit($value): - return is_string($value) ? "'$value'" : (int) $value; - case is_numeric($value): - return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value); - case false !== strpos($value, "\n") || false !== strpos($value, "\r"): - return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); - case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): - return sprintf("'%s'", str_replace('\'', '\'\'', $value)); - case '' == $value: - return "''"; - case preg_match(self::getTimestampRegex(), $value): - return "'$value'"; - case in_array(strtolower($value), $trueValues): - return "'$value'"; - case in_array(strtolower($value), $falseValues): - return "'$value'"; - case in_array(strtolower($value), array('null', '~')): - return "'$value'"; - default: - return $value; - } - } - - /** - * Dumps a PHP array to a YAML string. - * - * @param array $value The PHP array to dump - * - * @return string The YAML string representing the PHP array - */ - static protected function dumpArray($value) - { - // array - $keys = array_keys($value); - if ( - (1 == count($keys) && '0' == $keys[0]) - || - (count($keys) > 1 && array_reduce($keys, create_function('$v,$w', 'return (integer) $v + $w;'), 0) == count($keys) * (count($keys) - 1) / 2)) - { - $output = array(); - foreach ($value as $val) - { - $output[] = self::dump($val); - } - - return sprintf('[%s]', implode(', ', $output)); - } - - // mapping - $output = array(); - foreach ($value as $key => $val) - { - $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); - } - - return sprintf('{ %s }', implode(', ', $output)); - } - - /** - * Parses a scalar to a YAML string. - * - * @param scalar $scalar - * @param string $delimiters - * @param array $stringDelimiter - * @param integer $i - * @param boolean $evaluate - * - * @return string A YAML string - */ - static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) - { - if (in_array($scalar[$i], $stringDelimiters)) - { - // quoted scalar - $output = self::parseQuotedScalar($scalar, $i); - } - else - { - // "normal" string - if (!$delimiters) - { - $output = substr($scalar, $i); - $i += strlen($output); - - // remove comments - if (false !== $strpos = strpos($output, ' #')) - { - $output = rtrim(substr($output, 0, $strpos)); - } - } - else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) - { - $output = $match[1]; - $i += strlen($output); - } - else - { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); - } - - $output = $evaluate ? self::evaluateScalar($output) : $output; - } - - return $output; - } - - /** - * Parses a quoted scalar to YAML. - * - * @param string $scalar - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseQuotedScalar($scalar, &$i) - { - if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) - { - throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); - } - - $output = substr($match[0], 1, strlen($match[0]) - 2); - - if ('"' == $scalar[$i]) - { - // evaluate the string - $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); - } - else - { - // unescape ' - $output = str_replace('\'\'', '\'', $output); - } - - $i += strlen($match[0]); - - return $output; - } - - /** - * Parses a sequence to a YAML string. - * - * @param string $sequence - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseSequence($sequence, &$i = 0) - { - $output = array(); - $len = strlen($sequence); - $i += 1; - - // [foo, bar, ...] - while ($i < $len) - { - switch ($sequence[$i]) - { - case '[': - // nested sequence - $output[] = self::parseSequence($sequence, $i); - break; - case '{': - // nested mapping - $output[] = self::parseMapping($sequence, $i); - break; - case ']': - return $output; - case ',': - case ' ': - break; - default: - $isQuoted = in_array($sequence[$i], array('"', "'")); - $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); - - if (!$isQuoted && false !== strpos($value, ': ')) - { - // embedded mapping? - try - { - $value = self::parseMapping('{'.$value.'}'); - } - catch (InvalidArgumentException $e) - { - // no, it's not - } - } - - $output[] = $value; - - --$i; - } - - ++$i; - } - - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); - } - - /** - * Parses a mapping to a YAML string. - * - * @param string $mapping - * @param integer $i - * - * @return string A YAML string - */ - static protected function parseMapping($mapping, &$i = 0) - { - $output = array(); - $len = strlen($mapping); - $i += 1; - - // {foo: bar, bar:foo, ...} - while ($i < $len) - { - switch ($mapping[$i]) - { - case ' ': - case ',': - ++$i; - continue 2; - case '}': - return $output; - } - - // key - $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); - - // value - $done = false; - while ($i < $len) - { - switch ($mapping[$i]) - { - case '[': - // nested sequence - $output[$key] = self::parseSequence($mapping, $i); - $done = true; - break; - case '{': - // nested mapping - $output[$key] = self::parseMapping($mapping, $i); - $done = true; - break; - case ':': - case ' ': - break; - default: - $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); - $done = true; - --$i; - } - - ++$i; - - if ($done) - { - continue 2; - } - } - } - - throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); - } - - /** - * Evaluates scalars and replaces magic values. - * - * @param string $scalar - * - * @return string A YAML string - */ - static protected function evaluateScalar($scalar) - { - $scalar = trim($scalar); - - if ('1.1' === sfYaml::getSpecVersion()) - { - $trueValues = array('true', 'on', '+', 'yes', 'y'); - $falseValues = array('false', 'off', '-', 'no', 'n'); - } - else - { - $trueValues = array('true'); - $falseValues = array('false'); - } - - switch (true) - { - case 'null' == strtolower($scalar): - case '' == $scalar: - case '~' == $scalar: - return null; - case 0 === strpos($scalar, '!str'): - return (string) substr($scalar, 5); - case 0 === strpos($scalar, '! '): - return intval(self::parseScalar(substr($scalar, 2))); - case 0 === strpos($scalar, '!!php/object:'): - return unserialize(substr($scalar, 13)); - case ctype_digit($scalar): - $raw = $scalar; - $cast = intval($scalar); - return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); - case in_array(strtolower($scalar), $trueValues): - return true; - case in_array(strtolower($scalar), $falseValues): - return false; - case is_numeric($scalar): - return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); - case 0 == strcasecmp($scalar, '.inf'): - case 0 == strcasecmp($scalar, '.NaN'): - return -log(0); - case 0 == strcasecmp($scalar, '-.inf'): - return log(0); - case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): - return floatval(str_replace(',', '', $scalar)); - case preg_match(self::getTimestampRegex(), $scalar): - return strtotime($scalar); - default: - return (string) $scalar; - } - } - - static protected function getTimestampRegex() - { - return <<[0-9][0-9][0-9][0-9]) - -(?P[0-9][0-9]?) - -(?P[0-9][0-9]?) - (?:(?:[Tt]|[ \t]+) - (?P[0-9][0-9]?) - :(?P[0-9][0-9]) - :(?P[0-9][0-9]) - (?:\.(?P[0-9]*))? - (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) - (?::(?P[0-9][0-9]))?))?)? - $~x -EOF; - } -} diff --git a/test/lib/yaml/lib/sfYamlParser.php b/test/lib/yaml/lib/sfYamlParser.php deleted file mode 100644 index 91da2dc..0000000 --- a/test/lib/yaml/lib/sfYamlParser.php +++ /dev/null @@ -1,622 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -require_once(dirname(__FILE__).'/sfYamlInline.php'); - -if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) -{ - define('PREG_BAD_UTF8_OFFSET_ERROR', 5); -} - -/** - * sfYamlParser parses YAML strings to convert them to PHP arrays. - * - * @package symfony - * @subpackage yaml - * @author Fabien Potencier - * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $ - */ -class sfYamlParser -{ - protected - $offset = 0, - $lines = array(), - $currentLineNb = -1, - $currentLine = '', - $refs = array(); - - /** - * Constructor - * - * @param integer $offset The offset of YAML document (used for line numbers in error messages) - */ - public function __construct($offset = 0) - { - $this->offset = $offset; - } - - /** - * Parses a YAML string to a PHP value. - * - * @param string $value A YAML string - * - * @return mixed A PHP value - * - * @throws InvalidArgumentException If the YAML is not valid - */ - public function parse($value) - { - $this->currentLineNb = -1; - $this->currentLine = ''; - $this->lines = explode("\n", $this->cleanup($value)); - - if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) - { - $mbEncoding = mb_internal_encoding(); - mb_internal_encoding('UTF-8'); - } - - $data = array(); - while ($this->moveToNextLine()) - { - if ($this->isCurrentLineEmpty()) - { - continue; - } - - // tab? - if (preg_match('#^\t+#', $this->currentLine)) - { - throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - - $isRef = $isInPlace = $isProcessed = false; - if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } - - // array - if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[] = $parser->parse($this->getNextEmbedBlock()); - } - else - { - if (isset($values['leadspaces']) - && ' ' == $values['leadspaces'] - && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) - { - // this is a compact notation element, add to next block and parse - $c = $this->getRealCurrentLineNb(); - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - - $block = $values['value']; - if (!$this->isNextLineIndented()) - { - $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); - } - - $data[] = $parser->parse($block); - } - else - { - $data[] = $this->parseValue($values['value']); - } - } - } - else if (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) - { - $key = sfYamlInline::parseScalar($values['key']); - - if ('<<' === $key) - { - if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) - { - $isInPlace = substr($values['value'], 1); - if (!array_key_exists($isInPlace, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } - else - { - if (isset($values['value']) && $values['value'] !== '') - { - $value = $values['value']; - } - else - { - $value = $this->getNextEmbedBlock(); - } - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $parsed = $parser->parse($value); - - $merged = array(); - if (!is_array($parsed)) - { - throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - else if (isset($parsed[0])) - { - // Numeric array, merge individual elements - foreach (array_reverse($parsed) as $parsedItem) - { - if (!is_array($parsedItem)) - { - throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); - } - $merged = array_merge($parsedItem, $merged); - } - } - else - { - // Associative array, merge - $merged = array_merge($merge, $parsed); - } - - $isProcessed = $merged; - } - } - else if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) - { - $isRef = $matches['ref']; - $values['value'] = $matches['value']; - } - - if ($isProcessed) - { - // Merge keys - $data = $isProcessed; - } - // hash - else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) - { - // if next line is less indented or equal, then it means that the current value is null - if ($this->isNextLineIndented()) - { - $data[$key] = null; - } - else - { - $c = $this->getRealCurrentLineNb() + 1; - $parser = new sfYamlParser($c); - $parser->refs =& $this->refs; - $data[$key] = $parser->parse($this->getNextEmbedBlock()); - } - } - else - { - if ($isInPlace) - { - $data = $this->refs[$isInPlace]; - } - else - { - $data[$key] = $this->parseValue($values['value']); - } - } - } - else - { - // 1-liner followed by newline - if (2 == count($this->lines) && empty($this->lines[1])) - { - $value = sfYamlInline::load($this->lines[0]); - if (is_array($value)) - { - $first = reset($value); - if ('*' === substr($first, 0, 1)) - { - $data = array(); - foreach ($value as $alias) - { - $data[] = $this->refs[substr($alias, 1)]; - } - $value = $data; - } - } - - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } - - return $value; - } - - switch (preg_last_error()) - { - case PREG_INTERNAL_ERROR: - $error = 'Internal PCRE error on line'; - break; - case PREG_BACKTRACK_LIMIT_ERROR: - $error = 'pcre.backtrack_limit reached on line'; - break; - case PREG_RECURSION_LIMIT_ERROR: - $error = 'pcre.recursion_limit reached on line'; - break; - case PREG_BAD_UTF8_ERROR: - $error = 'Malformed UTF-8 data on line'; - break; - case PREG_BAD_UTF8_OFFSET_ERROR: - $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; - break; - default: - $error = 'Unable to parse line'; - } - - throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - - if ($isRef) - { - $this->refs[$isRef] = end($data); - } - } - - if (isset($mbEncoding)) - { - mb_internal_encoding($mbEncoding); - } - - return empty($data) ? null : $data; - } - - /** - * Returns the current line number (takes the offset into account). - * - * @return integer The current line number - */ - protected function getRealCurrentLineNb() - { - return $this->currentLineNb + $this->offset; - } - - /** - * Returns the current line indentation. - * - * @return integer The current line indentation - */ - protected function getCurrentLineIndentation() - { - return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); - } - - /** - * Returns the next embed block of YAML. - * - * @param integer $indentation The indent level at which the block is to be read, or null for default - * - * @return string A YAML string - */ - protected function getNextEmbedBlock($indentation = null) - { - $this->moveToNextLine(); - - if (null === $indentation) - { - $newIndent = $this->getCurrentLineIndentation(); - - if (!$this->isCurrentLineEmpty() && 0 == $newIndent) - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } - else - { - $newIndent = $indentation; - } - - $data = array(substr($this->currentLine, $newIndent)); - - while ($this->moveToNextLine()) - { - if ($this->isCurrentLineEmpty()) - { - if ($this->isCurrentLineBlank()) - { - $data[] = substr($this->currentLine, $newIndent); - } - - continue; - } - - $indent = $this->getCurrentLineIndentation(); - - if (preg_match('#^(?P *)$#', $this->currentLine, $match)) - { - // empty line - $data[] = $match['text']; - } - else if ($indent >= $newIndent) - { - $data[] = substr($this->currentLine, $newIndent); - } - else if (0 == $indent) - { - $this->moveToPreviousLine(); - - break; - } - else - { - throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); - } - } - - return implode("\n", $data); - } - - /** - * Moves the parser to the next line. - */ - protected function moveToNextLine() - { - if ($this->currentLineNb >= count($this->lines) - 1) - { - return false; - } - - $this->currentLine = $this->lines[++$this->currentLineNb]; - - return true; - } - - /** - * Moves the parser to the previous line. - */ - protected function moveToPreviousLine() - { - $this->currentLine = $this->lines[--$this->currentLineNb]; - } - - /** - * Parses a YAML value. - * - * @param string $value A YAML value - * - * @return mixed A PHP value - */ - protected function parseValue($value) - { - if ('*' === substr($value, 0, 1)) - { - if (false !== $pos = strpos($value, '#')) - { - $value = substr($value, 1, $pos - 2); - } - else - { - $value = substr($value, 1); - } - - if (!array_key_exists($value, $this->refs)) - { - throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); - } - return $this->refs[$value]; - } - - if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) - { - $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; - - return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); - } - else - { - return sfYamlInline::load($value); - } - } - - /** - * Parses a folded scalar. - * - * @param string $separator The separator that was used to begin this folded scalar (| or >) - * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) - * @param integer $indentation The indentation that was used to begin this folded scalar - * - * @return string The text value - */ - protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) - { - $separator = '|' == $separator ? "\n" : ' '; - $text = ''; - - $notEOF = $this->moveToNextLine(); - - while ($notEOF && $this->isCurrentLineBlank()) - { - $text .= "\n"; - - $notEOF = $this->moveToNextLine(); - } - - if (!$notEOF) - { - return ''; - } - - if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) - { - $this->moveToPreviousLine(); - - return ''; - } - - $textIndent = $matches['indent']; - $previousIndent = 0; - - $text .= $matches['text'].$separator; - while ($this->currentLineNb + 1 < count($this->lines)) - { - $this->moveToNextLine(); - - if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) - { - if (' ' == $separator && $previousIndent != $matches['indent']) - { - $text = substr($text, 0, -1)."\n"; - } - $previousIndent = $matches['indent']; - - $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); - } - else if (preg_match('#^(?P *)$#', $this->currentLine, $matches)) - { - $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; - } - else - { - $this->moveToPreviousLine(); - - break; - } - } - - if (' ' == $separator) - { - // replace last separator by a newline - $text = preg_replace('/ (\n*)$/', "\n$1", $text); - } - - switch ($indicator) - { - case '': - $text = preg_replace('#\n+$#s', "\n", $text); - break; - case '+': - break; - case '-': - $text = preg_replace('#\n+$#s', '', $text); - break; - } - - return $text; - } - - /** - * Returns true if the next line is indented. - * - * @return Boolean Returns true if the next line is indented, false otherwise - */ - protected function isNextLineIndented() - { - $currentIndentation = $this->getCurrentLineIndentation(); - $notEOF = $this->moveToNextLine(); - - while ($notEOF && $this->isCurrentLineEmpty()) - { - $notEOF = $this->moveToNextLine(); - } - - if (false === $notEOF) - { - return false; - } - - $ret = false; - if ($this->getCurrentLineIndentation() <= $currentIndentation) - { - $ret = true; - } - - $this->moveToPreviousLine(); - - return $ret; - } - - /** - * Returns true if the current line is blank or if it is a comment line. - * - * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise - */ - protected function isCurrentLineEmpty() - { - return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); - } - - /** - * Returns true if the current line is blank. - * - * @return Boolean Returns true if the current line is blank, false otherwise - */ - protected function isCurrentLineBlank() - { - return '' == trim($this->currentLine, ' '); - } - - /** - * Returns true if the current line is a comment line. - * - * @return Boolean Returns true if the current line is a comment line, false otherwise - */ - protected function isCurrentLineComment() - { - //checking explicitly the first char of the trim is faster than loops or strpos - $ltrimmedLine = ltrim($this->currentLine, ' '); - return $ltrimmedLine[0] === '#'; - } - - /** - * Cleanups a YAML string to be parsed. - * - * @param string $value The input YAML string - * - * @return string A cleaned up YAML string - */ - protected function cleanup($value) - { - $value = str_replace(array("\r\n", "\r"), "\n", $value); - - if (!preg_match("#\n$#", $value)) - { - $value .= "\n"; - } - - // strip YAML header - $count = 0; - $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); - $this->offset += $count; - - // remove leading comments - $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); - if ($count == 1) - { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; - } - - // remove start of the document marker (---) - $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); - if ($count == 1) - { - // items have been removed, update the offset - $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); - $value = $trimmedValue; - - // remove end of the document marker (...) - $value = preg_replace('#\.\.\.\s*$#s', '', $value); - } - - return $value; - } -} diff --git a/test/lib/yaml/package.xml b/test/lib/yaml/package.xml deleted file mode 100644 index 1869ae9..0000000 --- a/test/lib/yaml/package.xml +++ /dev/null @@ -1,102 +0,0 @@ - - - YAML - pear.symfony-project.com - The Symfony YAML Component. - The Symfony YAML Component. - - Fabien Potencier - fabpot - fabien.potencier@symfony-project.org - yes - - 2009-12-01 - - 1.0.2 - 1.0.0 - - - stable - stable - - MIT license - - - - - - - - - - - - - - - - - - - - 5.2.4 - - - 1.4.1 - - - - - - - - - - - 1.0.2 - 1.0.0 - - - stable - stable - - MIT license - 2009-12-01 - MIT - - * fabien: fixed \ usage in quoted string - - - - - 1.0.1 - 1.0.0 - - - stable - stable - - MIT license - 2009-12-01 - MIT - - * fabien: fixed a possible loop in parsing a non-valid quoted string - - - - - 1.0.0 - 1.0.0 - - - stable - stable - - MIT license - 2009-11-30 - MIT - - * fabien: first stable release as a Symfony Component - - - - diff --git a/test/spec b/vendor/spec similarity index 100% rename from test/spec rename to vendor/spec diff --git a/vendor/yaml b/vendor/yaml new file mode 160000 index 0000000..8a266aa --- /dev/null +++ b/vendor/yaml @@ -0,0 +1 @@ +Subproject commit 8a266aadcec878681ed458796b1ce792cc377f79 From ee4c52de8fdb193e24817e6bc4a44ecba9eb40e5 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sun, 4 Mar 2012 21:32:22 -0800 Subject: [PATCH 12/58] Fix E_STRICT warning in i18n example. --- examples/i18n/I18n.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/i18n/I18n.php b/examples/i18n/I18n.php index 73cdd74..ea62c5d 100644 --- a/examples/i18n/I18n.php +++ b/examples/i18n/I18n.php @@ -14,7 +14,7 @@ class I18n { 'My name is {{ name }}.' => 'Me llamo {{ name }}.', ); - public function __trans($text) { + public static function __trans($text) { return isset(self::$dictionary[$text]) ? self::$dictionary[$text] : $text; } } From 36e7247b1ebae6444d6e39792d32c10d48f881f1 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sun, 4 Mar 2012 21:35:33 -0800 Subject: [PATCH 13/58] Add a shortcut Mustache::render invocation. Consistent with the old 1.x API. --- src/Mustache/Mustache.php | 17 +++++++++++++++ test/Mustache/Test/MustacheTest.php | 32 +++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index d996ef3..8975907 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -95,6 +95,23 @@ class Mustache { } } + /** + * Shortcut 'render' invocation. + * + * Equivalent to calling `$mustache->loadTemplate($template)->render($data);` + * + * @see \Mustache\Mustache::loadTemplate + * @see \Mustache\Template::render + * + * @param string $template + * @param mixed $data + * + * @return string Rendered template + */ + public function render($template, $data) { + return $this->loadTemplate($template)->render($data); + } + /** * Get the current Mustache character set. * diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 4ed9115..88f9a03 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -53,6 +53,27 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('ISO-8859-1', $mustache->getCharset()); } + public function testRender() { + $source = '{{ foo }}'; + $data = array('bar' => 'baz'); + $output = 'TEH OUTPUT'; + + $template = $this->getMockBuilder('Mustache\Template') + ->disableOriginalConstructor() + ->getMock(); + + $mustache = new MustacheStub; + $mustache->template = $template; + + $template->expects($this->once()) + ->method('render') + ->with($data) + ->will($this->returnValue($output)); + + $this->assertEquals($output, $mustache->render($source, $data)); + $this->assertEquals($source, $mustache->source); + } + public function testSettingServices() { $loader = new StringLoader; $tokenizer = new Tokenizer; @@ -122,6 +143,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $mustache->setPartials(array('foo' => '{{ foo }}')); } + private static function rmdir($path) { $path = rtrim($path, '/').'/'; $handle = opendir($path); @@ -143,6 +165,16 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { } } +class MustacheStub extends Mustache { + public $source; + public $template; + public function loadTemplate($source) { + $this->source = $source; + + return $this->template; + } +} + // It's prob'ly best if you ignore this bit. From a196ac8dab5df88bd9e9564c39c3bb177d8ac313 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 5 Mar 2012 14:25:32 -0800 Subject: [PATCH 14/58] Clean up Tokenizer constants. Remove a bunch of hardcoded strings from everywhere. --- src/Mustache/Compiler.php | 18 +++--- src/Mustache/Parser.php | 8 +-- src/Mustache/Tokenizer.php | 97 +++++++++++++++------------- test/Mustache/Test/CompilerTest.php | 6 +- test/Mustache/Test/ParserTest.php | 52 +++++++-------- test/Mustache/Test/TokenizerTest.php | 16 ++--- 6 files changed, 101 insertions(+), 96 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 74aeb7b..3c5b7ee 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -47,8 +47,8 @@ class Compiler { $code = ''; $level++; foreach ($tree as $node) { - switch (is_string($node) ? 'text' : $node[Tokenizer::TAG]) { - case '#': + switch (is_string($node) ? 'text' : $node[Tokenizer::TYPE]) { + case Tokenizer::T_SECTION: $code .= $this->section( $node[Tokenizer::NODES], $node[Tokenizer::NAME], @@ -60,7 +60,7 @@ class Compiler { ); break; - case '^': + case Tokenizer::T_INVERTED: $code .= $this->invertedSection( $node[Tokenizer::NODES], $node[Tokenizer::NAME], @@ -68,8 +68,8 @@ class Compiler { ); break; - case '<': - case '>': + case Tokenizer::T_PARTIAL: + case Tokenizer::T_PARTIAL_2: $code .= $this->partial( $node[Tokenizer::NAME], isset($node[Tokenizer::INDENT]) ? $node[Tokenizer::INDENT] : '', @@ -77,15 +77,15 @@ class Compiler { ); break; - case '{': - case '&': + case Tokenizer::T_UNESCAPED: + case Tokenizer::T_UNESCAPED_2: $code .= $this->variable($node[Tokenizer::NAME], false, $level); break; - case '!': + case Tokenizer::T_COMMENT: break; - case '_v': + case Tokenizer::T_ESCAPED: $code .= $this->variable($node[Tokenizer::NAME], true, $level); break; diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index 270877b..d115ce9 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -49,13 +49,13 @@ class Parser { if ($token === null) { continue; } elseif (is_array($token)) { - switch ($token[Tokenizer::TAG]) { - case '#': - case '^': + switch ($token[Tokenizer::TYPE]) { + case Tokenizer::T_SECTION: + case Tokenizer::T_INVERTED: $nodes[] = $this->buildTree($tokens, $token); break; - case '/': + case Tokenizer::T_END_SECTION: if (!isset($parent)) { throw new \LogicException('Unexpected closing tag: /'. $token[Tokenizer::NAME]); } diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index 16a6c8f..226f091 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -24,40 +24,47 @@ class Tokenizer { const IN_TAG = 2; // Token types - const T_SECTION = 1; - const T_INVERTED = 2; - const T_END_SECTION = 3; - const T_COMMENT = 4; - const T_PARTIAL = 5; - const T_PARTIAL_2 = 6; - const T_DELIM_CHANGE = 7; - const T_ESCAPED = 8; - const T_UNESCAPED = 9; - const T_UNESCAPED_2 = 10; + const T_SECTION = '#'; + const T_INVERTED = '^'; + const T_END_SECTION = '/'; + const T_COMMENT = '!'; + const T_PARTIAL = '>'; + const T_PARTIAL_2 = '<'; + const T_DELIM_CHANGE = '='; + const T_ESCAPED = '_v'; + const T_UNESCAPED = '{'; + const T_UNESCAPED_2 = '&'; - // Token types map + // Valid token types private static $tagTypes = array( - '#' => self::T_SECTION, - '^' => self::T_INVERTED, - '/' => self::T_END_SECTION, - '!' => self::T_COMMENT, - '>' => self::T_PARTIAL, - '<' => self::T_PARTIAL_2, - '=' => self::T_DELIM_CHANGE, - '_v' => self::T_ESCAPED, - '{' => self::T_UNESCAPED, - '&' => self::T_UNESCAPED_2, + self::T_SECTION => true, + self::T_INVERTED => true, + self::T_END_SECTION => true, + self::T_COMMENT => true, + self::T_PARTIAL => true, + self::T_PARTIAL_2 => true, + self::T_DELIM_CHANGE => true, + self::T_ESCAPED => true, + self::T_UNESCAPED => true, + self::T_UNESCAPED_2 => true, + ); + + // Interpolated tags + private static $interpolatedTags = array( + self::T_ESCAPED => true, + self::T_UNESCAPED => true, + self::T_UNESCAPED_2 => true, ); // Token properties - const NODES = 'nodes'; - const TAG = 'tag'; + const TYPE = 'type'; const NAME = 'name'; const OTAG = 'otag'; const CTAG = 'ctag'; const INDEX = 'index'; const END = 'end'; const INDENT = 'indent'; + const NODES = 'nodes'; private $state; private $tagType; @@ -104,14 +111,21 @@ class Tokenizer { break; case self::IN_TAG_TYPE: + $i += strlen($this->otag) - 1; - $tag = isset(self::$tagTypes[$text[$i + 1]]) ? self::$tagTypes[$text[$i + 1]] : null; - $this->tagType = $tag ? $text[$i + 1] : '_v'; - if ($this->tagType === '=') { + if (isset(self::$tagTypes[$text[$i + 1]])) { + $tag = $text[$i + 1]; + $this->tagType = $tag; + } else { + $tag = null; + $this->tagType = self::T_ESCAPED; + } + + if ($this->tagType === self::T_DELIM_CHANGE) { $i = $this->changeDelimiters($text, $i); $this->state = self::IN_TEXT; } else { - if ($tag) { + if ($tag !== null) { $i++; } $this->state = self::IN_TAG; @@ -122,21 +136,25 @@ class Tokenizer { default: if ($this->tagChange($this->ctag, $text, $i)) { $this->tokens[] = array( - self::TAG => $this->tagType, + self::TYPE => $this->tagType, self::NAME => trim($this->buffer), self::OTAG => $this->otag, self::CTAG => $this->ctag, - self::INDEX => ($this->tagType == '/') ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) + self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) ); $this->buffer = ''; $i += strlen($this->ctag) - 1; $this->state = self::IN_TEXT; - if ($this->tagType == '{') { + if ($this->tagType == self::T_UNESCAPED) { if ($this->ctag == '}}') { $i++; } else { - $this->cleanTripleStache($this->tokens[count($this->tokens) - 1]); + // Clean up `{{{ tripleStache }}}` style tokens. + $lastName = $this->tokens[count($this->tokens) - 1][self::NAME]; + if (substr($lastName, -1) === '}') { + $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1)); + } } } } else { @@ -185,8 +203,8 @@ class Tokenizer { $tokensCount = count($this->tokens); for ($j = $this->lineStart; $j < $tokensCount; $j++) { $token = $this->tokens[$j]; - if (is_array($token) && isset(self::$tagTypes[$token[self::TAG]])) { - if (self::$tagTypes[$token[self::TAG]] >= self::T_ESCAPED) { + if (is_array($token) && isset(self::$tagTypes[$token[self::TYPE]])) { + if (isset(self::$interpolatedTags[$token[self::TYPE]])) { return false; } } elseif (is_string($token)) { @@ -210,7 +228,7 @@ class Tokenizer { $tokensCount = count($this->tokens); for ($j = $this->lineStart; $j < $tokensCount; $j++) { if (!is_array($this->tokens[$j])) { - if (isset($this->tokens[$j+1]) && is_array($this->tokens[$j+1]) && $this->tokens[$j+1][self::TAG] == '>') { + if (isset($this->tokens[$j+1]) && is_array($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { $this->tokens[$j+1][self::INDENT] = (string) $this->tokens[$j]; } @@ -245,17 +263,6 @@ class Tokenizer { return $closeIndex + strlen($close) - 1; } - /** - * Clean up `{{{ tripleStache }}}` style tokens. - * - * @param array &$token - */ - private function cleanTripleStache(&$token) { - if (substr($token[self::NAME], -1) === '}') { - $token[self::NAME] = trim(substr($token[self::NAME], 0, -1)); - } - } - /** * Test whether it's time to change tags. * diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index 0a34a00..4afe7e4 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -50,11 +50,11 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { 'foo', "\n", array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name', ), array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => '.', ), "'bar'", @@ -79,6 +79,6 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { */ public function testCompilerThrowsUnknownNodeTypeException() { $compiler = new Compiler; - $compiler->compile('', array(array(Tokenizer::TAG => 'invalid')), 'SomeClass'); + $compiler->compile('', array(array(Tokenizer::TYPE => 'invalid')), 'SomeClass'); } } diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php index 17c2fb8..473a16a 100644 --- a/test/Mustache/Test/ParserTest.php +++ b/test/Mustache/Test/ParserTest.php @@ -43,11 +43,11 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array(array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name' )), array(array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name' )), ), @@ -56,31 +56,31 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( 'foo', array( - Tokenizer::TAG => '^', + Tokenizer::TYPE => Tokenizer::T_INVERTED, Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' + Tokenizer::NAME => 'parent' ), array( - Tokenizer::TAG => '_v', - Tokenizer::NAME => 'name' + Tokenizer::TYPE => Tokenizer::T_ESCAPED, + Tokenizer::NAME => 'name' ), array( - Tokenizer::TAG => '/', + Tokenizer::TYPE => Tokenizer::T_END_SECTION, Tokenizer::INDEX => 456, - Tokenizer::NAME => 'parent' + Tokenizer::NAME => 'parent' ), 'bar', ), array( 'foo', array( - Tokenizer::TAG => '^', - Tokenizer::NAME => 'parent', + Tokenizer::TYPE => Tokenizer::T_INVERTED, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::END => 456, + Tokenizer::END => 456, Tokenizer::NODES => array( array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name' ), ), @@ -107,9 +107,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TAG => '#', + Tokenizer::TYPE => Tokenizer::T_SECTION, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' ), ), ), @@ -118,9 +118,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TAG => '^', + Tokenizer::TYPE => Tokenizer::T_INVERTED, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' ), ), ), @@ -129,9 +129,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TAG => '/', + Tokenizer::TYPE => Tokenizer::T_END_SECTION, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' ), ), ), @@ -140,24 +140,24 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TAG => '#', + Tokenizer::TYPE => Tokenizer::T_SECTION, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' ), array( - Tokenizer::TAG => '#', + Tokenizer::TYPE => Tokenizer::T_SECTION, + Tokenizer::NAME => 'child', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'child' ), array( - Tokenizer::TAG => '/', + Tokenizer::TYPE => Tokenizer::T_END_SECTION, + Tokenizer::NAME => 'parent', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' ), array( - Tokenizer::TAG => '/', + Tokenizer::TYPE => Tokenizer::T_END_SECTION, + Tokenizer::NAME => 'child', Tokenizer::INDEX => 123, - Tokenizer::NAME => 'child' ), ), ), diff --git a/test/Mustache/Test/TokenizerTest.php b/test/Mustache/Test/TokenizerTest.php index 64c0250..6782a87 100644 --- a/test/Mustache/Test/TokenizerTest.php +++ b/test/Mustache/Test/TokenizerTest.php @@ -45,7 +45,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { null, array( array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name', Tokenizer::OTAG => '{{', Tokenizer::CTAG => '}}', @@ -65,7 +65,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { '<<< >>>', array( array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'name', Tokenizer::OTAG => '<<<', Tokenizer::CTAG => '>>>', @@ -79,7 +79,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { null, array( array( - Tokenizer::TAG => '{', + Tokenizer::TYPE => Tokenizer::T_UNESCAPED, Tokenizer::NAME => 'a', Tokenizer::OTAG => '{{', Tokenizer::CTAG => '}}', @@ -87,7 +87,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { ), "\n", array( - Tokenizer::TAG => '#', + Tokenizer::TYPE => Tokenizer::T_SECTION, Tokenizer::NAME => 'b', Tokenizer::OTAG => '{{', Tokenizer::CTAG => '}}', @@ -95,14 +95,14 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { ), null, array( - Tokenizer::TAG => '_v', + Tokenizer::TYPE => Tokenizer::T_ESCAPED, Tokenizer::NAME => 'c', Tokenizer::OTAG => '|', Tokenizer::CTAG => '|', Tokenizer::INDEX => 37, ), array( - Tokenizer::TAG => '/', + Tokenizer::TYPE => Tokenizer::T_END_SECTION, Tokenizer::NAME => 'b', Tokenizer::OTAG => '|', Tokenizer::CTAG => '|', @@ -110,7 +110,7 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { ), "\n", array( - Tokenizer::TAG => '{', + Tokenizer::TYPE => Tokenizer::T_UNESCAPED, Tokenizer::NAME => 'd', Tokenizer::OTAG => '|', Tokenizer::CTAG => '|', @@ -119,8 +119,6 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { ) ), - - ); } } From 628aa02f05df4c6b1a73be9169cc01432c528796 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 5 Mar 2012 17:56:43 -0800 Subject: [PATCH 15/58] Template sections as functions. This creates DRYer output and shallower nested blocks in compiled templates. --- src/Mustache/Compiler.php | 60 +++++++++++++++++++++++++-------------- 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 3c5b7ee..2cd469c 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -18,6 +18,9 @@ namespace Mustache; */ class Compiler { + private $sections; + private $source; + /** * Compile a Mustache token parse tree into PHP source code. * @@ -28,7 +31,8 @@ class Compiler { * @return string Generated PHP source code */ public function compile($source, array $tree, $name) { - $this->source = $source; + $this->sections = array(); + $this->source = $source; return $this->writeCode($tree, $name); } @@ -106,12 +110,12 @@ class Compiler { class %s extends \Mustache\Template { public function renderInternal(\Mustache\Context $context, $indent = \'\') { - $mustache = $this->mustache; - $buffer = new \Mustache\Buffer($indent, $mustache->getCharset()); + $buffer = new \Mustache\Buffer($indent, $this->mustache->getCharset()); %s return $buffer->flush(); } + %s }'; /** @@ -123,24 +127,32 @@ class Compiler { * @return string Generated PHP source code */ private function writeCode($tree, $name) { - return sprintf($this->prepare(self::KLASS, 0, false), $name, $this->walk($tree), $name); + $code = $this->walk($tree); + $sections = implode("\n", $this->sections); + + return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $sections); } - const SECTION = ' + const SECTION_CALL = ' // %s section - $value = $context->%s(%s); - if ($context->isCallable($value)) { - $source = %s; - $buffer->write( - $mustache - ->loadLambda((string) call_user_func($value, $source)%s) - ->renderInternal($context, $buffer->getIndent()) - ); - } elseif ($context->isTruthy($value)) { - $values = $context->isIterable($value) ? $value : array($value); - foreach ($values as $value) { - $context->push($value);%s - $context->pop(); + $this->section%s($buffer, $context, $context->%s(%s)); + '; + + const SECTION = ' + private function section%s(\Mustache\Buffer $buffer, \Mustache\Context $context, $value) { + if ($context->isCallable($value)) { + $source = %s; + $buffer->write( + $this->mustache + ->loadLambda((string) call_user_func($value, $source)%s) + ->renderInternal($context, $buffer->getIndent()) + ); + } elseif ($context->isTruthy($value)) { + $values = $context->isIterable($value) ? $value : array($value); + foreach ($values as $value) { + $context->push($value);%s + $context->pop(); + } } }'; @@ -168,7 +180,13 @@ class Compiler { $delims = ''; } - return sprintf($this->prepare(self::SECTION, $level), $id, $method, $id, $source, $delims, $this->walk($nodes, $level + 1)); + $key = ucfirst(md5($delims."\n".$source)); + + if (!isset($this->sections[$key])) { + $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $source, $delims, $this->walk($nodes, 2)); + } + + return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id); } const INVERTED_SECTION = ' @@ -193,7 +211,7 @@ class Compiler { return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); } - const PARTIAL = '$buffer->write($mustache->loadPartial(%s)->renderInternal($context, %s));'; + const PARTIAL = '$buffer->write($this->mustache->loadPartial(%s)->renderInternal($context, %s));'; /** * Generate Mustache Template partial call PHP source. @@ -215,7 +233,7 @@ class Compiler { const VARIABLE = ' $value = $context->%s(%s); if ($context->isCallable($value)) { - $value = $mustache + $value = $this->mustache ->loadLambda((string) call_user_func($value)) ->renderInternal($context, $buffer->getIndent()); } From cb24d63258a3b90a391fcfee5bdefa6576822905 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 7 Mar 2012 09:22:31 -0800 Subject: [PATCH 16/58] update README. simplify + link to wiki. --- README.markdown | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.markdown b/README.markdown index e586913..1a0f7d0 100644 --- a/README.markdown +++ b/README.markdown @@ -12,8 +12,7 @@ A quick example: ```php loadTemplate('Hello {{planet}}'); -echo $tpl->render(array('planet' => 'World!')); // "Hello World!" +echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!" ``` @@ -50,14 +49,14 @@ And render it: ```php loadTemplate($template); $chris = new Chris; -echo $template->render($chris); +echo $m->render($template, $chris); ``` See Also -------- + * [Mustache.php wiki](https://github.com/bobthecow/mustache.php/wiki/Home). * [Readme for the Ruby Mustache implementation](http://github.com/defunkt/mustache/blob/master/README.md). - * [mustache(1)](http://mustache.github.com/mustache.1.html) and [mustache(5)](http://mustache.github.com/mustache.5.html) man pages. + * [mustache(5)](http://mustache.github.com/mustache.5.html) man page. From b27705375aa3a1c68dd9f8aec012e2ed7527203e Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 7 Mar 2012 09:23:32 -0800 Subject: [PATCH 17/58] Syntax highlighting for mustache in README. --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 1a0f7d0..1bc9de8 100644 --- a/README.markdown +++ b/README.markdown @@ -18,7 +18,7 @@ echo $m->render('Hello {{planet}}', array('planet' => 'World!')); // "Hello Worl And a more in-depth example -- this is the canonical Mustache template: -``` +```html+jinja Hello {{name}} You have just won ${{value}}! {{#in_ca}} From 9a334cddf075b47ab2ed95fdaa21a04ed365fc62 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 13 Mar 2012 14:14:20 -0500 Subject: [PATCH 18/58] Inline `isCallable` and `isTruthy` into compiled templates ~3-5% performance gain. --- src/Mustache/Compiler.php | 9 +++--- src/Mustache/Context.php | 30 ------------------ test/Mustache/Test/ContextTest.php | 51 ------------------------------ 3 files changed, 5 insertions(+), 85 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 2cd469c..7213117 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -140,14 +140,14 @@ class Compiler { const SECTION = ' private function section%s(\Mustache\Buffer $buffer, \Mustache\Context $context, $value) { - if ($context->isCallable($value)) { + if (!is_string($value) && is_callable($value)) { $source = %s; $buffer->write( $this->mustache ->loadLambda((string) call_user_func($value, $source)%s) ->renderInternal($context, $buffer->getIndent()) ); - } elseif ($context->isTruthy($value)) { + } elseif (!empty($value)) { $values = $context->isIterable($value) ? $value : array($value); foreach ($values as $value) { $context->push($value);%s @@ -191,7 +191,8 @@ class Compiler { const INVERTED_SECTION = ' // %s inverted section - if (!$context->isTruthy($context->%s(%s))) { + $value = $context->%s(%s); + if (empty($value)) { %s }'; @@ -232,7 +233,7 @@ class Compiler { const VARIABLE = ' $value = $context->%s(%s); - if ($context->isCallable($value)) { + if (!is_string($value) && is_callable($value)) { $value = $this->mustache ->loadLambda((string) call_user_func($value)) ->renderInternal($context, $buffer->getIndent()); diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index 33f3409..d63fc2b 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -28,36 +28,6 @@ class Context { } } - /** - * Helper function to test whether a value is 'truthy'. - * - * @param mixed $value - * - * @return boolean True if the value is 'truthy' - */ - public function isTruthy($value) { - return !empty($value); - } - - /** - * Higher order sections helper: tests whether a value is a valid callback. - * - * In Mustache.php, a variable is considered 'callable' if the variable is: - * - * 1. An anonymous function. - * 2. An object and the name of a public function, e.g. `array($someObject, 'methodName')` - * 3. A class name and the name of a public static function, e.g. `array('SomeClass', 'methodName')` - * - * Note that this specifically excludes strings, which PHP would normally consider 'callable'. - * - * @param mixed $value - * - * @return boolean True if the value is 'callable' - */ - public function isCallable($value) { - return !is_string($value) && is_callable($value); - } - /** * Tests whether a value should be iterated over (e.g. in a section context). * diff --git a/test/Mustache/Test/ContextTest.php b/test/Mustache/Test/ContextTest.php index 07e9c11..c71cd53 100644 --- a/test/Mustache/Test/ContextTest.php +++ b/test/Mustache/Test/ContextTest.php @@ -36,57 +36,6 @@ class ContextTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('NAME', $three->find('name')); } - public function testIsTruthy() { - $context = new Context; - - $this->assertTrue($context->isTruthy('string')); - $this->assertTrue($context->isTruthy(new \StdClass)); - $this->assertTrue($context->isTruthy(1)); - $this->assertTrue($context->isTruthy(array('a', 'b'))); - - $this->assertFalse($context->isTruthy(null)); - $this->assertFalse($context->isTruthy('')); - $this->assertFalse($context->isTruthy(0)); - $this->assertFalse($context->isTruthy(array())); - } - - public function testIsCallable() { - $dummy = new TestDummy; - $context = new Context; - - $this->assertTrue($context->isCallable(function() { - return null; - })); - $this->assertTrue($context->isCallable(array('\Mustache\Test\TestDummy', 'foo'))); - $this->assertTrue($context->isCallable(array($dummy, 'bar'))); - $this->assertTrue($context->isCallable($dummy)); - - $this->assertFalse($context->isCallable('count')); - $this->assertFalse($context->isCallable('TestDummy::foo')); - $this->assertFalse($context->isCallable(array('\Mustache\Test\TestDummy', 'name'))); - $this->assertFalse($context->isCallable(array('NotReallyAClass', 'foo'))); - $this->assertFalse($context->isCallable(array($dummy, 'name'))); - } - - /** - * @dataProvider getIterables - */ - public function testIsIterable($value, $iterable) { - $context = new Context; - $this->assertEquals($iterable, $context->isIterable($value)); - } - - public function getIterables() { - return array( - array(array(0 => 'a', 1 => 'b'), true), - array(array(0 => 'a', 2 => 'b'), false), - array(array(1 => 'a', 2 => 'b'), false), - array(array('a' => 0, 'b' => 1), false), - array('some string', false), - array(new \ArrayIterator, true), - ); - } - public function testPushPopAndLast() { $context = new Context; $this->assertFalse($context->last()); From e09bfb502fe94adda374a4430e455a79ba9083f1 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 13 Mar 2012 14:17:13 -0500 Subject: [PATCH 19/58] Check if array is iterable without full key diff. ~0.5-1% performance gain. --- src/Mustache/Context.php | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index d63fc2b..1d8b44b 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -61,10 +61,17 @@ class Context { if (is_object($value)) { return $value instanceof \Traversable; } elseif (is_array($value)) { - return !array_diff_key($value, array_keys(array_keys($value))); - } + $i = 0; + foreach ($value as $k => $v) { + if ($k !== $i++) { + return false; + } + } - return false; + return true; + } else { + return false; + } } /** From 6ed1f68e68fecc0dae9383cdb1dbcb588b94103a Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 13 Mar 2012 14:20:07 -0500 Subject: [PATCH 20/58] `isIterable` fits better in Template than Context. --- src/Mustache/Compiler.php | 2 +- src/Mustache/Context.php | 46 -------------------------------------- src/Mustache/Template.php | 47 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 47 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 7213117..4817299 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -148,7 +148,7 @@ class Compiler { ->renderInternal($context, $buffer->getIndent()) ); } elseif (!empty($value)) { - $values = $context->isIterable($value) ? $value : array($value); + $values = $this->isIterable($value) ? $value : array($value); foreach ($values as $value) { $context->push($value);%s $context->pop(); diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index 1d8b44b..f069892 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -28,52 +28,6 @@ class Context { } } - /** - * Tests whether a value should be iterated over (e.g. in a section context). - * - * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists - * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, - * Java, Python, etc. - * - * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish - * between between a list of things (numeric, normalized array) and a set of variables to be used as section context - * (associative array). In other words, this will be iterated over: - * - * $items = array( - * array('name' => 'foo'), - * array('name' => 'bar'), - * array('name' => 'baz'), - * ); - * - * ... but this will be used as a section context block: - * - * $items = array( - * 1 => array('name' => 'foo'), - * 'banana' => array('name' => 'bar'), - * 42 => array('name' => 'baz'), - * ); - * - * @param mixed $value - * - * @return boolean True if the value is 'iterable' - */ - public function isIterable($value) { - if (is_object($value)) { - return $value instanceof \Traversable; - } elseif (is_array($value)) { - $i = 0; - foreach ($value as $k => $v) { - if ($k !== $i++) { - return false; - } - } - - return true; - } else { - return false; - } - } - /** * Push a new Context frame onto the stack. * diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 513edf6..c787e47 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -72,4 +72,51 @@ abstract class Template { * @return string Rendered template */ abstract public function renderInternal(Context $context); + + /** + * Tests whether a value should be iterated over (e.g. in a section context). + * + * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists + * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, + * Java, Python, etc. + * + * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish + * between between a list of things (numeric, normalized array) and a set of variables to be used as section context + * (associative array). In other words, this will be iterated over: + * + * $items = array( + * array('name' => 'foo'), + * array('name' => 'bar'), + * array('name' => 'baz'), + * ); + * + * ... but this will be used as a section context block: + * + * $items = array( + * 1 => array('name' => 'foo'), + * 'banana' => array('name' => 'bar'), + * 42 => array('name' => 'baz'), + * ); + * + * @param mixed $value + * + * @return boolean True if the value is 'iterable' + */ + protected function isIterable($value) { + if (is_object($value)) { + return $value instanceof \Traversable; + } elseif (is_array($value)) { + $i = 0; + foreach ($value as $k => $v) { + if ($k !== $i++) { + return false; + } + } + + return true; + } else { + return false; + } + } + } From 367013f01c8c936062684865a8f3c72d321fdb33 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 13 Mar 2012 23:45:33 -0700 Subject: [PATCH 21/58] 2x faster. Who needs a Buffer instance, anyway? --- src/Mustache/Buffer.php | 138 ---------------------------- src/Mustache/Compiler.php | 38 ++++---- src/Mustache/Template.php | 2 +- test/Mustache/Test/BufferTest.php | 99 -------------------- test/Mustache/Test/CompilerTest.php | 16 ++-- test/Mustache/Test/TemplateTest.php | 2 +- 6 files changed, 32 insertions(+), 263 deletions(-) delete mode 100644 src/Mustache/Buffer.php delete mode 100644 test/Mustache/Test/BufferTest.php diff --git a/src/Mustache/Buffer.php b/src/Mustache/Buffer.php deleted file mode 100644 index 7344b10..0000000 --- a/src/Mustache/Buffer.php +++ /dev/null @@ -1,138 +0,0 @@ -setIndent($indent); - } - - if ($charset !== null) { - $this->charset = $charset; - } - } - - /** - * Get the current indent level. - * - * @return string - */ - public function getIndent() { - return $this->indent; - } - - /** - * Set the buffer indent level. - * - * Each line output by this buffer will be prefixed by this whitespace. This is used when rendering - * partials and Lambda sections. - * - * @param string $indent - */ - public function setIndent($indent) { - $this->indent = $indent; - } - - /** - * Get the character set used when escaping values. - * - * @return string - */ - public function getCharset() { - return $this->charset; - } - - /** - * Write a newline to the Buffer. - */ - public function writeLine() { - $this->buffer .= "\n"; - } - - /** - * Output text to the Buffer. - * - * @see \Mustache\Buffer::write - * - * @param string $text - * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) - */ - public function writeText($text, $escape = false) { - $this->write($text, true, $escape); - } - - /** - * Add output to the Buffer. - * - * @param string $text - * @param bool $indent Indent this line? (default: false) - * @param bool $escape Escape this text with `htmlspecialchars()`? (default: false) - */ - public function write($text, $indent = false, $escape = false) { - $text = (string) $text; - - if ($escape) { - $text = $this->escape($text); - } - - if ($indent) { - $this->buffer .= $this->indent . $text; - } else { - $this->buffer .= $text; - } - } - - /** - * Flush the contents of the Buffer. - * - * Resets the buffer and returns the current contents. - * - * @return string - */ - public function flush() { - $buffer = $this->buffer; - $this->buffer = ''; - - return $buffer; - } - - /** - * Helper function to escape text. - * - * Uses the Buffer's character set (default 'UTF-8', passed as the second argument to `__construct`). - * - * @see htmlspecialchars - * - * @param string $text - * - * @return string Escaped text - */ - private function escape($text) { - return htmlspecialchars($text, ENT_COMPAT, $this->charset); - } -} diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 4817299..bfe53f7 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -109,11 +109,15 @@ class Compiler { const KLASS = 'mustache->getCharset()); + public function renderInternal(\Mustache\Context $context, $indent = \'\', $escape = false) { + $buffer = \'\'; %s - return $buffer->flush(); + if ($escape) { + return htmlspecialchars($buffer, ENT_COMPAT, $this->mustache->getCharset()); + } + + return $buffer; } %s }'; @@ -135,18 +139,17 @@ class Compiler { const SECTION_CALL = ' // %s section - $this->section%s($buffer, $context, $context->%s(%s)); + $buffer .= $this->section%s($context, $indent, $context->%s(%s)); '; const SECTION = ' - private function section%s(\Mustache\Buffer $buffer, \Mustache\Context $context, $value) { + private function section%s(\Mustache\Context $context, $indent, $value) { + $buffer = \'\'; if (!is_string($value) && is_callable($value)) { $source = %s; - $buffer->write( - $this->mustache - ->loadLambda((string) call_user_func($value, $source)%s) - ->renderInternal($context, $buffer->getIndent()) - ); + $buffer .= $this->mustache + ->loadLambda((string) call_user_func($value, $source)%s) + ->renderInternal($context, $indent); } elseif (!empty($value)) { $values = $this->isIterable($value) ? $value : array($value); foreach ($values as $value) { @@ -154,6 +157,8 @@ class Compiler { $context->pop(); } } + + return $buffer; }'; /** @@ -212,7 +217,7 @@ class Compiler { return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); } - const PARTIAL = '$buffer->write($this->mustache->loadPartial(%s)->renderInternal($context, %s));'; + const PARTIAL = '$buffer .= $this->mustache->loadPartial(%s)->renderInternal($context, %s);'; /** * Generate Mustache Template partial call PHP source. @@ -236,10 +241,11 @@ class Compiler { if (!is_string($value) && is_callable($value)) { $value = $this->mustache ->loadLambda((string) call_user_func($value)) - ->renderInternal($context, $buffer->getIndent()); + ->renderInternal($context, $indent); } - $buffer->writeText($value, %s); + $buffer .= $indent . %s; '; + const VARIABLE_ESCAPED = 'htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset())'; /** * Generate Mustache Template variable interpolation PHP source. @@ -253,13 +259,13 @@ class Compiler { private function variable($id, $escape, $level) { $method = $this->getFindMethod($id); $id = ($method !== 'last') ? var_export($id, true) : ''; - $escape = $escape ? 'true' : 'false'; + $escape = $escape ? self::VARIABLE_ESCAPED : '$value'; return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $escape); } - const LINE = '$buffer->writeLine();'; - const TEXT = '$buffer->writeText(%s);'; + const LINE = '$buffer .= "\n";'; + const TEXT = '$buffer .= $indent . %s;'; /** * Generate Mustache Template output Buffer call PHP source. diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index c787e47..b3286f8 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -71,7 +71,7 @@ abstract class Template { * * @return string Rendered template */ - abstract public function renderInternal(Context $context); + abstract public function renderInternal(Context $context, $indent = '', $escape = false); /** * Tests whether a value should be iterated over (e.g. in a section context). diff --git a/test/Mustache/Test/BufferTest.php b/test/Mustache/Test/BufferTest.php deleted file mode 100644 index 23feca4..0000000 --- a/test/Mustache/Test/BufferTest.php +++ /dev/null @@ -1,99 +0,0 @@ -assertEquals($indent, $buffer->getIndent()); - $this->assertEquals($charset, $buffer->getCharset()); - } - - public function getConstructorArgs() { - return array( - array('', 'UTF-8'), - array(' ', 'ISO-8859-1'), - array("\t\t\t", 'Shift_JIS'), - ); - } - - public function testWrite() { - $buffer = new Buffer; - $this->assertEquals('', $buffer->flush()); - - $buffer->writeLine(); - $buffer->writeLine(); - $buffer->writeLine(); - $this->assertEquals("\n\n\n", $buffer->flush()); - $this->assertEquals('', $buffer->flush()); - - $buffer->write('foo'); - $buffer->write('bar'); - $buffer->writeLine(); - $buffer->write('baz'); - $this->assertEquals("foobar\nbaz", $buffer->flush()); - $this->assertEquals('', $buffer->flush()); - - $indent = "\t\t"; - $buffer->setIndent($indent); - $buffer->writeText('foo'); - $buffer->writeLine(); - $buffer->writeText('bar'); - $this->assertEquals("\t\tfoo\n\t\tbar", $buffer->flush()); - $this->assertEquals('', $buffer->flush()); - } - - /** - * @dataProvider getEscapeAndIndent - */ - public function testEscapingAndIndenting($text, $escape, $indent, $whitespace, $expected) { - $buffer = new Buffer; - $buffer->setIndent($whitespace); - - $buffer->write($text, $indent, $escape); - $this->assertEquals($expected, $buffer->flush()); - } - - public function getEscapeAndIndent() { - return array( - array('> "fun & games" <', false, false, "\t", '> "fun & games" <'), - array('> "fun & games" <', true, false, "\t", '> "fun & games" <'), - array('> "fun & games" <', true, true, "\t", "\t> "fun & games" <"), - array('> "fun & games" <', false, true, "\t", "\t> \"fun & games\" <"), - ); - } - - public function testChangeIndent() { - $indent = "\t\t"; - $buffer = new Buffer($indent); - $this->assertEquals($indent, $buffer->getIndent()); - - $indent = ""; - $buffer->setIndent($indent); - $this->assertEquals($indent, $buffer->getIndent()); - - $indent = " "; - $buffer->setIndent($indent); - $this->assertEquals($indent, $buffer->getIndent()); - } - -} diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index 4afe7e4..e08fa45 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -35,13 +35,13 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { return array( array('', array(), 'Banana', array( "\nclass Banana extends \Mustache\Template", - '$buffer->flush();', + 'return $buffer;', )), array('', array('TEXT'), 'Monkey', array( "\nclass Monkey extends \Mustache\Template", - '$buffer->writeText(\'TEXT\');', - '$buffer->flush();', + '$buffer .= $indent . \'TEXT\';', + 'return $buffer;', )), array( @@ -62,13 +62,13 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { 'Monkey', array( "\nclass Monkey extends \Mustache\Template", - '$buffer->writeText(\'foo\');', - '$buffer->writeLine();', + '$buffer .= $indent . \'foo\'', + '$buffer .= "\n"', '$value = $context->find(\'name\');', - '$buffer->writeText($value, true);', + '$buffer .= $indent . htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset());', '$value = $context->last();', - '$buffer->writeText(\'\\\'bar\\\'\');', - '$buffer->flush();', + '$buffer .= $indent . \'\\\'bar\\\'\';', + 'return $buffer;', ) ), ); diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php index 42ad2c5..8b24267 100644 --- a/test/Mustache/Test/TemplateTest.php +++ b/test/Mustache/Test/TemplateTest.php @@ -46,7 +46,7 @@ class TemplateStub extends Template { return $this->mustache; } - public function renderInternal(Context $context) { + public function renderInternal(Context $context, $indent = '', $escape = false) { return $this->rendered; } } From fe9fccb44162b302226bc70dd4aadbb1a1728ca8 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 14 Mar 2012 13:20:30 -0700 Subject: [PATCH 22/58] Update the `partials` example to be a failing test case for partial indenting. --- examples/partials/Partials.php | 8 ++++---- examples/partials/partials.mustache | 9 +++++++-- examples/partials/partials.txt | 11 ++++++++--- examples/partials/partials/children.mustache | 2 -- examples/partials/partials/header.mustache | 4 ++++ 5 files changed, 23 insertions(+), 11 deletions(-) delete mode 100644 examples/partials/partials/children.mustache create mode 100644 examples/partials/partials/header.mustache diff --git a/examples/partials/Partials.php b/examples/partials/Partials.php index 19f627a..f15d6b2 100644 --- a/examples/partials/Partials.php +++ b/examples/partials/Partials.php @@ -1,9 +1,9 @@ 'federica', 'age' => 27, 'gender' => 'female'), - array('name' => 'marco', 'age' => 32, 'gender' => 'male'), + public $page = array( + 'title' => 'Page Title', + 'subtitle' => 'Page Subtitle', + 'content' => 'Lorem ipsum dolor sit amet.', ); } diff --git a/examples/partials/partials.mustache b/examples/partials/partials.mustache index 037e1b3..54cf1c5 100644 --- a/examples/partials/partials.mustache +++ b/examples/partials/partials.mustache @@ -1,2 +1,7 @@ -Children of {{name}}: -{{>children}} \ No newline at end of file +
+ {{> header }} + +
+ {{ page.content }} +
+
\ No newline at end of file diff --git a/examples/partials/partials.txt b/examples/partials/partials.txt index d967e15..f8e45ce 100644 --- a/examples/partials/partials.txt +++ b/examples/partials/partials.txt @@ -1,3 +1,8 @@ -Children of ilmich: -federica - 27 - female -marco - 32 - male +
+

Page Title

+

Page Subtitle

+ +
+ Lorem ipsum dolor sit amet. +
+
\ No newline at end of file diff --git a/examples/partials/partials/children.mustache b/examples/partials/partials/children.mustache deleted file mode 100644 index 9506a28..0000000 --- a/examples/partials/partials/children.mustache +++ /dev/null @@ -1,2 +0,0 @@ -{{#data}}{{name}} - {{age}} - {{gender}} -{{/data}} \ No newline at end of file diff --git a/examples/partials/partials/header.mustache b/examples/partials/partials/header.mustache new file mode 100644 index 0000000..88d567b --- /dev/null +++ b/examples/partials/partials/header.mustache @@ -0,0 +1,4 @@ +{{# page }} +

{{ title }}

+

{{ subtitle }}

+{{/ page }} \ No newline at end of file From 50b359445849c52fd9e02a884c04b765042bd0ea Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 14 Mar 2012 17:41:38 -0700 Subject: [PATCH 23/58] Fix failing `partials` example. Only prepend $indent to the first output on a new line. --- src/Mustache/Compiler.php | 35 +++++++++++++++++++++++------ test/Mustache/Test/CompilerTest.php | 4 ++-- 2 files changed, 30 insertions(+), 9 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index bfe53f7..daebe2e 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -20,6 +20,7 @@ class Compiler { private $sections; private $source; + private $indentNextLine; /** * Compile a Mustache token parse tree into PHP source code. @@ -31,8 +32,9 @@ class Compiler { * @return string Generated PHP source code */ public function compile($source, array $tree, $name) { - $this->sections = array(); - $this->source = $source; + $this->sections = array(); + $this->source = $source; + $this->indentNextLine = true; return $this->writeCode($tree, $name); } @@ -243,7 +245,7 @@ class Compiler { ->loadLambda((string) call_user_func($value)) ->renderInternal($context, $indent); } - $buffer .= $indent . %s; + $buffer .= %s%s; '; const VARIABLE_ESCAPED = 'htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset())'; @@ -259,13 +261,13 @@ class Compiler { private function variable($id, $escape, $level) { $method = $this->getFindMethod($id); $id = ($method !== 'last') ? var_export($id, true) : ''; - $escape = $escape ? self::VARIABLE_ESCAPED : '$value'; + $value = $escape ? self::VARIABLE_ESCAPED : '$value'; - return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $escape); + return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $this->flushIndent(), $value); } const LINE = '$buffer .= "\n";'; - const TEXT = '$buffer .= $indent . %s;'; + const TEXT = '$buffer .= %s%s;'; /** * Generate Mustache Template output Buffer call PHP source. @@ -277,9 +279,11 @@ class Compiler { */ private function text($text, $level) { if ($text === "\n") { + $this->indentNextLine = true; + return $this->prepare(self::LINE, $level); } else { - return sprintf($this->prepare(self::TEXT, $level), var_export($text, true)); + return sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true)); } } @@ -323,4 +327,21 @@ class Compiler { return 'findDot'; } } + + const LINE_INDENT = '$indent . '; + + /** + * Get the current $indent prefix to write to the buffer. + * + * @return string "$indent . " or "" + */ + private function flushIndent() { + if ($this->indentNextLine) { + $this->indentNextLine = false; + + return self::LINE_INDENT; + } else { + return ''; + } + } } diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index e08fa45..b53879b 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -65,9 +65,9 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { '$buffer .= $indent . \'foo\'', '$buffer .= "\n"', '$value = $context->find(\'name\');', - '$buffer .= $indent . htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset());', + '$buffer .= htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset());', '$value = $context->last();', - '$buffer .= $indent . \'\\\'bar\\\'\';', + '$buffer .= \'\\\'bar\\\'\';', 'return $buffer;', ) ), From ba75d746e17719fcdd901b192bc345de39814f8b Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 1 Mar 2012 05:24:50 -0800 Subject: [PATCH 24/58] Add Helper implementation. --- src/Mustache/HelperCollection.php | 158 ++++++++++++++++++++ src/Mustache/Mustache.php | 99 ++++++++++++ src/Mustache/Template.php | 25 +++- test/Mustache/Test/HelperCollectionTest.php | 156 +++++++++++++++++++ test/Mustache/Test/MustacheTest.php | 50 +++++++ 5 files changed, 487 insertions(+), 1 deletion(-) create mode 100644 src/Mustache/HelperCollection.php create mode 100644 test/Mustache/Test/HelperCollectionTest.php diff --git a/src/Mustache/HelperCollection.php b/src/Mustache/HelperCollection.php new file mode 100644 index 0000000..047fe5f --- /dev/null +++ b/src/Mustache/HelperCollection.php @@ -0,0 +1,158 @@ + $helper` pairs. + * + * @throws \InvalidArgumentException if the $helpers argument isn't an array or \Traversable + * + * @param array|Traversable $helpers (default: null) + */ + public function __construct($helpers = null) { + if ($helpers !== null) { + if (!is_array($helpers) && !$helpers instanceof \Traversable) { + throw new \InvalidArgumentException('HelperCollection constructor expects an array of helpers'); + } + + foreach ($helpers as $name => $helper) { + $this->add($name, $helper); + } + } + } + + /** + * Magic mutator. + * + * @see \Mustache\HelperCollection::add + * + * @param string $name + * @param mixed $helper + */ + public function __set($name, $helper) { + $this->add($name, $helper); + } + + /** + * Add a helper to this collection. + * + * @param string $name + * @param mixed $helper + */ + public function add($name, $helper) { + $this->helpers[$name] = $helper; + } + + /** + * Magic accessor. + * + * @see \Mustache\HelperCollection::get + * + * @param string $name + * + * @return mixed Helper + */ + public function __get($name) { + return $this->get($name); + } + + /** + * Get a helper by name. + * + * @param string $name + * + * @return mixed Helper + */ + public function get($name) { + if (!$this->has($name)) { + throw new \InvalidArgumentException('Unknown helper: '.$name); + } + + return $this->helpers[$name]; + } + + /** + * Magic isset(). + * + * @see \Mustache\HelperCollection::has + * + * @param string $name + * + * @return boolean True if helper is present + */ + public function __isset($name) { + return $this->has($name); + } + + /** + * Check whether a given helper is present in the collection. + * + * @param string $name + * + * @return boolean True if helper is present + */ + public function has($name) { + return array_key_exists($name, $this->helpers); + } + + /** + * Magic unset(). + * + * @see \Mustache\HelperCollection::remove + * + * @param string $name + */ + public function __unset($name) { + $this->remove($name); + } + + /** + * Check whether a given helper is present in the collection. + * + * @throws \InvalidArgumentException if the requested helper is not present. + * + * @param string $name + */ + public function remove($name) { + if (!$this->has($name)) { + throw new \InvalidArgumentException('Unknown helper: '.$name); + } + + unset($this->helpers[$name]); + } + + /** + * Clear the helper collection. + * + * Removes all helpers from this collection + */ + public function clear() { + $this->helpers = array(); + } + + /** + * Check whether the helper collection is empty. + * + * @return boolean True if the collection is empty + */ + public function isEmpty() { + return empty($this->helpers); + } +} diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 8975907..68ecd2a 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -39,6 +39,7 @@ class Mustache { private $cache = null; private $loader; private $partialsLoader; + private $helpers; private $charset = 'UTF-8'; /** @@ -63,6 +64,13 @@ class Mustache { * // efficient or lazy as a Filesystem (or database) loader. * 'partials' => array('foo' => file_get_contents(__DIR__.'/views/partials/foo.mustache')), * + * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order + * // sections), or any other valid Mustache context value. They will be prepended to the context stack, + * // so they will be available in any template loaded by this Mustache instance. + * 'helpers' => array('i18n' => function($text) { + * // do something translatey here... + * }), + * * // character set for `htmlspecialchars`. Defaults to 'UTF-8' * 'charset' => 'ISO-8859-1', * ); @@ -90,6 +98,10 @@ class Mustache { $this->setPartials($options['partials']); } + if (isset($options['helpers'])) { + $this->setHelpers($options['helpers']); + } + if (isset($options['charset'])) { $this->charset = $options['charset']; } @@ -187,6 +199,93 @@ class Mustache { $loader->setTemplates($partials); } + /** + * Set an array of Mustache helpers. + * + * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or + * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in + * any template loaded by this Mustache instance. + * + * @throws \InvalidArgumentException if $helpers is not an array or \Traversable + * + * @param array|Traversable $helpers + */ + public function setHelpers($helpers) { + if (!is_array($helpers) && !$helpers instanceof \Traversable) { + throw new \InvalidArgumentException('setHelpers expects an array of helpers'); + } + + $this->getHelpers()->clear(); + + foreach ($helpers as $name => $helper) { + $this->addHelper($name, $helper); + } + } + + /** + * Get the current set of Mustache helpers. + * + * @see \Mustache\Mustache::setHelpers + * + * @return \Mustache\HelperCollection + */ + public function getHelpers() { + if (!isset($this->helpers)) { + $this->helpers = new HelperCollection; + } + + return $this->helpers; + } + + /** + * Add a new Mustache helper. + * + * @see \Mustache\Mustache::setHelpers + * + * @param string $name + * @param mixed $helper + */ + public function addHelper($name, $helper) { + $this->getHelpers()->add($name, $helper); + } + + /** + * Get a Mustache helper by name. + * + * @see \Mustache\Mustache::setHelpers + * + * @param string $name + * + * @return mixed Helper + */ + public function getHelper($name) { + return $this->getHelpers()->get($name); + } + + /** + * Check whether this Mustache instance has a helper. + * + * @see \Mustache\Mustache::setHelpers + * + * @param string $name + * + * @return boolean True if the helper is present + */ + public function hasHelper($name) { + return $this->getHelpers()->has($name); + } + + /** + * Remove a helper by name. + * + * @see \Mustache\Mustache::setHelpers + * + * @param string $name + */ + public function removeHelper($name) { + $this->getHelpers()->remove($name); + } + /** * Set the Mustache Tokenizer instance. * diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index b3286f8..0fa2db6 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -57,7 +57,7 @@ abstract class Template { * @return string Rendered template */ public function render($context = array()) { - return $this->renderInternal(new Context($context)); + return $this->renderInternal($this->prepareContextStack($context)); } /** @@ -119,4 +119,27 @@ abstract class Template { } } + /** + * Helper method to prepare the Context stack. + * + * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present. + * + * @param mixed $context Optional first context frame (default: null) + * + * @return \Mustache\Context + */ + protected function prepareContextStack($context = null) { + $stack = new Context; + + $helpers = $this->mustache->getHelpers(); + if (!$helpers->isEmpty()) { + $stack->push($helpers); + } + + if (!empty($context)) { + $stack->push($context); + } + + return $stack; + } } diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php new file mode 100644 index 0000000..12e48dd --- /dev/null +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -0,0 +1,156 @@ + $foo, + 'bar' => $bar, + )); + + $this->assertSame($foo, $helpers->get('foo')); + $this->assertSame($bar, $helpers->get('bar')); + } + + public function testAccessorsAndMutators() { + $foo = function() { echo 'foo'; }; + $bar = 'BAR'; + + $helpers = new HelperCollection; + $this->assertTrue($helpers->isEmpty()); + $this->assertFalse($helpers->has('foo')); + $this->assertFalse($helpers->has('bar')); + + $helpers->add('foo', $foo); + $this->assertFalse($helpers->isEmpty()); + $this->assertTrue($helpers->has('foo')); + $this->assertFalse($helpers->has('bar')); + + $helpers->add('bar', $bar); + $this->assertFalse($helpers->isEmpty()); + $this->assertTrue($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + + $helpers->remove('foo'); + $this->assertFalse($helpers->isEmpty()); + $this->assertFalse($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + } + + public function testMagicMethods() { + $foo = function() { echo 'foo'; }; + $bar = 'BAR'; + + $helpers = new HelperCollection; + $this->assertTrue($helpers->isEmpty()); + $this->assertFalse($helpers->has('foo')); + $this->assertFalse($helpers->has('bar')); + $this->assertFalse(isset($helpers->foo)); + $this->assertFalse(isset($helpers->bar)); + + $helpers->foo = $foo; + $this->assertFalse($helpers->isEmpty()); + $this->assertTrue($helpers->has('foo')); + $this->assertFalse($helpers->has('bar')); + $this->assertTrue(isset($helpers->foo)); + $this->assertFalse(isset($helpers->bar)); + + $helpers->bar = $bar; + $this->assertFalse($helpers->isEmpty()); + $this->assertTrue($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + $this->assertTrue(isset($helpers->foo)); + $this->assertTrue(isset($helpers->bar)); + + unset($helpers->foo); + $this->assertFalse($helpers->isEmpty()); + $this->assertFalse($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + $this->assertFalse(isset($helpers->foo)); + $this->assertTrue(isset($helpers->bar)); + } + + /** + * @dataProvider getInvalidHelperArguments + */ + public function testHelperCollectionIsntAfraidToThrowExceptions($helpers = array(), $actions = array(), $exception = null) { + if ($exception) { + $this->setExpectedException($exception); + } + + $helpers = new HelperCollection($helpers); + + foreach ($actions as $method => $args) { + call_user_func_array(array($helpers, $method), $args); + } + } + + public function getInvalidHelperArguments() { + return array( + array( + 'not helpers', + array(), + '\InvalidArgumentException', + ), + array( + array(), + array('get' => array('foo')), + '\InvalidArgumentException', + ), + array( + array('foo' => 'FOO'), + array('get' => array('foo')), + null, + ), + array( + array('foo' => 'FOO'), + array('get' => array('bar')), + '\InvalidArgumentException', + ), + array( + array('foo' => 'FOO'), + array( + 'add' => array('bar', 'BAR'), + 'get' => array('bar'), + ), + null, + ), + array( + array('foo' => 'FOO'), + array( + 'get' => array('foo'), + 'remove' => array('foo'), + ), + null, + ), + array( + array('foo' => 'FOO'), + array( + 'remove' => array('foo'), + 'get' => array('foo'), + ), + '\InvalidArgumentException', + ), + array( + array(), + array('remove' => array('foo')), + '\InvalidArgumentException', + ), + ); + } +} diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 88f9a03..4180bee 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -43,6 +43,10 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { 'partials' => array( 'foo' => '{{ foo }}', ), + 'helpers' => array( + 'foo' => function() { return 'foo'; }, + 'bar' => 'BAR', + ), 'charset' => 'ISO-8859-1', )); @@ -51,6 +55,9 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $this->assertEquals('{{ foo }}', $partialsLoader->load('foo')); $this->assertContains('__whot__', $mustache->getTemplateClassName('{{ foo }}')); $this->assertEquals('ISO-8859-1', $mustache->getCharset()); + $this->assertTrue($mustache->hasHelper('foo')); + $this->assertTrue($mustache->hasHelper('bar')); + $this->assertFalse($mustache->hasHelper('baz')); } public function testRender() { @@ -144,6 +151,49 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $mustache->setPartials(array('foo' => '{{ foo }}')); } + public function testHelpers() { + $foo = function() { return 'foo'; }; + $bar = 'BAR'; + $mustache = new Mustache(array('helpers' => array( + 'foo' => $foo, + 'bar' => $bar, + ))); + + $helpers = $mustache->getHelpers(); + $this->assertTrue($mustache->hasHelper('foo')); + $this->assertTrue($mustache->hasHelper('bar')); + $this->assertTrue($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + $this->assertSame($foo, $mustache->getHelper('foo')); + $this->assertSame($bar, $mustache->getHelper('bar')); + + $mustache->removeHelper('bar'); + $this->assertFalse($mustache->hasHelper('bar')); + $mustache->addHelper('bar', $bar); + $this->assertSame($bar, $mustache->getHelper('bar')); + + $baz = function($text) { return '__'.$text.'__'; }; + $this->assertFalse($mustache->hasHelper('baz')); + $this->assertFalse($helpers->has('baz')); + + $mustache->addHelper('baz', $baz); + $this->assertTrue($mustache->hasHelper('baz')); + $this->assertTrue($helpers->has('baz')); + + // ... and a functional test + $tpl = $mustache->loadTemplate('{{foo}} - {{bar}} - {{#baz}}qux{{/baz}}'); + $this->assertEquals('foo - BAR - __qux__', $tpl->render()); + $this->assertEquals('foo - BAR - __qux__', $tpl->render(array('qux' => "won't mess things up"))); + } + + /** + * @expectedException \InvalidArgumentException + */ + public function testSetHelpersThrowsExceptions() { + $mustache = new Mustache; + $mustache->setHelpers('monkeymonkeymonkey'); + } + private static function rmdir($path) { $path = rtrim($path, '/').'/'; $handle = opendir($path); From 23a4bb04f28778174ba4102b59f7b59caf86ebc5 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 14 Mar 2012 19:48:19 -0700 Subject: [PATCH 25/58] Add custom variable escapers. cf. #86 * Add `escape` Mustache constructor option. Expects something callable. * Update Compiler to either inline `htmlspecialchars` (old way) or a call to the custom escaper callback. * Update Compiler to statically compile charset. * Update template classname to account for charset and custom compilers. --- src/Mustache/Compiler.php | 33 ++++++++++++++++++++------ src/Mustache/Mustache.php | 36 +++++++++++++++++++++++++++-- test/Mustache/Test/CompilerTest.php | 22 ++++++++++++++---- test/Mustache/Test/MustacheTest.php | 17 ++++++++++++++ 4 files changed, 94 insertions(+), 14 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index daebe2e..f8c8494 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -21,6 +21,8 @@ class Compiler { private $sections; private $source; private $indentNextLine; + private $customEscape; + private $charset; /** * Compile a Mustache token parse tree into PHP source code. @@ -31,10 +33,12 @@ class Compiler { * * @return string Generated PHP source code */ - public function compile($source, array $tree, $name) { + public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8') { $this->sections = array(); $this->source = $source; $this->indentNextLine = true; + $this->customEscape = $customEscape; + $this->charset = $charset; return $this->writeCode($tree, $name); } @@ -116,10 +120,10 @@ class Compiler { %s if ($escape) { - return htmlspecialchars($buffer, ENT_COMPAT, $this->mustache->getCharset()); + return %s; + } else { + return $buffer; } - - return $buffer; } %s }'; @@ -136,7 +140,7 @@ class Compiler { $code = $this->walk($tree); $sections = implode("\n", $this->sections); - return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $sections); + return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $this->getEscape('$buffer'), $sections); } const SECTION_CALL = ' @@ -247,7 +251,6 @@ class Compiler { } $buffer .= %s%s; '; - const VARIABLE_ESCAPED = 'htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset())'; /** * Generate Mustache Template variable interpolation PHP source. @@ -261,7 +264,7 @@ class Compiler { private function variable($id, $escape, $level) { $method = $this->getFindMethod($id); $id = ($method !== 'last') ? var_export($id, true) : ''; - $value = $escape ? self::VARIABLE_ESCAPED : '$value'; + $value = $escape ? $this->getEscape() : '$value'; return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $this->flushIndent(), $value); } @@ -305,6 +308,22 @@ class Compiler { return preg_replace("/\n(\t\t)?/", "\n".str_repeat("\t", $bonus), $text); } + const DEFAULT_ESCAPE = 'htmlspecialchars(%s, ENT_COMPAT, %s)'; + const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)'; + + /** + * Get the current escaper. + * + * @return string Either a custom callback, or an inline call to `htmlspecialchars` + */ + private function getEscape($value = '$value') { + if ($this->customEscape) { + return sprintf(self::CUSTOM_ESCAPE, $value); + } else { + return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->charset, true)); + } + } + /** * Select the appropriate Context `find` method for a given $id. * diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 68ecd2a..7a8e61e 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -40,6 +40,7 @@ class Mustache { private $loader; private $partialsLoader; private $helpers; + private $escape; private $charset = 'UTF-8'; /** @@ -71,6 +72,11 @@ class Mustache { * // do something translatey here... * }), * + * // An 'escape' callback, responsible for escaping double-mustache variables. + * 'escape' => function($value) { + * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8'); + * }, + * * // character set for `htmlspecialchars`. Defaults to 'UTF-8' * 'charset' => 'ISO-8859-1', * ); @@ -102,6 +108,14 @@ class Mustache { $this->setHelpers($options['helpers']); } + if (isset($options['escape'])) { + if (!is_callable($options['escape'])) { + throw new \InvalidArgumentException('Mustache Constructor "escape" option must be callable'); + } + + $this->escape = $options['escape']; + } + if (isset($options['charset'])) { $this->charset = $options['charset']; } @@ -124,6 +138,15 @@ class Mustache { return $this->loadTemplate($template)->render($data); } + /** + * Get the current Mustache escape callback. + * + * @return mixed Callable or null + */ + public function getEscape() { + return $this->escape; + } + /** * Get the current Mustache character set. * @@ -366,7 +389,13 @@ class Mustache { * @return string Mustache Template class name */ public function getTemplateClassName($source) { - return $this->templateClassPrefix . md5(self::VERSION . ':' . $source); + return $this->templateClassPrefix . md5(sprintf( + 'version:%s,escape:%s,charset:%s,source:%s', + self::VERSION, + isset($this->escape) ? 'custom' : 'default', + $this->charset, + $source + )); } /** @@ -482,7 +511,10 @@ class Mustache { * @return string generated Mustache template class code */ private function compile($source) { - return $this->getCompiler()->compile($source, $this->parse($source), $this->getTemplateClassName($source)); + $tree = $this->parse($source); + $name = $this->getTemplateClassName($source); + + return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset); } /** diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index b53879b..266b4cf 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -22,10 +22,10 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getCompileValues */ - public function testCompile($source, array $tree, $name, $expected) { + public function testCompile($source, array $tree, $name, $customEscaper, $charset, $expected) { $compiler = new Compiler; - $compiled = $compiler->compile($source, $tree, $name); + $compiled = $compiler->compile($source, $tree, $name, $customEscaper, $charset); foreach ($expected as $contains) { $this->assertContains($contains, $compiled); } @@ -33,14 +33,23 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { public function getCompileValues() { return array( - array('', array(), 'Banana', array( + array('', array(), 'Banana', false, 'ISO-8859-1', array( "\nclass Banana extends \Mustache\Template", + 'return htmlspecialchars($buffer, ENT_COMPAT, \'ISO-8859-1\');', 'return $buffer;', )), - array('', array('TEXT'), 'Monkey', array( + array('', array('TEXT'), 'Monkey', false, 'UTF-8', array( + "\nclass Monkey extends \Mustache\Template", + 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', + '$buffer .= $indent . \'TEXT\';', + 'return $buffer;', + )), + + array('', array('TEXT'), 'Monkey', true, 'ISO-8859-1', array( "\nclass Monkey extends \Mustache\Template", '$buffer .= $indent . \'TEXT\';', + 'return call_user_func($this->mustache->getEscape(), $buffer);', 'return $buffer;', )), @@ -60,14 +69,17 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { "'bar'", ), 'Monkey', + false, + 'UTF-8', array( "\nclass Monkey extends \Mustache\Template", '$buffer .= $indent . \'foo\'', '$buffer .= "\n"', '$value = $context->find(\'name\');', - '$buffer .= htmlspecialchars($value, ENT_COMPAT, $this->mustache->getCharset());', + '$buffer .= htmlspecialchars($value, ENT_COMPAT, \'UTF-8\');', '$value = $context->last();', '$buffer .= \'\\\'bar\\\'\';', + 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', 'return $buffer;', ) ), diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 4180bee..53d804f 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -47,6 +47,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { 'foo' => function() { return 'foo'; }, 'bar' => 'BAR', ), + 'escape' => 'strtoupper', 'charset' => 'ISO-8859-1', )); @@ -54,6 +55,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $this->assertSame($partialsLoader, $mustache->getPartialsLoader()); $this->assertEquals('{{ foo }}', $partialsLoader->load('foo')); $this->assertContains('__whot__', $mustache->getTemplateClassName('{{ foo }}')); + $this->assertEquals('strtoupper', $mustache->getEscape()); $this->assertEquals('ISO-8859-1', $mustache->getCharset()); $this->assertTrue($mustache->hasHelper('foo')); $this->assertTrue($mustache->hasHelper('bar')); @@ -127,6 +129,21 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $this->assertContains("\nclass $className extends \Mustache\Template", file_get_contents($fileName)); } + /** + * @expectedException \InvalidArgumentException + * @dataProvider getBadEscapers + */ + public function testNonCallableEscapeThrowsException($escape) { + new Mustache(array('escape' => $escape)); + } + + public function getBadEscapers() { + return array( + array('nothing'), + array('foo', 'bar'), + ); + } + /** * @group functional * @expectedException \RuntimeException From 99ff7316b3398d9a9b359df3186c20a69a57e305 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 17 Mar 2012 22:57:56 -0700 Subject: [PATCH 26/58] Add composer.json --- .gitignore | 1 + composer.json | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) create mode 100644 .gitignore create mode 100644 composer.json diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2659611 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +composer.lock diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..a48498c --- /dev/null +++ b/composer.json @@ -0,0 +1,21 @@ +{ + "name": "bobthecow/mustache", + "description": "A Mustache implementation in PHP.", + "keywords": ["templating", "mustache"], + "homepage": "https://github.com/bobthecow/mustache.php", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Justin Hileman", + "email": "justin@justinhileman.info", + "homepage": "http://justinhileman.com/" + } + ], + "require": { + "php": ">=5.3.0" + }, + "autoload": { + "psr-0": { "Mustache": "src/" } + } +} From bec9ce84482def7027273b97b962f8b70e539a5a Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 1 Mar 2012 11:14:49 -0800 Subject: [PATCH 27/58] Add support for PHP 5.2.x --- README.markdown | 4 +- src/Mustache/Autoloader.php | 8 +- src/Mustache/Compiler.php | 62 +++++----- src/Mustache/Context.php | 6 +- src/Mustache/HelperCollection.php | 26 ++--- src/Mustache/Loader.php | 4 +- src/Mustache/Loader/ArrayLoader.php | 11 +- src/Mustache/Loader/FilesystemLoader.php | 14 +-- src/Mustache/Loader/MutableLoader.php | 4 +- src/Mustache/Loader/StringLoader.php | 6 +- src/Mustache/Mustache.php | 108 +++++++++--------- src/Mustache/Parser.php | 32 +++--- src/Mustache/Template.php | 24 ++-- src/Mustache/Tokenizer.php | 4 +- test/Mustache/Test/AutoloaderTest.php | 18 ++- test/Mustache/Test/CompilerTest.php | 29 ++--- test/Mustache/Test/ContextTest.php | 28 ++--- test/Mustache/Test/Functional/CallTest.php | 12 +- .../Mustache/Test/Functional/ExamplesTest.php | 8 +- .../Functional/HigherOrderSectionsTest.php | 26 ++--- .../Test/Functional/MustacheInjectionTest.php | 8 +- .../Test/Functional/MustacheSpecTest.php | 11 +- .../Test/Functional/ObjectSectionTest.php | 32 +++--- test/Mustache/Test/HelperCollectionTest.php | 14 +-- test/Mustache/Test/Loader/ArrayLoaderTest.php | 12 +- .../Test/Loader/FilesystemLoaderTest.php | 14 +-- .../Mustache/Test/Loader/StringLoaderTest.php | 8 +- test/Mustache/Test/MustacheTest.php | 69 +++-------- test/Mustache/Test/ParserTest.php | 91 +++++++-------- test/Mustache/Test/TemplateTest.php | 22 ++-- test/Mustache/Test/TokenizerTest.php | 78 ++++++------- test/bootstrap.php | 2 +- test/fixtures/autoloader/Mustache/Bar.php | 4 +- test/fixtures/autoloader/Mustache/Foo.php | 4 +- 34 files changed, 330 insertions(+), 473 deletions(-) diff --git a/README.markdown b/README.markdown index 1bc9de8..3f545cd 100644 --- a/README.markdown +++ b/README.markdown @@ -11,7 +11,7 @@ A quick example: ```php render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!" ``` @@ -48,7 +48,7 @@ And render it: ```php render($template, $chris); ``` diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index 26ba662..5858262 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -9,12 +9,10 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Mustache class autoloader. */ -class Autoloader { +class Mustache_Autoloader { private $baseDir; @@ -32,7 +30,7 @@ class Autoloader { * * @param string $baseDir Mustache library base directory (default: __DIR__.'/..') * - * @return \Mustache\Autoloader Registered Autoloader instance + * @return Mustache_Autoloader Registered Autoloader instance */ static public function register($baseDir = null) { $loader = new self($baseDir); @@ -55,7 +53,7 @@ class Autoloader { return; } - $file = sprintf('%s/%s.php', $this->baseDir, str_replace('\\', '/', $class)); + $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class)); if (is_file($file)) { require $file; } diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index f8c8494..5c002d1 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -9,14 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Mustache Compiler class. * * This class is responsible for turning a Mustache token parse tree into normal PHP source code. */ -class Compiler { +class Mustache_Compiler { private $sections; private $source; @@ -46,7 +44,7 @@ class Compiler { /** * Helper function for walking the Mustache token parse tree. * - * @throws \InvalidArgumentException upon encountering unknown token types. + * @throws InvalidArgumentException upon encountering unknown token types. * * @param array $tree Parse tree of Mustache tokens * @param int $level (default: 0) @@ -57,46 +55,46 @@ class Compiler { $code = ''; $level++; foreach ($tree as $node) { - switch (is_string($node) ? 'text' : $node[Tokenizer::TYPE]) { - case Tokenizer::T_SECTION: + switch (is_string($node) ? 'text' : $node[Mustache_Tokenizer::TYPE]) { + case Mustache_Tokenizer::T_SECTION: $code .= $this->section( - $node[Tokenizer::NODES], - $node[Tokenizer::NAME], - $node[Tokenizer::INDEX], - $node[Tokenizer::END], - $node[Tokenizer::OTAG], - $node[Tokenizer::CTAG], + $node[Mustache_Tokenizer::NODES], + $node[Mustache_Tokenizer::NAME], + $node[Mustache_Tokenizer::INDEX], + $node[Mustache_Tokenizer::END], + $node[Mustache_Tokenizer::OTAG], + $node[Mustache_Tokenizer::CTAG], $level ); break; - case Tokenizer::T_INVERTED: + case Mustache_Tokenizer::T_INVERTED: $code .= $this->invertedSection( - $node[Tokenizer::NODES], - $node[Tokenizer::NAME], + $node[Mustache_Tokenizer::NODES], + $node[Mustache_Tokenizer::NAME], $level ); break; - case Tokenizer::T_PARTIAL: - case Tokenizer::T_PARTIAL_2: + case Mustache_Tokenizer::T_PARTIAL: + case Mustache_Tokenizer::T_PARTIAL_2: $code .= $this->partial( - $node[Tokenizer::NAME], - isset($node[Tokenizer::INDENT]) ? $node[Tokenizer::INDENT] : '', + $node[Mustache_Tokenizer::NAME], + isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', $level ); break; - case Tokenizer::T_UNESCAPED: - case Tokenizer::T_UNESCAPED_2: - $code .= $this->variable($node[Tokenizer::NAME], false, $level); + case Mustache_Tokenizer::T_UNESCAPED: + case Mustache_Tokenizer::T_UNESCAPED_2: + $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level); break; - case Tokenizer::T_COMMENT: + case Mustache_Tokenizer::T_COMMENT: break; - case Tokenizer::T_ESCAPED: - $code .= $this->variable($node[Tokenizer::NAME], true, $level); + case Mustache_Tokenizer::T_ESCAPED: + $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level); break; @@ -105,7 +103,7 @@ class Compiler { break; default: - throw new \InvalidArgumentException('Unknown node type: '.json_encode($node)); + throw new InvalidArgumentException('Unknown node type: '.json_encode($node)); } } @@ -114,8 +112,8 @@ class Compiler { const KLASS = ' $helper` pairs. + * Optionally accepts an array (or Traversable) of `$name => $helper` pairs. * - * @throws \InvalidArgumentException if the $helpers argument isn't an array or \Traversable + * @throws InvalidArgumentException if the $helpers argument isn't an array or Traversable * * @param array|Traversable $helpers (default: null) */ public function __construct($helpers = null) { if ($helpers !== null) { - if (!is_array($helpers) && !$helpers instanceof \Traversable) { - throw new \InvalidArgumentException('HelperCollection constructor expects an array of helpers'); + if (!is_array($helpers) && !$helpers instanceof Traversable) { + throw new InvalidArgumentException('HelperCollection constructor expects an array of helpers'); } foreach ($helpers as $name => $helper) { @@ -41,7 +39,7 @@ class HelperCollection { /** * Magic mutator. * - * @see \Mustache\HelperCollection::add + * @see Mustache_HelperCollection::add * * @param string $name * @param mixed $helper @@ -63,7 +61,7 @@ class HelperCollection { /** * Magic accessor. * - * @see \Mustache\HelperCollection::get + * @see Mustache_HelperCollection::get * * @param string $name * @@ -82,7 +80,7 @@ class HelperCollection { */ public function get($name) { if (!$this->has($name)) { - throw new \InvalidArgumentException('Unknown helper: '.$name); + throw new InvalidArgumentException('Unknown helper: '.$name); } return $this->helpers[$name]; @@ -91,7 +89,7 @@ class HelperCollection { /** * Magic isset(). * - * @see \Mustache\HelperCollection::has + * @see Mustache_HelperCollection::has * * @param string $name * @@ -115,7 +113,7 @@ class HelperCollection { /** * Magic unset(). * - * @see \Mustache\HelperCollection::remove + * @see Mustache_HelperCollection::remove * * @param string $name */ @@ -126,13 +124,13 @@ class HelperCollection { /** * Check whether a given helper is present in the collection. * - * @throws \InvalidArgumentException if the requested helper is not present. + * @throws InvalidArgumentException if the requested helper is not present. * * @param string $name */ public function remove($name) { if (!$this->has($name)) { - throw new \InvalidArgumentException('Unknown helper: '.$name); + throw new InvalidArgumentException('Unknown helper: '.$name); } unset($this->helpers[$name]); diff --git a/src/Mustache/Loader.php b/src/Mustache/Loader.php index 00bf67d..bdd2817 100644 --- a/src/Mustache/Loader.php +++ b/src/Mustache/Loader.php @@ -9,12 +9,10 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Mustache Template Loader interface. */ -interface Loader { +interface Mustache_Loader { /** * Load a Template by name. diff --git a/src/Mustache/Loader/ArrayLoader.php b/src/Mustache/Loader/ArrayLoader.php index 4bd674a..883b5ae 100644 --- a/src/Mustache/Loader/ArrayLoader.php +++ b/src/Mustache/Loader/ArrayLoader.php @@ -9,11 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache\Loader; - -use Mustache\Loader; -use Mustache\Loader\MutableLoader; - /** * Mustache Template array Loader implementation. * @@ -26,13 +21,13 @@ use Mustache\Loader\MutableLoader; * * $tpl = $loader->load('foo'); // '{{ bar }}' * - * The ArrayLoader is used internally as a partials loader by \Mustache\Mustache instance when an array of partials + * The ArrayLoader is used internally as a partials loader by Mustache_Mustache instance when an array of partials * is set. It can also be used as a quick-and-dirty Template loader. * * @implements Loader * @implements MutableLoader */ -class ArrayLoader implements Loader, MutableLoader { +class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader { /** * ArrayLoader constructor. @@ -52,7 +47,7 @@ class ArrayLoader implements Loader, MutableLoader { */ public function load($name) { if (!isset($this->templates[$name])) { - throw new \InvalidArgumentException('Template '.$name.' not found.'); + throw new InvalidArgumentException('Template '.$name.' not found.'); } return $this->templates[$name]; diff --git a/src/Mustache/Loader/FilesystemLoader.php b/src/Mustache/Loader/FilesystemLoader.php index 626040d..28ed564 100644 --- a/src/Mustache/Loader/FilesystemLoader.php +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -9,10 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache\Loader; - -use Mustache\Loader; - /** * Mustache Template filesystem Loader implementation. * @@ -30,7 +26,7 @@ use Mustache\Loader; * * @implements Loader */ -class FilesystemLoader implements Loader { +class Mustache_Loader_FilesystemLoader implements Mustache_Loader { private $baseDir; private $extension = '.mustache'; private $templates = array(); @@ -45,7 +41,7 @@ class FilesystemLoader implements Loader { * 'extension' => '.ms', * ); * - * @throws \RuntimeException if $baseDir does not exist. + * @throws RuntimeException if $baseDir does not exist. * * @param string $baseDir Base directory containing Mustache template files. * @param array $options Array of Loader options (default: array()) @@ -54,7 +50,7 @@ class FilesystemLoader implements Loader { $this->baseDir = rtrim(realpath($baseDir), '/'); if (!is_dir($this->baseDir)) { - throw new \RuntimeException('FilesystemLoader baseDir must be a directory: '.$baseDir); + throw new RuntimeException('FilesystemLoader baseDir must be a directory: '.$baseDir); } if (isset($options['extension'])) { @@ -83,7 +79,7 @@ class FilesystemLoader implements Loader { /** * Helper function for loading a Mustache file by name. * - * @throws \InvalidArgumentException if a template file is not found. + * @throws InvalidArgumentException if a template file is not found. * * @param string $name * @@ -93,7 +89,7 @@ class FilesystemLoader implements Loader { $fileName = $this->getFileName($name); if (!file_exists($fileName)) { - throw new \InvalidArgumentException('Template '.$name.' not found.'); + throw new InvalidArgumentException('Template '.$name.' not found.'); } return file_get_contents($fileName); diff --git a/src/Mustache/Loader/MutableLoader.php b/src/Mustache/Loader/MutableLoader.php index f951fe2..0af14c2 100644 --- a/src/Mustache/Loader/MutableLoader.php +++ b/src/Mustache/Loader/MutableLoader.php @@ -9,12 +9,10 @@ * file that was distributed with this source code. */ -namespace Mustache\Loader; - /** * Mustache Template mutable Loader interface. */ -interface MutableLoader { +interface Mustache_Loader_MutableLoader { /** * Set an associative array of Template sources for this loader. diff --git a/src/Mustache/Loader/StringLoader.php b/src/Mustache/Loader/StringLoader.php index 5b65732..88b253f 100644 --- a/src/Mustache/Loader/StringLoader.php +++ b/src/Mustache/Loader/StringLoader.php @@ -9,10 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache\Loader; - -use Mustache\Loader; - /** * Mustache Template string Loader implementation. * @@ -29,7 +25,7 @@ use Mustache\Loader; * * @implements Loader */ -class StringLoader implements Loader { +class Mustache_Loader_StringLoader implements Mustache_Loader { /** * Load a Template by source. diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 7a8e61e..472c6bb 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -9,12 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache; - -use Mustache\Loader\ArrayLoader; -use Mustache\Loader\MutableLoader; -use Mustache\Loader\StringLoader; - /** * A Mustache implementation in PHP. * @@ -27,7 +21,7 @@ use Mustache\Loader\StringLoader; * * @author Justin Hileman {@link http://justinhileman.com} */ -class Mustache { +class Mustache_Mustache { const VERSION = '2.0.0-dev'; const SPEC_VERSION = '1.1.2'; @@ -50,16 +44,16 @@ class Mustache { * * $options = array( * // The class prefix for compiled templates. Defaults to '__Mustache_' - * 'template_class_prefix' => '\My\Namespace\Template\', + * 'template_class_prefix' => '__MyTemplates_', * * // A cache directory for compiled templates. Mustache will not cache templates unless this is set * 'cache' => __DIR__.'/tmp/cache/mustache', * * // A Mustache template loader instance. Uses a StringLoader if not specified - * 'loader' => new \Mustache\Loader\FilesystemLoader(__DIR__.'/views'), + * 'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/views'), * * // A Mustache loader instance for partials. - * 'partials_loader' => new \Mustache\Loader\FilesystemLoader(__DIR__.'/views/partials'), + * 'partials_loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/views/partials'), * * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as * // efficient or lazy as a Filesystem (or database) loader. @@ -126,8 +120,8 @@ class Mustache { * * Equivalent to calling `$mustache->loadTemplate($template)->render($data);` * - * @see \Mustache\Mustache::loadTemplate - * @see \Mustache\Template::render + * @see Mustache_Mustache::loadTemplate + * @see Mustache_Template::render * * @param string $template * @param mixed $data @@ -159,9 +153,9 @@ class Mustache { /** * Set the Mustache template Loader instance. * - * @param \Mustache\Loader $loader + * @param Mustache_Loader $loader */ - public function setLoader(Loader $loader) { + public function setLoader(Mustache_Loader $loader) { $this->loader = $loader; } @@ -171,11 +165,11 @@ class Mustache { * If no Loader instance has been explicitly specified, this method will instantiate and return * a StringLoader instance. * - * @return \Mustache\Loader + * @return Mustache_Loader */ public function getLoader() { if (!isset($this->loader)) { - $this->loader = new StringLoader; + $this->loader = new Mustache_Loader_StringLoader; } return $this->loader; @@ -184,9 +178,9 @@ class Mustache { /** * Set the Mustache partials Loader instance. * - * @param \Mustache\Loader $partialsLoader + * @param Mustache_Loader $partialsLoader */ - public function setPartialsLoader(Loader $partialsLoader) { + public function setPartialsLoader(Mustache_Loader $partialsLoader) { $this->partialsLoader = $partialsLoader; } @@ -196,11 +190,11 @@ class Mustache { * If no Loader instance has been explicitly specified, this method will instantiate and return * an ArrayLoader instance. * - * @return \Mustache\Loader + * @return Mustache_Loader */ public function getPartialsLoader() { if (!isset($this->partialsLoader)) { - $this->partialsLoader = new ArrayLoader; + $this->partialsLoader = new Mustache_Loader_ArrayLoader; } return $this->partialsLoader; @@ -209,14 +203,14 @@ class Mustache { /** * Set partials for the current partials Loader instance. * - * @throws \RuntimeException If the current Loader instance is immutable + * @throws RuntimeException If the current Loader instance is immutable * * @param array $partials (default: array()) */ public function setPartials(array $partials = array()) { $loader = $this->getPartialsLoader(); - if (!$loader instanceof MutableLoader) { - throw new \RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); + if (!$loader instanceof Mustache_Loader_MutableLoader) { + throw new RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); } $loader->setTemplates($partials); @@ -229,13 +223,13 @@ class Mustache { * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in * any template loaded by this Mustache instance. * - * @throws \InvalidArgumentException if $helpers is not an array or \Traversable + * @throws InvalidArgumentException if $helpers is not an array or Traversable * * @param array|Traversable $helpers */ public function setHelpers($helpers) { - if (!is_array($helpers) && !$helpers instanceof \Traversable) { - throw new \InvalidArgumentException('setHelpers expects an array of helpers'); + if (!is_array($helpers) && !$helpers instanceof Traversable) { + throw new InvalidArgumentException('setHelpers expects an array of helpers'); } $this->getHelpers()->clear(); @@ -248,13 +242,13 @@ class Mustache { /** * Get the current set of Mustache helpers. * - * @see \Mustache\Mustache::setHelpers + * @see Mustache_Mustache::setHelpers * - * @return \Mustache\HelperCollection + * @return Mustache_HelperCollection */ public function getHelpers() { if (!isset($this->helpers)) { - $this->helpers = new HelperCollection; + $this->helpers = new Mustache_HelperCollection; } return $this->helpers; @@ -263,7 +257,7 @@ class Mustache { /** * Add a new Mustache helper. * - * @see \Mustache\Mustache::setHelpers + * @see Mustache_Mustache::setHelpers * * @param string $name * @param mixed $helper @@ -275,7 +269,7 @@ class Mustache { /** * Get a Mustache helper by name. * - * @see \Mustache\Mustache::setHelpers + * @see Mustache_Mustache::setHelpers * * @param string $name * @@ -288,7 +282,7 @@ class Mustache { /** * Check whether this Mustache instance has a helper. * - * @see \Mustache\Mustache::setHelpers + * @see Mustache_Mustache::setHelpers * * @param string $name * @@ -301,7 +295,7 @@ class Mustache { /** * Remove a helper by name. * - * @see \Mustache\Mustache::setHelpers + * @see Mustache_Mustache::setHelpers * * @param string $name */ @@ -312,9 +306,9 @@ class Mustache { /** * Set the Mustache Tokenizer instance. * - * @param \Mustache\Tokenizer $tokenizer + * @param Mustache_Tokenizer $tokenizer */ - public function setTokenizer(Tokenizer $tokenizer) { + public function setTokenizer(Mustache_Tokenizer $tokenizer) { $this->tokenizer = $tokenizer; } @@ -323,11 +317,11 @@ class Mustache { * * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. * - * @return \Mustache\Tokenizer + * @return Mustache_Tokenizer */ public function getTokenizer() { if (!isset($this->tokenizer)) { - $this->tokenizer = new Tokenizer; + $this->tokenizer = new Mustache_Tokenizer; } return $this->tokenizer; @@ -336,9 +330,9 @@ class Mustache { /** * Set the Mustache Parser instance. * - * @param \Mustache\Parser $parser + * @param Mustache_Parser $parser */ - public function setParser(Parser $parser) { + public function setParser(Mustache_Parser $parser) { $this->parser = $parser; } @@ -347,11 +341,11 @@ class Mustache { * * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. * - * @return \Mustache\Parser + * @return Mustache_Parser */ public function getParser() { if (!isset($this->parser)) { - $this->parser = new Parser; + $this->parser = new Mustache_Parser; } return $this->parser; @@ -360,9 +354,9 @@ class Mustache { /** * Set the Mustache Compiler instance. * - * @param \Mustache\Compiler $compiler + * @param Mustache_Compiler $compiler */ - public function setCompiler(Compiler $compiler) { + public function setCompiler(Mustache_Compiler $compiler) { $this->compiler = $compiler; } @@ -371,11 +365,11 @@ class Mustache { * * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. * - * @return \Mustache\Compiler + * @return Mustache_Compiler */ public function getCompiler() { if (!isset($this->compiler)) { - $this->compiler = new Compiler; + $this->compiler = new Mustache_Compiler; } return $this->compiler; @@ -403,7 +397,7 @@ class Mustache { * * @param string $name * - * @return \Mustache\Template + * @return Mustache_Template */ public function loadTemplate($name) { return $this->loadSource($this->getLoader()->load($name)); @@ -417,7 +411,7 @@ class Mustache { * * @param string $name * - * @return \Mustache\Template + * @return Mustache_Template */ public function loadPartial($name) { return $this->loadSource($this->getPartialsLoader()->load($name)); @@ -432,7 +426,7 @@ class Mustache { * @param string $source * @param string $delims (default: null) * - * @return \Mustache\Template + * @return Mustache_Template */ public function loadLambda($source, $delims = null) { if ($delims !== null) { @@ -445,13 +439,13 @@ class Mustache { /** * Instantiate and return a Mustache Template instance by source. * - * @see \Mustache\Mustache::loadTemplate - * @see \Mustache\Mustache::loadPartial - * @see \Mustache\Mustache::loadLambda + * @see Mustache_Mustache::loadTemplate + * @see Mustache_Mustache::loadPartial + * @see Mustache_Mustache::loadLambda * * @param string $source * - * @return \Mustache\Template + * @return Mustache_Template */ private function loadSource($source) { $className = $this->getTemplateClassName($source); @@ -478,7 +472,7 @@ class Mustache { /** * Helper method to tokenize a Mustache template. * - * @see \Mustache\Tokenizer::scan + * @see Mustache_Tokenizer::scan * * @param string $source * @@ -491,7 +485,7 @@ class Mustache { /** * Helper method to parse a Mustache template. * - * @see \Mustache\Parser::parse + * @see Mustache_Parser::parse * * @param string $source * @@ -504,7 +498,7 @@ class Mustache { /** * Helper method to compile a Mustache template. * - * @see \Mustache\Compiler::compile + * @see Mustache_Compiler::compile * * @param string $source * @@ -533,7 +527,7 @@ class Mustache { /** * Helper method to dump a generated Mustache Template subclass to the file cache. * - * @throws \RuntimeException if unable to write to $fileName. + * @throws RuntimeException if unable to write to $fileName. * * @param string $fileName * @param string $source @@ -552,6 +546,6 @@ class Mustache { } } - throw new \RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); + throw new RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); } } diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index d115ce9..eb3c3b8 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -9,14 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Mustache Parser class. * * This class is responsible for turning a set of Mustache tokens into a parse tree. */ -class Parser { +class Mustache_Parser { /** * Process an array of Mustache tokens and convert them into a parse tree. @@ -26,20 +24,20 @@ class Parser { * @return array Mustache token parse tree */ public function parse(array $tokens = array()) { - return $this->buildTree(new \ArrayIterator($tokens)); + return $this->buildTree(new ArrayIterator($tokens)); } /** * Helper method for recursively building a parse tree. * - * @throws \LogicException when nesting errors or mismatched section tags are encountered. + * @throws LogicException when nesting errors or mismatched section tags are encountered. * - * @param \ArrayIterator $tokens Stream of Mustache tokens + * @param ArrayIterator $tokens Stream of Mustache tokens * @param array $parent Parent token (default: null) * * @return array Mustache Token parse tree */ - private function buildTree(\ArrayIterator $tokens, array $parent = null) { + private function buildTree(ArrayIterator $tokens, array $parent = null) { $nodes = array(); do { @@ -49,23 +47,23 @@ class Parser { if ($token === null) { continue; } elseif (is_array($token)) { - switch ($token[Tokenizer::TYPE]) { - case Tokenizer::T_SECTION: - case Tokenizer::T_INVERTED: + switch ($token[Mustache_Tokenizer::TYPE]) { + case Mustache_Tokenizer::T_SECTION: + case Mustache_Tokenizer::T_INVERTED: $nodes[] = $this->buildTree($tokens, $token); break; - case Tokenizer::T_END_SECTION: + case Mustache_Tokenizer::T_END_SECTION: if (!isset($parent)) { - throw new \LogicException('Unexpected closing tag: /'. $token[Tokenizer::NAME]); + throw new LogicException('Unexpected closing tag: /'. $token[Mustache_Tokenizer::NAME]); } - if ($token[Tokenizer::NAME] !== $parent[Tokenizer::NAME]) { - throw new \LogicException('Nesting error: ' . $parent[Tokenizer::NAME] . ' vs. ' . $token[Tokenizer::NAME]); + if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { + throw new LogicException('Nesting error: ' . $parent[Mustache_Tokenizer::NAME] . ' vs. ' . $token[Mustache_Tokenizer::NAME]); } - $parent[Tokenizer::END] = $token[Tokenizer::INDEX]; - $parent[Tokenizer::NODES] = $nodes; + $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; + $parent[Mustache_Tokenizer::NODES] = $nodes; return $parent; break; @@ -81,7 +79,7 @@ class Parser { } while ($tokens->valid()); if (isset($parent)) { - throw new \LogicException('Missing closing tag: ' . $parent[Tokenizer::NAME]); + throw new LogicException('Missing closing tag: ' . $parent[Mustache_Tokenizer::NAME]); } return $nodes; diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 0fa2db6..97be3b9 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -9,37 +9,35 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Abstract Mustache Template class. * * @abstract */ -abstract class Template { +abstract class Mustache_Template { /** - * @var \Mustache\Mustache + * @var Mustache_Mustache */ protected $mustache; /** * Mustache Template constructor. * - * @param \Mustache\Mustache $mustache + * @param Mustache_Mustache $mustache */ - public function __construct(Mustache $mustache) { + public function __construct(Mustache_Mustache $mustache) { $this->mustache = $mustache; } /** * Mustache Template instances can be treated as a function and rendered by simply calling them: * - * $m = new Mustache; + * $m = new Mustache_Mustache; * $tpl = $m->loadTemplate('Hello, {{ name }}!'); * echo $tpl(array('name' => 'World')); // "Hello, World!" * - * @see \Mustache\Template::render + * @see Mustache_Template::render * * @param mixed $context Array or object rendering context (default: array()) * @@ -67,11 +65,11 @@ abstract class Template { * * @abstract * - * @param \Mustache\Context $context + * @param Mustache_Context $context * * @return string Rendered template */ - abstract public function renderInternal(Context $context, $indent = '', $escape = false); + abstract public function renderInternal(Mustache_Context $context, $indent = '', $escape = false); /** * Tests whether a value should be iterated over (e.g. in a section context). @@ -104,7 +102,7 @@ abstract class Template { */ protected function isIterable($value) { if (is_object($value)) { - return $value instanceof \Traversable; + return $value instanceof Traversable; } elseif (is_array($value)) { $i = 0; foreach ($value as $k => $v) { @@ -126,10 +124,10 @@ abstract class Template { * * @param mixed $context Optional first context frame (default: null) * - * @return \Mustache\Context + * @return Mustache_Context */ protected function prepareContextStack($context = null) { - $stack = new Context; + $stack = new Mustache_Context; $helpers = $this->mustache->getHelpers(); if (!$helpers->isEmpty()) { diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index 226f091..bafd2b0 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -9,14 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache; - /** * Mustache Tokenizer class. * * This class is responsible for turning raw template source into a set of Mustache tokens. */ -class Tokenizer { +class Mustache_Tokenizer { // Finite state machine states const IN_TEXT = 0; diff --git a/test/Mustache/Test/AutoloaderTest.php b/test/Mustache/Test/AutoloaderTest.php index 2c8f694..9a4a358 100644 --- a/test/Mustache/Test/AutoloaderTest.php +++ b/test/Mustache/Test/AutoloaderTest.php @@ -9,29 +9,25 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Autoloader; - /** * @group unit */ -class AutoloaderTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase { public function testRegister() { - $loader = Autoloader::register(); + $loader = Mustache_Autoloader::register(); $this->assertTrue(spl_autoload_unregister(array($loader, 'autoload'))); } public function testAutoloader() { - $loader = new Autoloader(__DIR__.'/../../fixtures/autoloader'); + $loader = new Mustache_Autoloader(__DIR__.'/../../fixtures/autoloader'); $this->assertNull($loader->autoload('NonMustacheClass')); $this->assertFalse(class_exists('NonMustacheClass')); - $loader->autoload('Mustache\Foo'); - $this->assertTrue(class_exists('Mustache\Foo')); + $loader->autoload('Mustache_Foo'); + $this->assertTrue(class_exists('Mustache_Foo')); - $loader->autoload('\Mustache\Bar'); - $this->assertTrue(class_exists('Mustache\Bar')); + $loader->autoload('\Mustache_Bar'); + $this->assertTrue(class_exists('Mustache_Bar')); } } diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index 266b4cf..2984a1a 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -9,21 +9,16 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Compiler; -use Mustache\Tokenizer; - /** * @group unit */ -class CompilerTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { /** * @dataProvider getCompileValues */ public function testCompile($source, array $tree, $name, $customEscaper, $charset, $expected) { - $compiler = new Compiler; + $compiler = new Mustache_Compiler; $compiled = $compiler->compile($source, $tree, $name, $customEscaper, $charset); foreach ($expected as $contains) { @@ -34,20 +29,20 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { public function getCompileValues() { return array( array('', array(), 'Banana', false, 'ISO-8859-1', array( - "\nclass Banana extends \Mustache\Template", + "\nclass Banana extends Mustache_Template", 'return htmlspecialchars($buffer, ENT_COMPAT, \'ISO-8859-1\');', 'return $buffer;', )), array('', array('TEXT'), 'Monkey', false, 'UTF-8', array( - "\nclass Monkey extends \Mustache\Template", + "\nclass Monkey extends Mustache_Template", 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', '$buffer .= $indent . \'TEXT\';', 'return $buffer;', )), array('', array('TEXT'), 'Monkey', true, 'ISO-8859-1', array( - "\nclass Monkey extends \Mustache\Template", + "\nclass Monkey extends Mustache_Template", '$buffer .= $indent . \'TEXT\';', 'return call_user_func($this->mustache->getEscape(), $buffer);', 'return $buffer;', @@ -59,12 +54,12 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { 'foo', "\n", array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name', + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', ), array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => '.', + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => '.', ), "'bar'", ), @@ -72,7 +67,7 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { false, 'UTF-8', array( - "\nclass Monkey extends \Mustache\Template", + "\nclass Monkey extends Mustache_Template", '$buffer .= $indent . \'foo\'', '$buffer .= "\n"', '$value = $context->find(\'name\');', @@ -90,7 +85,7 @@ class CompilerTest extends \PHPUnit_Framework_TestCase { * @expectedException InvalidArgumentException */ public function testCompilerThrowsUnknownNodeTypeException() { - $compiler = new Compiler; - $compiler->compile('', array(array(Tokenizer::TYPE => 'invalid')), 'SomeClass'); + $compiler = new Mustache_Compiler; + $compiler->compile('', array(array(Mustache_Tokenizer::TYPE => 'invalid')), 'SomeClass'); } } diff --git a/test/Mustache/Test/ContextTest.php b/test/Mustache/Test/ContextTest.php index c71cd53..c11afb8 100644 --- a/test/Mustache/Test/ContextTest.php +++ b/test/Mustache/Test/ContextTest.php @@ -9,44 +9,40 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Context; - /** * @group unit */ -class ContextTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_ContextTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $one = new Context; + $one = new Mustache_Context; $this->assertSame('', $one->find('foo')); $this->assertSame('', $one->find('bar')); - $two = new Context(array( + $two = new Mustache_Context(array( 'foo' => 'FOO', 'bar' => '' )); $this->assertEquals('FOO', $two->find('foo')); $this->assertEquals('', $two->find('bar')); - $obj = new \StdClass; + $obj = new StdClass; $obj->name = 'NAME'; - $three = new Context($obj); + $three = new Mustache_Context($obj); $this->assertSame($obj, $three->last()); $this->assertEquals('NAME', $three->find('name')); } public function testPushPopAndLast() { - $context = new Context; + $context = new Mustache_Context; $this->assertFalse($context->last()); - $dummy = new TestDummy; + $dummy = new Mustache_Test_TestDummy; $context->push($dummy); $this->assertSame($dummy, $context->last()); $this->assertSame($dummy, $context->pop()); $this->assertFalse($context->last()); - $obj = new \StdClass; + $obj = new StdClass; $context->push($dummy); $this->assertSame($dummy, $context->last()); $context->push($obj); @@ -57,11 +53,11 @@ class ContextTest extends \PHPUnit_Framework_TestCase { } public function testFind() { - $context = new Context; + $context = new Mustache_Context; - $dummy = new TestDummy; + $dummy = new Mustache_Test_TestDummy; - $obj = new \StdClass; + $obj = new StdClass; $obj->name = 'obj'; $arr = array( @@ -98,7 +94,7 @@ class ContextTest extends \PHPUnit_Framework_TestCase { } } -class TestDummy { +class Mustache_Test_TestDummy { public $name = 'dummy'; public function __invoke() { diff --git a/test/Mustache/Test/Functional/CallTest.php b/test/Mustache/Test/Functional/CallTest.php index 4ebd6bc..bb89e43 100644 --- a/test/Mustache/Test/Functional/CallTest.php +++ b/test/Mustache/Test/Functional/CallTest.php @@ -9,21 +9,17 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; - /** * @group magic_methods * @group functional */ -class CallTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_CallTest extends PHPUnit_Framework_TestCase { public function testCallEatsContext() { - $m = new Mustache; + $m = new Mustache_Mustache; $tpl = $m->loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); - $foo = new ClassWithCall(); + $foo = new Mustache_Test_Functional_ClassWithCall(); $foo->name = 'Bob'; $data = array('label' => 'name', 'foo' => $foo); @@ -32,7 +28,7 @@ class CallTest extends \PHPUnit_Framework_TestCase { } } -class ClassWithCall { +class Mustache_Test_Functional_ClassWithCall { public $name; public function __call($method, $args) { return 'unknown value'; diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 104bf50..46d6bd0 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -9,15 +9,11 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; - /** * @group examples * @group functional */ -class ExamplesTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase { /** * Test everything in the `examples` directory. @@ -30,7 +26,7 @@ class ExamplesTest extends \PHPUnit_Framework_TestCase { * @param string $expected */ public function testExamples($context, $source, $partials, $expected) { - $mustache = new Mustache(array( + $mustache = new Mustache_Mustache(array( 'partials' => $partials )); $this->assertEquals($expected, $mustache->loadTemplate($source)->render($context)); diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 608aaab..8743551 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -9,26 +9,22 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; - /** * @group lambdas * @group functional */ -class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework_TestCase { private $mustache; public function setUp() { - $this->mustache = new Mustache; + $this->mustache = new Mustache_Mustache; } public function testAnonymousFunctionSectionCallback() { $tpl = $this->mustache->loadTemplate('{{#wrapper}}{{name}}{{/wrapper}}'); - $foo = new Foo; + $foo = new Mustache_Test_Functional_Foo; $foo->name = 'Mario'; $foo->wrapper = function($text) { return sprintf('
%s
', $text); @@ -41,7 +37,7 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { $one = $this->mustache->loadTemplate('{{name}}'); $two = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); - $foo = new Foo; + $foo = new Mustache_Test_Functional_Foo; $foo->name = 'Luigi'; $this->assertEquals($foo->name, $one->render($foo)); @@ -51,7 +47,7 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { public function testRuntimeSectionCallback() { $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); - $foo = new Foo; + $foo = new Mustache_Test_Functional_Foo; $foo->doublewrap = array($foo, 'wrapWithBoth'); $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); @@ -60,7 +56,7 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { public function testStaticSectionCallback() { $tpl = $this->mustache->loadTemplate('{{#trimmer}} {{name}} {{/trimmer}}'); - $foo = new Foo; + $foo = new Mustache_Test_Functional_Foo; $foo->trimmer = array(get_class($foo), 'staticTrim'); $this->assertEquals($foo->name, $tpl->render($foo)); @@ -69,7 +65,7 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { public function testViewArraySectionCallback() { $tpl = $this->mustache->loadTemplate('{{#trim}} {{name}} {{/trim}}'); - $foo = new Foo; + $foo = new Mustache_Test_Functional_Foo; $data = array( 'name' => 'Bob', @@ -95,19 +91,19 @@ class HigherOrderSectionsTest extends \PHPUnit_Framework_TestCase { public function testMonsters() { $tpl = $this->mustache->loadTemplate('{{#title}}{{title}} {{/title}}{{name}}'); - $frank = new Monster(); + $frank = new Mustache_Test_Functional_Monster(); $frank->title = 'Dr.'; $frank->name = 'Frankenstein'; $this->assertEquals('Dr. Frankenstein', $tpl->render($frank)); - $dracula = new Monster(); + $dracula = new Mustache_Test_Functional_Monster(); $dracula->title = 'Count'; $dracula->name = 'Dracula'; $this->assertEquals('Count Dracula', $tpl->render($dracula)); } } -class Foo { +class Mustache_Test_Functional_Foo { public $name = 'Justin'; public $lorem = 'Lorem ipsum dolor sit amet,'; public $wrap; @@ -135,7 +131,7 @@ class Foo { } } -class Monster { +class Mustache_Test_Functional_Monster { public $title; public $name; } diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index 7c31f5e..e16bd7f 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -9,20 +9,16 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; - /** * @group mustache_injection * @group functional */ -class MustacheInjectionTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_TestCase { private $mustache; public function setUp() { - $this->mustache = new Mustache; + $this->mustache = new Mustache_Mustache; } // interpolation diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 8fe91a9..2343fbd 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -9,23 +9,18 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; -use Mustache\Loader\StringLoader; - /** * A PHPUnit test case wrapping the Mustache Spec * * @group mustache-spec * @group functional */ -class MustacheSpecTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCase { private static $mustache; public static function setUpBeforeClass() { - self::$mustache = new Mustache; + self::$mustache = new Mustache_Mustache; } /** @@ -167,7 +162,7 @@ class MustacheSpecTest extends \PHPUnit_Framework_TestCase { } $data = array(); - $yaml = new \sfYamlParser; + $yaml = new sfYamlParser; $file = file_get_contents($filename); // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. diff --git a/test/Mustache/Test/Functional/ObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php index 1c52499..e9decf0 100644 --- a/test/Mustache/Test/Functional/ObjectSectionTest.php +++ b/test/Mustache/Test/Functional/ObjectSectionTest.php @@ -9,24 +9,20 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Functional; - -use Mustache\Mustache; - /** * @group sections * @group functional */ -class ObjectSectionTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_ObjectSectionTest extends PHPUnit_Framework_TestCase { private $mustache; public function setUp() { - $this->mustache = new Mustache; + $this->mustache = new Mustache_Mustache; } public function testBasicObject() { $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $this->assertEquals('Foo', $tpl->render(new Alpha)); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Alpha)); } /** @@ -34,7 +30,7 @@ class ObjectSectionTest extends \PHPUnit_Framework_TestCase { */ public function testObjectWithGet() { $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $this->assertEquals('Foo', $tpl->render(new Beta)); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Beta)); } /** @@ -42,32 +38,32 @@ class ObjectSectionTest extends \PHPUnit_Framework_TestCase { */ public function testSectionObjectWithGet() { $tpl = $this->mustache->loadTemplate('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}'); - $this->assertEquals('Foo', $tpl->render(new Gamma)); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Gamma)); } public function testSectionObjectWithFunction() { $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $alpha = new Alpha; - $alpha->foo = new Delta; + $alpha = new Mustache_Test_Functional_Alpha; + $alpha->foo = new Mustache_Test_Functional_Delta; $this->assertEquals('Foo', $tpl->render($alpha)); } } -class Alpha { +class Mustache_Test_Functional_Alpha { public $foo; public function __construct() { - $this->foo = new \StdClass(); + $this->foo = new StdClass(); $this->foo->name = 'Foo'; $this->foo->number = 1; } } -class Beta { +class Mustache_Test_Functional_Beta { protected $_data = array(); public function __construct() { - $this->_data['foo'] = new \StdClass(); + $this->_data['foo'] = new StdClass(); $this->_data['foo']->name = 'Foo'; $this->_data['foo']->number = 1; } @@ -81,15 +77,15 @@ class Beta { } } -class Gamma { +class Mustache_Test_Functional_Gamma { public $bar; public function __construct() { - $this->bar = new Beta(); + $this->bar = new Mustache_Test_Functional_Beta; } } -class Delta { +class Mustache_Test_Functional_Delta { protected $_name = 'Foo'; public function name() { diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php index 12e48dd..1a643d4 100644 --- a/test/Mustache/Test/HelperCollectionTest.php +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -9,16 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\HelperCollection; - -class HelperCollectionTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { public function testConstructor() { $foo = function() { echo 'foo'; }; $bar = 'BAR'; - $helpers = new HelperCollection(array( + $helpers = new Mustache_HelperCollection(array( 'foo' => $foo, 'bar' => $bar, )); @@ -31,7 +27,7 @@ class HelperCollectionTest extends \PHPUnit_Framework_TestCase { $foo = function() { echo 'foo'; }; $bar = 'BAR'; - $helpers = new HelperCollection; + $helpers = new Mustache_HelperCollection; $this->assertTrue($helpers->isEmpty()); $this->assertFalse($helpers->has('foo')); $this->assertFalse($helpers->has('bar')); @@ -56,7 +52,7 @@ class HelperCollectionTest extends \PHPUnit_Framework_TestCase { $foo = function() { echo 'foo'; }; $bar = 'BAR'; - $helpers = new HelperCollection; + $helpers = new Mustache_HelperCollection; $this->assertTrue($helpers->isEmpty()); $this->assertFalse($helpers->has('foo')); $this->assertFalse($helpers->has('bar')); @@ -93,7 +89,7 @@ class HelperCollectionTest extends \PHPUnit_Framework_TestCase { $this->setExpectedException($exception); } - $helpers = new HelperCollection($helpers); + $helpers = new Mustache_HelperCollection($helpers); foreach ($actions as $method => $args) { call_user_func_array(array($helpers, $method), $args); diff --git a/test/Mustache/Test/Loader/ArrayLoaderTest.php b/test/Mustache/Test/Loader/ArrayLoaderTest.php index 7eab52e..c5d53a1 100644 --- a/test/Mustache/Test/Loader/ArrayLoaderTest.php +++ b/test/Mustache/Test/Loader/ArrayLoaderTest.php @@ -9,16 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Loader; - -use Mustache\Loader\ArrayLoader; - /** * @group unit */ -class ArrayLoaderTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Loader_ArrayLoaderTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $loader = new ArrayLoader(array( + $loader = new Mustache_Loader_ArrayLoader(array( 'foo' => 'bar' )); @@ -26,7 +22,7 @@ class ArrayLoaderTest extends \PHPUnit_Framework_TestCase { } public function testSetAndLoadTemplates() { - $loader = new ArrayLoader(array( + $loader = new Mustache_Loader_ArrayLoader(array( 'foo' => 'bar' )); $this->assertEquals('bar', $loader->load('foo')); @@ -46,7 +42,7 @@ class ArrayLoaderTest extends \PHPUnit_Framework_TestCase { * @expectedException \InvalidArgumentException */ public function testMissingTemplatesThrowExceptions() { - $loader = new ArrayLoader; + $loader = new Mustache_Loader_ArrayLoader; $loader->load('not_a_real_template'); } } diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php index 64818ed..e158b45 100644 --- a/test/Mustache/Test/Loader/FilesystemLoaderTest.php +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -9,24 +9,20 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Loader; - -use Mustache\Loader\FilesystemLoader; - /** * @group unit */ -class FilesystemLoaderTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCase { public function testConstructor() { $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); - $loader = new FilesystemLoader($baseDir, array('extension' => '.ms')); + $loader = new Mustache_Loader_FilesystemLoader($baseDir, array('extension' => '.ms')); $this->assertEquals('alpha contents', $loader->load('alpha')); $this->assertEquals('beta contents', $loader->load('beta.ms')); } public function testLoadTemplates() { $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); - $loader = new FilesystemLoader($baseDir); + $loader = new Mustache_Loader_FilesystemLoader($baseDir); $this->assertEquals('one contents', $loader->load('one')); $this->assertEquals('two contents', $loader->load('two.mustache')); } @@ -35,7 +31,7 @@ class FilesystemLoaderTest extends \PHPUnit_Framework_TestCase { * @expectedException \RuntimeException */ public function testMissingBaseDirThrowsException() { - $loader = new FilesystemLoader(__DIR__.'/not_a_directory'); + $loader = new Mustache_Loader_FilesystemLoader(__DIR__.'/not_a_directory'); } /** @@ -43,7 +39,7 @@ class FilesystemLoaderTest extends \PHPUnit_Framework_TestCase { */ public function testMissingTemplateThrowsException() { $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); - $loader = new FilesystemLoader($baseDir); + $loader = new Mustache_Loader_FilesystemLoader($baseDir); $loader->load('fake'); } diff --git a/test/Mustache/Test/Loader/StringLoaderTest.php b/test/Mustache/Test/Loader/StringLoaderTest.php index 7be91a2..7a0d302 100644 --- a/test/Mustache/Test/Loader/StringLoaderTest.php +++ b/test/Mustache/Test/Loader/StringLoaderTest.php @@ -9,16 +9,12 @@ * file that was distributed with this source code. */ -namespace Mustache\Test\Loader; - -use Mustache\Loader\StringLoader; - /** * @group unit */ -class StringLoaderTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_Loader_StringLoaderTest extends PHPUnit_Framework_TestCase { public function testLoadTemplates() { - $loader = new StringLoader; + $loader = new Mustache_Loader_StringLoader; $this->assertEquals('foo', $loader->load('foo')); $this->assertEquals('{{ bar }}', $loader->load('{{ bar }}')); diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 53d804f..8ff097d 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -9,19 +9,10 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Compiler; -use Mustache\Mustache; -use Mustache\Loader\StringLoader; -use Mustache\Loader\ArrayLoader; -use Mustache\Parser; -use Mustache\Tokenizer; - /** * @group unit */ -class MustacheTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { private static $tempDir; @@ -33,9 +24,9 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { } public function testConstructor() { - $loader = new StringLoader; - $partialsLoader = new ArrayLoader; - $mustache = new Mustache(array( + $loader = new Mustache_Loader_StringLoader; + $partialsLoader = new Mustache_Loader_ArrayLoader; + $mustache = new Mustache_Mustache(array( 'template_class_prefix' => '__whot__', 'cache' => self::$tempDir, 'loader' => $loader, @@ -67,7 +58,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $data = array('bar' => 'baz'); $output = 'TEH OUTPUT'; - $template = $this->getMockBuilder('Mustache\Template') + $template = $this->getMockBuilder('Mustache_Template') ->disableOriginalConstructor() ->getMock(); @@ -84,11 +75,11 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { } public function testSettingServices() { - $loader = new StringLoader; - $tokenizer = new Tokenizer; - $parser = new Parser; - $compiler = new Compiler; - $mustache = new Mustache; + $loader = new Mustache_Loader_StringLoader; + $tokenizer = new Mustache_Tokenizer; + $parser = new Mustache_Parser; + $compiler = new Mustache_Compiler; + $mustache = new Mustache_Mustache; $this->assertNotSame($loader, $mustache->getLoader()); $mustache->setLoader($loader); @@ -115,7 +106,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { * @group functional */ public function testCache() { - $mustache = new Mustache(array( + $mustache = new Mustache_Mustache(array( 'template_class_prefix' => '__whot__', 'cache' => self::$tempDir, )); @@ -126,7 +117,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { $fileName = self::$tempDir . '/' . $className . '.php'; $this->assertInstanceOf($className, $template); $this->assertFileExists($fileName); - $this->assertContains("\nclass $className extends \Mustache\Template", file_get_contents($fileName)); + $this->assertContains("\nclass $className extends Mustache_Template", file_get_contents($fileName)); } /** @@ -134,7 +125,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { * @dataProvider getBadEscapers */ public function testNonCallableEscapeThrowsException($escape) { - new Mustache(array('escape' => $escape)); + new Mustache_Mustache(array('escape' => $escape)); } public function getBadEscapers() { @@ -144,25 +135,12 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { ); } - /** - * @group functional - * @expectedException \RuntimeException - */ - public function testCacheFailsThrowException() { - global $mustacheFilesystemRenameHax; - - $mustacheFilesystemRenameHax = true; - - $mustache = new Mustache(array('cache' => self::$tempDir)); - $mustache->loadTemplate('{{ foo }}'); - } - /** * @expectedException \RuntimeException */ public function testImmutablePartialsLoadersThrowException() { - $mustache = new Mustache(array( - 'partials_loader' => new StringLoader, + $mustache = new Mustache_Mustache(array( + 'partials_loader' => new Mustache_Loader_StringLoader, )); $mustache->setPartials(array('foo' => '{{ foo }}')); @@ -171,7 +149,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { public function testHelpers() { $foo = function() { return 'foo'; }; $bar = 'BAR'; - $mustache = new Mustache(array('helpers' => array( + $mustache = new Mustache_Mustache(array('helpers' => array( 'foo' => $foo, 'bar' => $bar, ))); @@ -207,7 +185,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { * @expectedException \InvalidArgumentException */ public function testSetHelpersThrowsExceptions() { - $mustache = new Mustache; + $mustache = new Mustache_Mustache; $mustache->setHelpers('monkeymonkeymonkey'); } @@ -232,7 +210,7 @@ class MustacheTest extends \PHPUnit_Framework_TestCase { } } -class MustacheStub extends Mustache { +class MustacheStub extends Mustache_Mustache { public $source; public $template; public function loadTemplate($source) { @@ -241,14 +219,3 @@ class MustacheStub extends Mustache { return $this->template; } } - - -// It's prob'ly best if you ignore this bit. - -namespace Mustache; - -function rename($a, $b) { - global $mustacheFilesystemRenameHax; - - return ($mustacheFilesystemRenameHax) ? false : \rename($a, $b); -} diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php index 473a16a..9f4f3f4 100644 --- a/test/Mustache/Test/ParserTest.php +++ b/test/Mustache/Test/ParserTest.php @@ -9,22 +9,17 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Parser; -use Mustache\Tokenizer; - /** * @group unit */ -class ParserTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { /** * @dataProvider getTokenSets */ public function testParse($tokens, $expected) { - $parser = new Parser; + $parser = new Mustache_Parser; $this->assertEquals($expected, $parser->parse($tokens)); } @@ -43,12 +38,12 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array(array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' )), array(array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' )), ), @@ -56,32 +51,32 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( 'foo', array( - Tokenizer::TYPE => Tokenizer::T_INVERTED, - Tokenizer::INDEX => 123, - Tokenizer::NAME => 'parent' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::INDEX => 123, + Mustache_Tokenizer::NAME => 'parent' ), array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' ), array( - Tokenizer::TYPE => Tokenizer::T_END_SECTION, - Tokenizer::INDEX => 456, - Tokenizer::NAME => 'parent' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::INDEX => 456, + Mustache_Tokenizer::NAME => 'parent' ), 'bar', ), array( 'foo', array( - Tokenizer::TYPE => Tokenizer::T_INVERTED, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, - Tokenizer::END => 456, - Tokenizer::NODES => array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + Mustache_Tokenizer::END => 456, + Mustache_Tokenizer::NODES => array( array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name' + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' ), ), ), @@ -97,7 +92,7 @@ class ParserTest extends \PHPUnit_Framework_TestCase { * @expectedException \LogicException */ public function testParserThrowsExceptions($tokens) { - $parser = new Parser; + $parser = new Mustache_Parser; $parser->parse($tokens); } @@ -107,9 +102,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TYPE => Tokenizer::T_SECTION, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, ), ), ), @@ -118,9 +113,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TYPE => Tokenizer::T_INVERTED, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, ), ), ), @@ -129,9 +124,9 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TYPE => Tokenizer::T_END_SECTION, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, ), ), ), @@ -140,24 +135,24 @@ class ParserTest extends \PHPUnit_Framework_TestCase { array( array( array( - Tokenizer::TYPE => Tokenizer::T_SECTION, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, ), array( - Tokenizer::TYPE => Tokenizer::T_SECTION, - Tokenizer::NAME => 'child', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'child', + Mustache_Tokenizer::INDEX => 123, ), array( - Tokenizer::TYPE => Tokenizer::T_END_SECTION, - Tokenizer::NAME => 'parent', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, ), array( - Tokenizer::TYPE => Tokenizer::T_END_SECTION, - Tokenizer::NAME => 'child', - Tokenizer::INDEX => 123, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'child', + Mustache_Tokenizer::INDEX => 123, ), ), ), diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php index 8b24267..2b0999d 100644 --- a/test/Mustache/Test/TemplateTest.php +++ b/test/Mustache/Test/TemplateTest.php @@ -9,28 +9,22 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Context; -use Mustache\Mustache; -use Mustache\Template; - /** * @group unit */ -class TemplateTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_TemplateTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $mustache = new Mustache; - $template = new TemplateStub($mustache); + $mustache = new Mustache_Mustache; + $template = new Mustache_Test_TemplateStub($mustache); $this->assertSame($mustache, $template->getMustache()); } public function testRendering() { $rendered = '<< wheee >>'; - $mustache = new Mustache; - $template = new TemplateStub($mustache); + $mustache = new Mustache_Mustache; + $template = new Mustache_Test_TemplateStub($mustache); $template->rendered = $rendered; - $context = new Context; + $context = new Mustache_Context; $this->assertEquals($rendered, $template()); $this->assertEquals($rendered, $template->render()); @@ -39,14 +33,14 @@ class TemplateTest extends \PHPUnit_Framework_TestCase { } } -class TemplateStub extends Template { +class Mustache_Test_TemplateStub extends Mustache_Template { public $rendered; public function getMustache() { return $this->mustache; } - public function renderInternal(Context $context, $indent = '', $escape = false) { + public function renderInternal(Mustache_Context $context, $indent = '', $escape = false) { return $this->rendered; } } diff --git a/test/Mustache/Test/TokenizerTest.php b/test/Mustache/Test/TokenizerTest.php index 6782a87..654af82 100644 --- a/test/Mustache/Test/TokenizerTest.php +++ b/test/Mustache/Test/TokenizerTest.php @@ -9,20 +9,16 @@ * file that was distributed with this source code. */ -namespace Mustache\Test; - -use Mustache\Tokenizer; - /** * @group unit */ -class TokenizerTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { /** * @dataProvider getTokens */ public function testScan($text, $delimiters, $expected) { - $tokenizer = new Tokenizer; + $tokenizer = new Mustache_Tokenizer; $this->assertSame($expected, $tokenizer->scan($text, $delimiters)); } @@ -45,11 +41,11 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { null, array( array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name', - Tokenizer::OTAG => '{{', - Tokenizer::CTAG => '}}', - Tokenizer::INDEX => 10, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 10, ) ) ), @@ -65,11 +61,11 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { '<<< >>>', array( array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'name', - Tokenizer::OTAG => '<<<', - Tokenizer::CTAG => '>>>', - Tokenizer::INDEX => 12, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', + Mustache_Tokenizer::OTAG => '<<<', + Mustache_Tokenizer::CTAG => '>>>', + Mustache_Tokenizer::INDEX => 12, ) ) ), @@ -79,42 +75,42 @@ class TokenizerTest extends \PHPUnit_Framework_TestCase { null, array( array( - Tokenizer::TYPE => Tokenizer::T_UNESCAPED, - Tokenizer::NAME => 'a', - Tokenizer::OTAG => '{{', - Tokenizer::CTAG => '}}', - Tokenizer::INDEX => 8, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, + Mustache_Tokenizer::NAME => 'a', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 8, ), "\n", array( - Tokenizer::TYPE => Tokenizer::T_SECTION, - Tokenizer::NAME => 'b', - Tokenizer::OTAG => '{{', - Tokenizer::CTAG => '}}', - Tokenizer::INDEX => 18, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'b', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 18, ), null, array( - Tokenizer::TYPE => Tokenizer::T_ESCAPED, - Tokenizer::NAME => 'c', - Tokenizer::OTAG => '|', - Tokenizer::CTAG => '|', - Tokenizer::INDEX => 37, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'c', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 37, ), array( - Tokenizer::TYPE => Tokenizer::T_END_SECTION, - Tokenizer::NAME => 'b', - Tokenizer::OTAG => '|', - Tokenizer::CTAG => '|', - Tokenizer::INDEX => 37, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'b', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 37, ), "\n", array( - Tokenizer::TYPE => Tokenizer::T_UNESCAPED, - Tokenizer::NAME => 'd', - Tokenizer::OTAG => '|', - Tokenizer::CTAG => '|', - Tokenizer::INDEX => 51, + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, + Mustache_Tokenizer::NAME => 'd', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 51, ), ) diff --git a/test/bootstrap.php b/test/bootstrap.php index e7c9838..fd1386a 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -10,6 +10,6 @@ */ require __DIR__.'/../src/Mustache/Autoloader.php'; -\Mustache\Autoloader::register(); +Mustache_Autoloader::register(); require __DIR__.'/../vendor/yaml/lib/sfYamlParser.php'; diff --git a/test/fixtures/autoloader/Mustache/Bar.php b/test/fixtures/autoloader/Mustache/Bar.php index dd89a31..1df3265 100644 --- a/test/fixtures/autoloader/Mustache/Bar.php +++ b/test/fixtures/autoloader/Mustache/Bar.php @@ -9,8 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache; - -class Bar { +class Mustache_Bar { // nada } diff --git a/test/fixtures/autoloader/Mustache/Foo.php b/test/fixtures/autoloader/Mustache/Foo.php index aaebcae..9cf31a2 100644 --- a/test/fixtures/autoloader/Mustache/Foo.php +++ b/test/fixtures/autoloader/Mustache/Foo.php @@ -9,8 +9,6 @@ * file that was distributed with this source code. */ -namespace Mustache; - -class Foo { +class Mustache_Foo { // nada } From 550da214552b632c2ac672202668458f512c0fd9 Mon Sep 17 00:00:00 2001 From: scribu Date: Thu, 1 Mar 2012 14:33:15 -0800 Subject: [PATCH 28/58] replace __DIR__ with dirname(__FILE__) --- src/Mustache/Autoloader.php | 6 +++--- src/Mustache/Loader/FilesystemLoader.php | 10 +++++----- src/Mustache/Mustache.php | 8 ++++---- test/Mustache/Test/AutoloaderTest.php | 2 +- test/Mustache/Test/Functional/ExamplesTest.php | 2 +- test/Mustache/Test/Functional/MustacheSpecTest.php | 4 ++-- test/Mustache/Test/Loader/FilesystemLoaderTest.php | 8 ++++---- test/bootstrap.php | 4 ++-- 8 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index 5858262..63c3b52 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -19,16 +19,16 @@ class Mustache_Autoloader { /** * Autoloader constructor. * - * @param string $baseDir Mustache library base directory (default: __DIR__.'/..') + * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') */ public function __construct($baseDir = null) { - $this->baseDir = rtrim($baseDir, '/') ?: __DIR__.'/..'; + $this->baseDir = rtrim($baseDir, '/') ?: dirname(__FILE__).'/..'; } /** * Register a new instance as an SPL autoloader. * - * @param string $baseDir Mustache library base directory (default: __DIR__.'/..') + * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') * * @return Mustache_Autoloader Registered Autoloader instance */ diff --git a/src/Mustache/Loader/FilesystemLoader.php b/src/Mustache/Loader/FilesystemLoader.php index 28ed564..ecb98c8 100644 --- a/src/Mustache/Loader/FilesystemLoader.php +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -14,14 +14,14 @@ * * An ArrayLoader instance loads Mustache Template source from the filesystem by name: * - * $loader = new FilesystemLoader(__DIR__.'/views'); - * $tpl = $loader->load('foo'); // equivalent to `file_get_contents(__DIR__.'/views/foo.mustache'); + * $loader = new FilesystemLoader(dirname(__FILE__).'/views'); + * $tpl = $loader->load('foo'); // equivalent to `file_get_contents(dirname(__FILE__).'/views/foo.mustache'); * * This is probably the most useful Mustache Loader implementation. It can be used for partials and normal Templates: * * $m = new Mustache(array( - * 'loader' => new FilesystemLoader(__DIR__.'/views'), - * 'partials_loader' => new FilesystemLoader(__DIR__.'/views/partials'), + * 'loader' => new FilesystemLoader(dirname(__FILE__).'/views'), + * 'partials_loader' => new FilesystemLoader(dirname(__FILE__).'/views/partials'), * )); * * @implements Loader @@ -61,7 +61,7 @@ class Mustache_Loader_FilesystemLoader implements Mustache_Loader { /** * Load a Template by name. * - * $loader = new FilesystemLoader(__DIR__.'/views'); + * $loader = new FilesystemLoader(dirname(__FILE__).'/views'); * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; * * @param string $name diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 472c6bb..1859d34 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -47,17 +47,17 @@ class Mustache_Mustache { * 'template_class_prefix' => '__MyTemplates_', * * // A cache directory for compiled templates. Mustache will not cache templates unless this is set - * 'cache' => __DIR__.'/tmp/cache/mustache', + * 'cache' => dirname(__FILE__).'/tmp/cache/mustache', * * // A Mustache template loader instance. Uses a StringLoader if not specified - * 'loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/views'), + * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), * * // A Mustache loader instance for partials. - * 'partials_loader' => new Mustache_Loader_FilesystemLoader(__DIR__.'/views/partials'), + * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), * * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as * // efficient or lazy as a Filesystem (or database) loader. - * 'partials' => array('foo' => file_get_contents(__DIR__.'/views/partials/foo.mustache')), + * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')), * * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order * // sections), or any other valid Mustache context value. They will be prepended to the context stack, diff --git a/test/Mustache/Test/AutoloaderTest.php b/test/Mustache/Test/AutoloaderTest.php index 9a4a358..4743e01 100644 --- a/test/Mustache/Test/AutoloaderTest.php +++ b/test/Mustache/Test/AutoloaderTest.php @@ -19,7 +19,7 @@ class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase { } public function testAutoloader() { - $loader = new Mustache_Autoloader(__DIR__.'/../../fixtures/autoloader'); + $loader = new Mustache_Autoloader(dirname(__FILE__).'/../../fixtures/autoloader'); $this->assertNull($loader->autoload('NonMustacheClass')); $this->assertFalse(class_exists('NonMustacheClass')); diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 46d6bd0..52fdbe1 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -46,7 +46,7 @@ class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase { * @return array */ public function getExamples() { - $path = realpath(__DIR__.'/../../../../examples'); + $path = realpath(dirname(__FILE__).'/../../../../examples'); $examples = array(); $handle = opendir($path); diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 2343fbd..e10d60c 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -28,7 +28,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa * simply to provide a 'skipped' test if the `spec` submodule isn't initialized. */ public function testSpecInitialized() { - if (!file_exists(__DIR__.'/../../../../vendor/spec/specs/')) { + if (!file_exists(dirname(__FILE__).'/../../../../vendor/spec/specs/')) { $this->markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); } } @@ -156,7 +156,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa * @return array */ private function loadSpec($name) { - $filename = __DIR__ . '/../../../../vendor/spec/specs/' . $name . '.yml'; + $filename = dirname(__FILE__) . '/../../../../vendor/spec/specs/' . $name . '.yml'; if (!file_exists($filename)) { return array(); } diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php index e158b45..b01b805 100644 --- a/test/Mustache/Test/Loader/FilesystemLoaderTest.php +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -14,14 +14,14 @@ */ class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); $loader = new Mustache_Loader_FilesystemLoader($baseDir, array('extension' => '.ms')); $this->assertEquals('alpha contents', $loader->load('alpha')); $this->assertEquals('beta contents', $loader->load('beta.ms')); } public function testLoadTemplates() { - $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); $loader = new Mustache_Loader_FilesystemLoader($baseDir); $this->assertEquals('one contents', $loader->load('one')); $this->assertEquals('two contents', $loader->load('two.mustache')); @@ -31,14 +31,14 @@ class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCa * @expectedException \RuntimeException */ public function testMissingBaseDirThrowsException() { - $loader = new Mustache_Loader_FilesystemLoader(__DIR__.'/not_a_directory'); + $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/not_a_directory'); } /** * @expectedException \InvalidArgumentException */ public function testMissingTemplateThrowsException() { - $baseDir = realpath(__DIR__.'/../../../fixtures/templates'); + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); $loader = new Mustache_Loader_FilesystemLoader($baseDir); $loader->load('fake'); diff --git a/test/bootstrap.php b/test/bootstrap.php index fd1386a..91f654a 100644 --- a/test/bootstrap.php +++ b/test/bootstrap.php @@ -9,7 +9,7 @@ * file that was distributed with this source code. */ -require __DIR__.'/../src/Mustache/Autoloader.php'; +require dirname(__FILE__).'/../src/Mustache/Autoloader.php'; Mustache_Autoloader::register(); -require __DIR__.'/../vendor/yaml/lib/sfYamlParser.php'; +require dirname(__FILE__).'/../vendor/yaml/lib/sfYamlParser.php'; From 139f6bd3bb2b01f9fba7a8f8256f384733f3d6c3 Mon Sep 17 00:00:00 2001 From: scribu Date: Thu, 1 Mar 2012 14:37:17 -0800 Subject: [PATCH 29/58] don't use ternary shorthand --- src/Mustache/Autoloader.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index 63c3b52..4e6822a 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -22,7 +22,8 @@ class Mustache_Autoloader { * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') */ public function __construct($baseDir = null) { - $this->baseDir = rtrim($baseDir, '/') ?: dirname(__FILE__).'/..'; + $baseDir = rtrim($baseDir, '/'); + $this->baseDir = $baseDir ? $basedir : dirname(__FILE__).'/..'; } /** From ad78639e602180a9f38d834a1f3fd21c41b6843d Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 1 Mar 2012 15:56:41 -0800 Subject: [PATCH 30/58] Make Autoloader constructor $baseDir manipulation a little more grokkable. --- src/Mustache/Autoloader.php | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index 4e6822a..dc39772 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -22,8 +22,11 @@ class Mustache_Autoloader { * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') */ public function __construct($baseDir = null) { - $baseDir = rtrim($baseDir, '/'); - $this->baseDir = $baseDir ? $basedir : dirname(__FILE__).'/..'; + if ($baseDir === null) { + $this->baseDir = dirname(__FILE__).'/..'; + } else { + $this->baseDir = rtrim($baseDir, '/'); + } } /** From 21d2b9b3924005bc62dd926b63682ac0c58f3f08 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 17 Mar 2012 23:08:43 -0700 Subject: [PATCH 31/58] Update composer for 5.2.x --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index a48498c..4e42da3 100644 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ } ], "require": { - "php": ">=5.3.0" + "php": ">=5.2.4" }, "autoload": { "psr-0": { "Mustache": "src/" } From 99a5e9b14a93c62287c9867302fbbe4d939eb8a1 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 24 Mar 2012 20:39:35 -0700 Subject: [PATCH 32/58] Per the spec, missing partials should be treated as an empty string. --- src/Mustache/Compiler.php | 6 +++++- src/Mustache/Mustache.php | 6 +++++- test/Mustache/Test/MustacheTest.php | 11 +++++++++++ 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 5c002d1..36596c6 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -221,7 +221,11 @@ class Mustache_Compiler { return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); } - const PARTIAL = '$buffer .= $this->mustache->loadPartial(%s)->renderInternal($context, %s);'; + const PARTIAL = ' + if ($partial = $this->mustache->loadPartial(%s)) { + $buffer .= $partial->renderInternal($context, %s); + } + '; /** * Generate Mustache Template partial call PHP source. diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 1859d34..8c92547 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -414,7 +414,11 @@ class Mustache_Mustache { * @return Mustache_Template */ public function loadPartial($name) { - return $this->loadSource($this->getPartialsLoader()->load($name)); + try { + return $this->loadSource($this->getPartialsLoader()->load($name)); + } catch (InvalidArgumentException $e) { + // If the named partial cannot be found, return null. + } } /** diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 8ff097d..ab7c8af 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -146,6 +146,17 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { $mustache->setPartials(array('foo' => '{{ foo }}')); } + public function testMissingPartialsTreatedAsEmptyString() { + $mustache = new Mustache_Mustache(array( + 'partials_loader' => new Mustache_Loader_ArrayLoader(array( + 'foo' => 'FOO', + 'baz' => 'BAZ', + )) + )); + + $this->assertEquals('FOOBAZ', $mustache->render('{{>foo}}{{>bar}}{{>baz}}', array())); + } + public function testHelpers() { $foo = function() { return 'foo'; }; $bar = 'BAR'; From 1430b27f86d0d2f6af504e24a907fe8af21551e5 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 26 Mar 2012 19:02:05 -0700 Subject: [PATCH 33/58] Move `examples` into the test fixtures. --- bin/create_example.php | 7 +++---- test/Mustache/Test/Functional/ExamplesTest.php | 10 ++++------ .../fixtures/examples}/child_context/ChildContext.php | 0 .../examples}/child_context/child_context.mustache | 0 .../fixtures/examples}/child_context/child_context.txt | 0 .../fixtures/examples}/comments/Comments.php | 0 .../fixtures/examples}/comments/comments.mustache | 0 .../fixtures/examples}/comments/comments.txt | 0 .../fixtures/examples}/complex/complex.mustache | 0 .../fixtures/examples}/complex/complex.php | 0 .../fixtures/examples}/complex/complex.txt | 0 .../fixtures/examples}/delimiters/Delimiters.php | 0 .../fixtures/examples}/delimiters/delimiters.mustache | 0 .../fixtures/examples}/delimiters/delimiters.txt | 0 .../fixtures/examples}/dot_notation/DotNotation.php | 0 .../examples}/dot_notation/dot_notation.mustache | 0 .../fixtures/examples}/dot_notation/dot_notation.txt | 0 .../examples}/double_section/DoubleSection.php | 0 .../examples}/double_section/double_section.mustache | 0 .../examples}/double_section/double_section.txt | 0 .../fixtures/examples}/escaped/Escaped.php | 0 .../fixtures/examples}/escaped/escaped.mustache | 0 .../fixtures/examples}/escaped/escaped.txt | 0 .../grand_parent_context/GrandParentContext.php | 0 .../grand_parent_context/grand_parent_context.mustache | 0 .../grand_parent_context/grand_parent_context.txt | 0 {examples => test/fixtures/examples}/i18n/I18n.php | 0 .../fixtures/examples}/i18n/i18n.mustache | 0 {examples => test/fixtures/examples}/i18n/i18n.txt | 0 .../examples}/implicit_iterator/ImplicitIterator.php | 0 .../implicit_iterator/implicit_iterator.mustache | 0 .../examples}/implicit_iterator/implicit_iterator.txt | 0 .../inverted_double_section/InvertedDoubleSection.php | 0 .../inverted_double_section.mustache | 0 .../inverted_double_section.txt | 0 .../examples}/inverted_section/InvertedSection.php | 0 .../inverted_section/inverted_section.mustache | 0 .../examples}/inverted_section/inverted_section.txt | 0 .../fixtures/examples}/partials/Partials.php | 0 .../fixtures/examples}/partials/partials.mustache | 0 .../fixtures/examples}/partials/partials.txt | 0 .../examples}/partials/partials/header.mustache | 0 .../examples}/recursive_partials/RecursivePartials.php | 0 .../recursive_partials/partials/child.mustache | 0 .../recursive_partials/recursive_partials.mustache | 0 .../recursive_partials/recursive_partials.txt | 0 .../SectionIteratorObjects.php | 0 .../section_iterator_objects.mustache | 0 .../section_iterator_objects.txt | 0 .../section_magic_objects/SectionMagicObjects.php | 0 .../section_magic_objects.mustache | 0 .../section_magic_objects/section_magic_objects.txt | 0 .../examples}/section_objects/SectionObjects.php | 0 .../examples}/section_objects/section_objects.mustache | 0 .../examples}/section_objects/section_objects.txt | 0 .../fixtures/examples}/sections/Sections.php | 0 .../fixtures/examples}/sections/sections.mustache | 0 .../fixtures/examples}/sections/sections.txt | 0 .../examples}/sections_nested/SectionsNested.php | 0 .../examples}/sections_nested/sections_nested.mustache | 0 .../examples}/sections_nested/sections_nested.txt | 0 {examples => test/fixtures/examples}/simple/Simple.php | 0 .../fixtures/examples}/simple/simple.mustache | 0 {examples => test/fixtures/examples}/simple/simple.txt | 0 .../fixtures/examples}/unescaped/Unescaped.php | 0 .../fixtures/examples}/unescaped/unescaped.mustache | 0 .../fixtures/examples}/unescaped/unescaped.txt | 0 {examples => test/fixtures/examples}/utf8/UTF8.php | 0 .../fixtures/examples}/utf8/utf8.mustache | 0 {examples => test/fixtures/examples}/utf8/utf8.txt | 0 .../examples}/utf8_unescaped/UTF8Unescaped.php | 0 .../examples}/utf8_unescaped/utf8_unescaped.mustache | 0 .../examples}/utf8_unescaped/utf8_unescaped.txt | 0 .../fixtures/examples}/whitespace/Whitespace.php | 0 .../examples}/whitespace/partials/alphabet.mustache | 0 .../fixtures/examples}/whitespace/whitespace.mustache | 0 .../fixtures/examples}/whitespace/whitespace.txt | 0 77 files changed, 7 insertions(+), 10 deletions(-) rename {examples => test/fixtures/examples}/child_context/ChildContext.php (100%) rename {examples => test/fixtures/examples}/child_context/child_context.mustache (100%) rename {examples => test/fixtures/examples}/child_context/child_context.txt (100%) rename {examples => test/fixtures/examples}/comments/Comments.php (100%) rename {examples => test/fixtures/examples}/comments/comments.mustache (100%) rename {examples => test/fixtures/examples}/comments/comments.txt (100%) rename {examples => test/fixtures/examples}/complex/complex.mustache (100%) rename {examples => test/fixtures/examples}/complex/complex.php (100%) rename {examples => test/fixtures/examples}/complex/complex.txt (100%) rename {examples => test/fixtures/examples}/delimiters/Delimiters.php (100%) rename {examples => test/fixtures/examples}/delimiters/delimiters.mustache (100%) rename {examples => test/fixtures/examples}/delimiters/delimiters.txt (100%) rename {examples => test/fixtures/examples}/dot_notation/DotNotation.php (100%) rename {examples => test/fixtures/examples}/dot_notation/dot_notation.mustache (100%) rename {examples => test/fixtures/examples}/dot_notation/dot_notation.txt (100%) rename {examples => test/fixtures/examples}/double_section/DoubleSection.php (100%) rename {examples => test/fixtures/examples}/double_section/double_section.mustache (100%) rename {examples => test/fixtures/examples}/double_section/double_section.txt (100%) rename {examples => test/fixtures/examples}/escaped/Escaped.php (100%) rename {examples => test/fixtures/examples}/escaped/escaped.mustache (100%) rename {examples => test/fixtures/examples}/escaped/escaped.txt (100%) rename {examples => test/fixtures/examples}/grand_parent_context/GrandParentContext.php (100%) rename {examples => test/fixtures/examples}/grand_parent_context/grand_parent_context.mustache (100%) rename {examples => test/fixtures/examples}/grand_parent_context/grand_parent_context.txt (100%) rename {examples => test/fixtures/examples}/i18n/I18n.php (100%) rename {examples => test/fixtures/examples}/i18n/i18n.mustache (100%) rename {examples => test/fixtures/examples}/i18n/i18n.txt (100%) rename {examples => test/fixtures/examples}/implicit_iterator/ImplicitIterator.php (100%) rename {examples => test/fixtures/examples}/implicit_iterator/implicit_iterator.mustache (100%) rename {examples => test/fixtures/examples}/implicit_iterator/implicit_iterator.txt (100%) rename {examples => test/fixtures/examples}/inverted_double_section/InvertedDoubleSection.php (100%) rename {examples => test/fixtures/examples}/inverted_double_section/inverted_double_section.mustache (100%) rename {examples => test/fixtures/examples}/inverted_double_section/inverted_double_section.txt (100%) rename {examples => test/fixtures/examples}/inverted_section/InvertedSection.php (100%) rename {examples => test/fixtures/examples}/inverted_section/inverted_section.mustache (100%) rename {examples => test/fixtures/examples}/inverted_section/inverted_section.txt (100%) rename {examples => test/fixtures/examples}/partials/Partials.php (100%) rename {examples => test/fixtures/examples}/partials/partials.mustache (100%) rename {examples => test/fixtures/examples}/partials/partials.txt (100%) rename {examples => test/fixtures/examples}/partials/partials/header.mustache (100%) rename {examples => test/fixtures/examples}/recursive_partials/RecursivePartials.php (100%) rename {examples => test/fixtures/examples}/recursive_partials/partials/child.mustache (100%) rename {examples => test/fixtures/examples}/recursive_partials/recursive_partials.mustache (100%) rename {examples => test/fixtures/examples}/recursive_partials/recursive_partials.txt (100%) rename {examples => test/fixtures/examples}/section_iterator_objects/SectionIteratorObjects.php (100%) rename {examples => test/fixtures/examples}/section_iterator_objects/section_iterator_objects.mustache (100%) rename {examples => test/fixtures/examples}/section_iterator_objects/section_iterator_objects.txt (100%) rename {examples => test/fixtures/examples}/section_magic_objects/SectionMagicObjects.php (100%) rename {examples => test/fixtures/examples}/section_magic_objects/section_magic_objects.mustache (100%) rename {examples => test/fixtures/examples}/section_magic_objects/section_magic_objects.txt (100%) rename {examples => test/fixtures/examples}/section_objects/SectionObjects.php (100%) rename {examples => test/fixtures/examples}/section_objects/section_objects.mustache (100%) rename {examples => test/fixtures/examples}/section_objects/section_objects.txt (100%) rename {examples => test/fixtures/examples}/sections/Sections.php (100%) rename {examples => test/fixtures/examples}/sections/sections.mustache (100%) rename {examples => test/fixtures/examples}/sections/sections.txt (100%) rename {examples => test/fixtures/examples}/sections_nested/SectionsNested.php (100%) rename {examples => test/fixtures/examples}/sections_nested/sections_nested.mustache (100%) rename {examples => test/fixtures/examples}/sections_nested/sections_nested.txt (100%) rename {examples => test/fixtures/examples}/simple/Simple.php (100%) rename {examples => test/fixtures/examples}/simple/simple.mustache (100%) rename {examples => test/fixtures/examples}/simple/simple.txt (100%) rename {examples => test/fixtures/examples}/unescaped/Unescaped.php (100%) rename {examples => test/fixtures/examples}/unescaped/unescaped.mustache (100%) rename {examples => test/fixtures/examples}/unescaped/unescaped.txt (100%) rename {examples => test/fixtures/examples}/utf8/UTF8.php (100%) rename {examples => test/fixtures/examples}/utf8/utf8.mustache (100%) rename {examples => test/fixtures/examples}/utf8/utf8.txt (100%) rename {examples => test/fixtures/examples}/utf8_unescaped/UTF8Unescaped.php (100%) rename {examples => test/fixtures/examples}/utf8_unescaped/utf8_unescaped.mustache (100%) rename {examples => test/fixtures/examples}/utf8_unescaped/utf8_unescaped.txt (100%) rename {examples => test/fixtures/examples}/whitespace/Whitespace.php (100%) rename {examples => test/fixtures/examples}/whitespace/partials/alphabet.mustache (100%) rename {examples => test/fixtures/examples}/whitespace/whitespace.mustache (100%) rename {examples => test/fixtures/examples}/whitespace/whitespace.txt (100%) diff --git a/bin/create_example.php b/bin/create_example.php index 0838b38..306eae0 100755 --- a/bin/create_example.php +++ b/bin/create_example.php @@ -22,8 +22,7 @@ This creates a new example and the corresponding files in the examples/ director USAGE ); -define('DS', DIRECTORY_SEPARATOR); -define('EXAMPLE_PATH', realpath(dirname(__FILE__) . DS . ".." . DS . "examples")); +define('EXAMPLE_PATH', realpath(dirname(__FILE__) . '/../test/fixtures/examples')); /** @@ -90,8 +89,8 @@ function out($value) { * @return string */ function buildPath($directory, $filename = null, $extension = null) { - return out(EXAMPLE_PATH . DS . $directory. - ($extension !== null && $filename !== null ? DS . $filename. "." . $extension : "")); + return out(EXAMPLE_PATH . '/' . $directory. + ($extension !== null && $filename !== null ? '/' . $filename. "." . $extension : "")); } /** diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 52fdbe1..32f0fa0 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -35,18 +35,16 @@ class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase { /** * Data provider for testExamples method. * - * Assumes that an `examples` directory exists inside parent directory. + * Loads examples from the test fixtures directory. + * * This examples directory should contain any number of subdirectories, each of which contains * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file - * (.txt). - * - * This whole mess will be refined later to be more intuitive and less prescriptive, but it'll - * do for now. Especially since it means we can have unit tests :) + * (.txt). Optionally, the directory may contain a folder full of partials. * * @return array */ public function getExamples() { - $path = realpath(dirname(__FILE__).'/../../../../examples'); + $path = realpath(dirname(__FILE__).'/../../../fixtures/examples'); $examples = array(); $handle = opendir($path); diff --git a/examples/child_context/ChildContext.php b/test/fixtures/examples/child_context/ChildContext.php similarity index 100% rename from examples/child_context/ChildContext.php rename to test/fixtures/examples/child_context/ChildContext.php diff --git a/examples/child_context/child_context.mustache b/test/fixtures/examples/child_context/child_context.mustache similarity index 100% rename from examples/child_context/child_context.mustache rename to test/fixtures/examples/child_context/child_context.mustache diff --git a/examples/child_context/child_context.txt b/test/fixtures/examples/child_context/child_context.txt similarity index 100% rename from examples/child_context/child_context.txt rename to test/fixtures/examples/child_context/child_context.txt diff --git a/examples/comments/Comments.php b/test/fixtures/examples/comments/Comments.php similarity index 100% rename from examples/comments/Comments.php rename to test/fixtures/examples/comments/Comments.php diff --git a/examples/comments/comments.mustache b/test/fixtures/examples/comments/comments.mustache similarity index 100% rename from examples/comments/comments.mustache rename to test/fixtures/examples/comments/comments.mustache diff --git a/examples/comments/comments.txt b/test/fixtures/examples/comments/comments.txt similarity index 100% rename from examples/comments/comments.txt rename to test/fixtures/examples/comments/comments.txt diff --git a/examples/complex/complex.mustache b/test/fixtures/examples/complex/complex.mustache similarity index 100% rename from examples/complex/complex.mustache rename to test/fixtures/examples/complex/complex.mustache diff --git a/examples/complex/complex.php b/test/fixtures/examples/complex/complex.php similarity index 100% rename from examples/complex/complex.php rename to test/fixtures/examples/complex/complex.php diff --git a/examples/complex/complex.txt b/test/fixtures/examples/complex/complex.txt similarity index 100% rename from examples/complex/complex.txt rename to test/fixtures/examples/complex/complex.txt diff --git a/examples/delimiters/Delimiters.php b/test/fixtures/examples/delimiters/Delimiters.php similarity index 100% rename from examples/delimiters/Delimiters.php rename to test/fixtures/examples/delimiters/Delimiters.php diff --git a/examples/delimiters/delimiters.mustache b/test/fixtures/examples/delimiters/delimiters.mustache similarity index 100% rename from examples/delimiters/delimiters.mustache rename to test/fixtures/examples/delimiters/delimiters.mustache diff --git a/examples/delimiters/delimiters.txt b/test/fixtures/examples/delimiters/delimiters.txt similarity index 100% rename from examples/delimiters/delimiters.txt rename to test/fixtures/examples/delimiters/delimiters.txt diff --git a/examples/dot_notation/DotNotation.php b/test/fixtures/examples/dot_notation/DotNotation.php similarity index 100% rename from examples/dot_notation/DotNotation.php rename to test/fixtures/examples/dot_notation/DotNotation.php diff --git a/examples/dot_notation/dot_notation.mustache b/test/fixtures/examples/dot_notation/dot_notation.mustache similarity index 100% rename from examples/dot_notation/dot_notation.mustache rename to test/fixtures/examples/dot_notation/dot_notation.mustache diff --git a/examples/dot_notation/dot_notation.txt b/test/fixtures/examples/dot_notation/dot_notation.txt similarity index 100% rename from examples/dot_notation/dot_notation.txt rename to test/fixtures/examples/dot_notation/dot_notation.txt diff --git a/examples/double_section/DoubleSection.php b/test/fixtures/examples/double_section/DoubleSection.php similarity index 100% rename from examples/double_section/DoubleSection.php rename to test/fixtures/examples/double_section/DoubleSection.php diff --git a/examples/double_section/double_section.mustache b/test/fixtures/examples/double_section/double_section.mustache similarity index 100% rename from examples/double_section/double_section.mustache rename to test/fixtures/examples/double_section/double_section.mustache diff --git a/examples/double_section/double_section.txt b/test/fixtures/examples/double_section/double_section.txt similarity index 100% rename from examples/double_section/double_section.txt rename to test/fixtures/examples/double_section/double_section.txt diff --git a/examples/escaped/Escaped.php b/test/fixtures/examples/escaped/Escaped.php similarity index 100% rename from examples/escaped/Escaped.php rename to test/fixtures/examples/escaped/Escaped.php diff --git a/examples/escaped/escaped.mustache b/test/fixtures/examples/escaped/escaped.mustache similarity index 100% rename from examples/escaped/escaped.mustache rename to test/fixtures/examples/escaped/escaped.mustache diff --git a/examples/escaped/escaped.txt b/test/fixtures/examples/escaped/escaped.txt similarity index 100% rename from examples/escaped/escaped.txt rename to test/fixtures/examples/escaped/escaped.txt diff --git a/examples/grand_parent_context/GrandParentContext.php b/test/fixtures/examples/grand_parent_context/GrandParentContext.php similarity index 100% rename from examples/grand_parent_context/GrandParentContext.php rename to test/fixtures/examples/grand_parent_context/GrandParentContext.php diff --git a/examples/grand_parent_context/grand_parent_context.mustache b/test/fixtures/examples/grand_parent_context/grand_parent_context.mustache similarity index 100% rename from examples/grand_parent_context/grand_parent_context.mustache rename to test/fixtures/examples/grand_parent_context/grand_parent_context.mustache diff --git a/examples/grand_parent_context/grand_parent_context.txt b/test/fixtures/examples/grand_parent_context/grand_parent_context.txt similarity index 100% rename from examples/grand_parent_context/grand_parent_context.txt rename to test/fixtures/examples/grand_parent_context/grand_parent_context.txt diff --git a/examples/i18n/I18n.php b/test/fixtures/examples/i18n/I18n.php similarity index 100% rename from examples/i18n/I18n.php rename to test/fixtures/examples/i18n/I18n.php diff --git a/examples/i18n/i18n.mustache b/test/fixtures/examples/i18n/i18n.mustache similarity index 100% rename from examples/i18n/i18n.mustache rename to test/fixtures/examples/i18n/i18n.mustache diff --git a/examples/i18n/i18n.txt b/test/fixtures/examples/i18n/i18n.txt similarity index 100% rename from examples/i18n/i18n.txt rename to test/fixtures/examples/i18n/i18n.txt diff --git a/examples/implicit_iterator/ImplicitIterator.php b/test/fixtures/examples/implicit_iterator/ImplicitIterator.php similarity index 100% rename from examples/implicit_iterator/ImplicitIterator.php rename to test/fixtures/examples/implicit_iterator/ImplicitIterator.php diff --git a/examples/implicit_iterator/implicit_iterator.mustache b/test/fixtures/examples/implicit_iterator/implicit_iterator.mustache similarity index 100% rename from examples/implicit_iterator/implicit_iterator.mustache rename to test/fixtures/examples/implicit_iterator/implicit_iterator.mustache diff --git a/examples/implicit_iterator/implicit_iterator.txt b/test/fixtures/examples/implicit_iterator/implicit_iterator.txt similarity index 100% rename from examples/implicit_iterator/implicit_iterator.txt rename to test/fixtures/examples/implicit_iterator/implicit_iterator.txt diff --git a/examples/inverted_double_section/InvertedDoubleSection.php b/test/fixtures/examples/inverted_double_section/InvertedDoubleSection.php similarity index 100% rename from examples/inverted_double_section/InvertedDoubleSection.php rename to test/fixtures/examples/inverted_double_section/InvertedDoubleSection.php diff --git a/examples/inverted_double_section/inverted_double_section.mustache b/test/fixtures/examples/inverted_double_section/inverted_double_section.mustache similarity index 100% rename from examples/inverted_double_section/inverted_double_section.mustache rename to test/fixtures/examples/inverted_double_section/inverted_double_section.mustache diff --git a/examples/inverted_double_section/inverted_double_section.txt b/test/fixtures/examples/inverted_double_section/inverted_double_section.txt similarity index 100% rename from examples/inverted_double_section/inverted_double_section.txt rename to test/fixtures/examples/inverted_double_section/inverted_double_section.txt diff --git a/examples/inverted_section/InvertedSection.php b/test/fixtures/examples/inverted_section/InvertedSection.php similarity index 100% rename from examples/inverted_section/InvertedSection.php rename to test/fixtures/examples/inverted_section/InvertedSection.php diff --git a/examples/inverted_section/inverted_section.mustache b/test/fixtures/examples/inverted_section/inverted_section.mustache similarity index 100% rename from examples/inverted_section/inverted_section.mustache rename to test/fixtures/examples/inverted_section/inverted_section.mustache diff --git a/examples/inverted_section/inverted_section.txt b/test/fixtures/examples/inverted_section/inverted_section.txt similarity index 100% rename from examples/inverted_section/inverted_section.txt rename to test/fixtures/examples/inverted_section/inverted_section.txt diff --git a/examples/partials/Partials.php b/test/fixtures/examples/partials/Partials.php similarity index 100% rename from examples/partials/Partials.php rename to test/fixtures/examples/partials/Partials.php diff --git a/examples/partials/partials.mustache b/test/fixtures/examples/partials/partials.mustache similarity index 100% rename from examples/partials/partials.mustache rename to test/fixtures/examples/partials/partials.mustache diff --git a/examples/partials/partials.txt b/test/fixtures/examples/partials/partials.txt similarity index 100% rename from examples/partials/partials.txt rename to test/fixtures/examples/partials/partials.txt diff --git a/examples/partials/partials/header.mustache b/test/fixtures/examples/partials/partials/header.mustache similarity index 100% rename from examples/partials/partials/header.mustache rename to test/fixtures/examples/partials/partials/header.mustache diff --git a/examples/recursive_partials/RecursivePartials.php b/test/fixtures/examples/recursive_partials/RecursivePartials.php similarity index 100% rename from examples/recursive_partials/RecursivePartials.php rename to test/fixtures/examples/recursive_partials/RecursivePartials.php diff --git a/examples/recursive_partials/partials/child.mustache b/test/fixtures/examples/recursive_partials/partials/child.mustache similarity index 100% rename from examples/recursive_partials/partials/child.mustache rename to test/fixtures/examples/recursive_partials/partials/child.mustache diff --git a/examples/recursive_partials/recursive_partials.mustache b/test/fixtures/examples/recursive_partials/recursive_partials.mustache similarity index 100% rename from examples/recursive_partials/recursive_partials.mustache rename to test/fixtures/examples/recursive_partials/recursive_partials.mustache diff --git a/examples/recursive_partials/recursive_partials.txt b/test/fixtures/examples/recursive_partials/recursive_partials.txt similarity index 100% rename from examples/recursive_partials/recursive_partials.txt rename to test/fixtures/examples/recursive_partials/recursive_partials.txt diff --git a/examples/section_iterator_objects/SectionIteratorObjects.php b/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php similarity index 100% rename from examples/section_iterator_objects/SectionIteratorObjects.php rename to test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php diff --git a/examples/section_iterator_objects/section_iterator_objects.mustache b/test/fixtures/examples/section_iterator_objects/section_iterator_objects.mustache similarity index 100% rename from examples/section_iterator_objects/section_iterator_objects.mustache rename to test/fixtures/examples/section_iterator_objects/section_iterator_objects.mustache diff --git a/examples/section_iterator_objects/section_iterator_objects.txt b/test/fixtures/examples/section_iterator_objects/section_iterator_objects.txt similarity index 100% rename from examples/section_iterator_objects/section_iterator_objects.txt rename to test/fixtures/examples/section_iterator_objects/section_iterator_objects.txt diff --git a/examples/section_magic_objects/SectionMagicObjects.php b/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php similarity index 100% rename from examples/section_magic_objects/SectionMagicObjects.php rename to test/fixtures/examples/section_magic_objects/SectionMagicObjects.php diff --git a/examples/section_magic_objects/section_magic_objects.mustache b/test/fixtures/examples/section_magic_objects/section_magic_objects.mustache similarity index 100% rename from examples/section_magic_objects/section_magic_objects.mustache rename to test/fixtures/examples/section_magic_objects/section_magic_objects.mustache diff --git a/examples/section_magic_objects/section_magic_objects.txt b/test/fixtures/examples/section_magic_objects/section_magic_objects.txt similarity index 100% rename from examples/section_magic_objects/section_magic_objects.txt rename to test/fixtures/examples/section_magic_objects/section_magic_objects.txt diff --git a/examples/section_objects/SectionObjects.php b/test/fixtures/examples/section_objects/SectionObjects.php similarity index 100% rename from examples/section_objects/SectionObjects.php rename to test/fixtures/examples/section_objects/SectionObjects.php diff --git a/examples/section_objects/section_objects.mustache b/test/fixtures/examples/section_objects/section_objects.mustache similarity index 100% rename from examples/section_objects/section_objects.mustache rename to test/fixtures/examples/section_objects/section_objects.mustache diff --git a/examples/section_objects/section_objects.txt b/test/fixtures/examples/section_objects/section_objects.txt similarity index 100% rename from examples/section_objects/section_objects.txt rename to test/fixtures/examples/section_objects/section_objects.txt diff --git a/examples/sections/Sections.php b/test/fixtures/examples/sections/Sections.php similarity index 100% rename from examples/sections/Sections.php rename to test/fixtures/examples/sections/Sections.php diff --git a/examples/sections/sections.mustache b/test/fixtures/examples/sections/sections.mustache similarity index 100% rename from examples/sections/sections.mustache rename to test/fixtures/examples/sections/sections.mustache diff --git a/examples/sections/sections.txt b/test/fixtures/examples/sections/sections.txt similarity index 100% rename from examples/sections/sections.txt rename to test/fixtures/examples/sections/sections.txt diff --git a/examples/sections_nested/SectionsNested.php b/test/fixtures/examples/sections_nested/SectionsNested.php similarity index 100% rename from examples/sections_nested/SectionsNested.php rename to test/fixtures/examples/sections_nested/SectionsNested.php diff --git a/examples/sections_nested/sections_nested.mustache b/test/fixtures/examples/sections_nested/sections_nested.mustache similarity index 100% rename from examples/sections_nested/sections_nested.mustache rename to test/fixtures/examples/sections_nested/sections_nested.mustache diff --git a/examples/sections_nested/sections_nested.txt b/test/fixtures/examples/sections_nested/sections_nested.txt similarity index 100% rename from examples/sections_nested/sections_nested.txt rename to test/fixtures/examples/sections_nested/sections_nested.txt diff --git a/examples/simple/Simple.php b/test/fixtures/examples/simple/Simple.php similarity index 100% rename from examples/simple/Simple.php rename to test/fixtures/examples/simple/Simple.php diff --git a/examples/simple/simple.mustache b/test/fixtures/examples/simple/simple.mustache similarity index 100% rename from examples/simple/simple.mustache rename to test/fixtures/examples/simple/simple.mustache diff --git a/examples/simple/simple.txt b/test/fixtures/examples/simple/simple.txt similarity index 100% rename from examples/simple/simple.txt rename to test/fixtures/examples/simple/simple.txt diff --git a/examples/unescaped/Unescaped.php b/test/fixtures/examples/unescaped/Unescaped.php similarity index 100% rename from examples/unescaped/Unescaped.php rename to test/fixtures/examples/unescaped/Unescaped.php diff --git a/examples/unescaped/unescaped.mustache b/test/fixtures/examples/unescaped/unescaped.mustache similarity index 100% rename from examples/unescaped/unescaped.mustache rename to test/fixtures/examples/unescaped/unescaped.mustache diff --git a/examples/unescaped/unescaped.txt b/test/fixtures/examples/unescaped/unescaped.txt similarity index 100% rename from examples/unescaped/unescaped.txt rename to test/fixtures/examples/unescaped/unescaped.txt diff --git a/examples/utf8/UTF8.php b/test/fixtures/examples/utf8/UTF8.php similarity index 100% rename from examples/utf8/UTF8.php rename to test/fixtures/examples/utf8/UTF8.php diff --git a/examples/utf8/utf8.mustache b/test/fixtures/examples/utf8/utf8.mustache similarity index 100% rename from examples/utf8/utf8.mustache rename to test/fixtures/examples/utf8/utf8.mustache diff --git a/examples/utf8/utf8.txt b/test/fixtures/examples/utf8/utf8.txt similarity index 100% rename from examples/utf8/utf8.txt rename to test/fixtures/examples/utf8/utf8.txt diff --git a/examples/utf8_unescaped/UTF8Unescaped.php b/test/fixtures/examples/utf8_unescaped/UTF8Unescaped.php similarity index 100% rename from examples/utf8_unescaped/UTF8Unescaped.php rename to test/fixtures/examples/utf8_unescaped/UTF8Unescaped.php diff --git a/examples/utf8_unescaped/utf8_unescaped.mustache b/test/fixtures/examples/utf8_unescaped/utf8_unescaped.mustache similarity index 100% rename from examples/utf8_unescaped/utf8_unescaped.mustache rename to test/fixtures/examples/utf8_unescaped/utf8_unescaped.mustache diff --git a/examples/utf8_unescaped/utf8_unescaped.txt b/test/fixtures/examples/utf8_unescaped/utf8_unescaped.txt similarity index 100% rename from examples/utf8_unescaped/utf8_unescaped.txt rename to test/fixtures/examples/utf8_unescaped/utf8_unescaped.txt diff --git a/examples/whitespace/Whitespace.php b/test/fixtures/examples/whitespace/Whitespace.php similarity index 100% rename from examples/whitespace/Whitespace.php rename to test/fixtures/examples/whitespace/Whitespace.php diff --git a/examples/whitespace/partials/alphabet.mustache b/test/fixtures/examples/whitespace/partials/alphabet.mustache similarity index 100% rename from examples/whitespace/partials/alphabet.mustache rename to test/fixtures/examples/whitespace/partials/alphabet.mustache diff --git a/examples/whitespace/whitespace.mustache b/test/fixtures/examples/whitespace/whitespace.mustache similarity index 100% rename from examples/whitespace/whitespace.mustache rename to test/fixtures/examples/whitespace/whitespace.mustache diff --git a/examples/whitespace/whitespace.txt b/test/fixtures/examples/whitespace/whitespace.txt similarity index 100% rename from examples/whitespace/whitespace.txt rename to test/fixtures/examples/whitespace/whitespace.txt From 2328615772f223ffabc6deaa62dcec8c4c90f0aa Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 26 Mar 2012 19:34:55 -0700 Subject: [PATCH 34/58] Change text tokens to proper tokens (instead of strings) --- src/Mustache/Compiler.php | 6 +++--- src/Mustache/Parser.php | 4 +--- src/Mustache/Tokenizer.php | 18 +++++++++------- test/Mustache/Test/CompilerTest.php | 17 ++++++++++----- test/Mustache/Test/ParserTest.php | 30 +++++++++++++++++++++------ test/Mustache/Test/TokenizerTest.php | 31 +++++++++++++++++++++++----- 6 files changed, 76 insertions(+), 30 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 36596c6..0ea567b 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -55,7 +55,7 @@ class Mustache_Compiler { $code = ''; $level++; foreach ($tree as $node) { - switch (is_string($node) ? 'text' : $node[Mustache_Tokenizer::TYPE]) { + switch ($node[Mustache_Tokenizer::TYPE]) { case Mustache_Tokenizer::T_SECTION: $code .= $this->section( $node[Mustache_Tokenizer::NODES], @@ -98,8 +98,8 @@ class Mustache_Compiler { break; - case 'text': - $code .= $this->text($node, $level); + case Mustache_Tokenizer::T_TEXT: + $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); break; default: diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index eb3c3b8..eb71859 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -46,7 +46,7 @@ class Mustache_Parser { if ($token === null) { continue; - } elseif (is_array($token)) { + } else { switch ($token[Mustache_Tokenizer::TYPE]) { case Mustache_Tokenizer::T_SECTION: case Mustache_Tokenizer::T_INVERTED: @@ -72,8 +72,6 @@ class Mustache_Parser { $nodes[] = $token; break; } - } else { - $nodes[] = $token; } } while ($tokens->valid()); diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index bafd2b0..2aff838 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -32,6 +32,7 @@ class Mustache_Tokenizer { const T_ESCAPED = '_v'; const T_UNESCAPED = '{'; const T_UNESCAPED_2 = '&'; + const T_TEXT = '_t'; // Valid token types private static $tagTypes = array( @@ -63,6 +64,7 @@ class Mustache_Tokenizer { const END = 'end'; const INDENT = 'indent'; const NODES = 'nodes'; + const VALUE = 'value'; private $state; private $tagType; @@ -187,7 +189,7 @@ class Mustache_Tokenizer { */ private function flushBuffer() { if (!empty($this->buffer)) { - $this->tokens[] = $this->buffer; + $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => $this->buffer); $this->buffer = ''; } } @@ -201,12 +203,12 @@ class Mustache_Tokenizer { $tokensCount = count($this->tokens); for ($j = $this->lineStart; $j < $tokensCount; $j++) { $token = $this->tokens[$j]; - if (is_array($token) && isset(self::$tagTypes[$token[self::TYPE]])) { + if (isset(self::$tagTypes[$token[self::TYPE]])) { if (isset(self::$interpolatedTags[$token[self::TYPE]])) { return false; } - } elseif (is_string($token)) { - if (preg_match('/\S/', $token)) { + } elseif ($token[self::TYPE] == self::T_TEXT) { + if (preg_match('/\S/', $token[self::VALUE])) { return false; } } @@ -225,16 +227,16 @@ class Mustache_Tokenizer { if ($this->seenTag && $this->lineIsWhitespace()) { $tokensCount = count($this->tokens); for ($j = $this->lineStart; $j < $tokensCount; $j++) { - if (!is_array($this->tokens[$j])) { - if (isset($this->tokens[$j+1]) && is_array($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { - $this->tokens[$j+1][self::INDENT] = (string) $this->tokens[$j]; + if ($this->tokens[$j][self::TYPE] == self::T_TEXT) { + if (isset($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { + $this->tokens[$j+1][self::INDENT] = $this->tokens[$j][self::VALUE]; } $this->tokens[$j] = null; } } } elseif (!$noNewLine) { - $this->tokens[] = "\n"; + $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => "\n"); } $this->seenTag = false; diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index 2984a1a..bd04a1e 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -34,14 +34,14 @@ class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { 'return $buffer;', )), - array('', array('TEXT'), 'Monkey', false, 'UTF-8', array( + array('', array($this->createTextToken('TEXT')), 'Monkey', false, 'UTF-8', array( "\nclass Monkey extends Mustache_Template", 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', '$buffer .= $indent . \'TEXT\';', 'return $buffer;', )), - array('', array('TEXT'), 'Monkey', true, 'ISO-8859-1', array( + array('', array($this->createTextToken('TEXT')), 'Monkey', true, 'ISO-8859-1', array( "\nclass Monkey extends Mustache_Template", '$buffer .= $indent . \'TEXT\';', 'return call_user_func($this->mustache->getEscape(), $buffer);', @@ -51,8 +51,8 @@ class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { array( '', array( - 'foo', - "\n", + $this->createTextToken('foo'), + $this->createTextToken("\n"), array( Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, Mustache_Tokenizer::NAME => 'name', @@ -61,7 +61,7 @@ class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, Mustache_Tokenizer::NAME => '.', ), - "'bar'", + $this->createTextToken("'bar'"), ), 'Monkey', false, @@ -88,4 +88,11 @@ class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { $compiler = new Mustache_Compiler; $compiler->compile('', array(array(Mustache_Tokenizer::TYPE => 'invalid')), 'SomeClass'); } + + private function createTextToken($value) { + return array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => $value, + ); + } } diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php index 9f4f3f4..52f65a2 100644 --- a/test/Mustache/Test/ParserTest.php +++ b/test/Mustache/Test/ParserTest.php @@ -32,8 +32,14 @@ class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { ), array( - array('text'), - array('text') + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text' + )), + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text' + )), ), array( @@ -49,7 +55,10 @@ class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { array( array( - 'foo', + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'foo' + ), array( Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, Mustache_Tokenizer::INDEX => 123, @@ -64,10 +73,16 @@ class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { Mustache_Tokenizer::INDEX => 456, Mustache_Tokenizer::NAME => 'parent' ), - 'bar', + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'bar' + ), ), array( - 'foo', + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'foo' + ), array( Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, Mustache_Tokenizer::NAME => 'parent', @@ -80,7 +95,10 @@ class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { ), ), ), - 'bar', + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'bar' + ), ), ), diff --git a/test/Mustache/Test/TokenizerTest.php b/test/Mustache/Test/TokenizerTest.php index 654af82..522668c 100644 --- a/test/Mustache/Test/TokenizerTest.php +++ b/test/Mustache/Test/TokenizerTest.php @@ -27,13 +27,23 @@ class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { array( 'text', null, - array('text'), + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text', + ), + ), ), array( 'text', '<<< >>>', - array('text'), + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text', + ), + ), ), array( @@ -53,7 +63,12 @@ class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { array( '{{ name }}', '<<< >>>', - array('{{ name }}'), + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => '{{ name }}', + ), + ), ), array( @@ -81,7 +96,10 @@ class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { Mustache_Tokenizer::CTAG => '}}', Mustache_Tokenizer::INDEX => 8, ), - "\n", + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => "\n", + ), array( Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, Mustache_Tokenizer::NAME => 'b', @@ -104,7 +122,10 @@ class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { Mustache_Tokenizer::CTAG => '|', Mustache_Tokenizer::INDEX => 37, ), - "\n", + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => "\n", + ), array( Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, Mustache_Tokenizer::NAME => 'd', From 8051acf8acb623faa57bb9e7dc4c78a0cb5c5919 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 3 Apr 2012 21:53:55 -0700 Subject: [PATCH 35/58] Switch submodules to use git:// repo urls. --- .gitmodules | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.gitmodules b/.gitmodules index 042ea4d..54f3a7b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,6 +1,6 @@ [submodule "vendor/spec"] path = vendor/spec - url = https://github.com/mustache/spec.git + url = git://github.com/mustache/spec.git [submodule "vendor/yaml"] path = vendor/yaml - url = https://github.com/fabpot/yaml.git + url = git://github.com/fabpot/yaml.git From cf14f042750ef2eddcf554d8dce862bc39cfcea0 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 30 Apr 2012 18:35:18 -0700 Subject: [PATCH 36/58] Add Travis CI config --- .travis.yml | 6 ++++++ 1 file changed, 6 insertions(+) create mode 100644 .travis.yml diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..94372d9 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,6 @@ +language: php +php: + - 5.3 + - 5.4 +before_install: + - git submodule update --init From 27a9b1ec72e30bf370a9227badbb33763e2f87c3 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 30 Apr 2012 18:43:16 -0700 Subject: [PATCH 37/58] Add Travis build status badge. --- README.markdown | 1 + 1 file changed, 1 insertion(+) diff --git a/README.markdown b/README.markdown index 3f545cd..4f1c0cb 100644 --- a/README.markdown +++ b/README.markdown @@ -3,6 +3,7 @@ Mustache.php A [Mustache](http://defunkt.github.com/mustache/) implementation in PHP. +[![Build Status](https://secure.travis-ci.org/bobthecow/mustache.php.png?branch=dev)](http://travis-ci.org/bobthecow/mustache.php) Usage ----- From f5137d2053d7d8dd2dfad3f870051044c297dc86 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 30 Apr 2012 22:51:52 -0700 Subject: [PATCH 38/58] Strictly speaking, the submodule init isn't necessary. --- .travis.yml | 2 -- 1 file changed, 2 deletions(-) diff --git a/.travis.yml b/.travis.yml index 94372d9..625062e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,5 +2,3 @@ language: php php: - 5.3 - 5.4 -before_install: - - git submodule update --init From 74e54cb68e0458c640b92039282e42839345305d Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 10:13:19 -0700 Subject: [PATCH 39/58] Mustache.php v2.0 will play well with PHP 5.2.x --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 625062e..1284d21 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,4 +1,5 @@ language: php php: + - 5.2 - 5.3 - 5.4 From 9316775ccb655620023d75e5c04dc8faddea2014 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 10:19:03 -0700 Subject: [PATCH 40/58] Fix test failures in PHP 5.2.x --- test/Mustache/Test/CompilerTest.php | 2 +- test/Mustache/Test/Functional/HigherOrderSectionsTest.php | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index bd04a1e..b508b02 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -12,7 +12,7 @@ /** * @group unit */ -class Mustache_Test_CompilerTest extends \PHPUnit_Framework_TestCase { +class Mustache_Test_CompilerTest extends PHPUnit_Framework_TestCase { /** * @dataProvider getCompileValues diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 8743551..eef60fd 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -22,6 +22,11 @@ class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework } public function testAnonymousFunctionSectionCallback() { + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + $this->markTestSkipped('Unable to test anonymous function section callbacks in PHP < 5.3'); + return; + } + $tpl = $this->mustache->loadTemplate('{{#wrapper}}{{name}}{{/wrapper}}'); $foo = new Mustache_Test_Functional_Foo; From d1912038f3a3b6bfadefbabafc19ae823cb639c4 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:03:11 -0700 Subject: [PATCH 41/58] Segregate 5.3+ tests, exclude them from phpunit config. --- phpunit.xml.dist | 3 +- .../Functional/HigherOrderSectionsTest.php | 71 +++++++++++ .../FiveThree/Functional/MustacheSpecTest.php | 114 ++++++++++++++++++ .../Functional/HigherOrderSectionsTest.php | 48 -------- .../Test/Functional/MustacheInjectionTest.php | 16 ++- .../Test/Functional/MustacheSpecTest.php | 35 ------ test/Mustache/Test/HelperCollectionTest.php | 10 +- test/Mustache/Test/MustacheTest.php | 14 ++- 8 files changed, 215 insertions(+), 96 deletions(-) create mode 100644 test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php create mode 100644 test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 8863a59..462675a 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,7 +1,8 @@ - ./test + ./test/Mustache/Test/FiveThree + ./test diff --git a/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php new file mode 100644 index 0000000..dc3a39a --- /dev/null +++ b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php @@ -0,0 +1,71 @@ +mustache = new Mustache_Mustache; + } + + public function testAnonymousFunctionSectionCallback() { + $tpl = $this->mustache->loadTemplate('{{#wrapper}}{{name}}{{/wrapper}}'); + + $foo = new Mustache_Test_FiveThree_Functional_Foo; + $foo->name = 'Mario'; + $foo->wrapper = function($text) { + return sprintf('
%s
', $text); + }; + + $this->assertEquals(sprintf('
%s
', $foo->name), $tpl->render($foo)); + } + + public function testSectionCallback() { + $one = $this->mustache->loadTemplate('{{name}}'); + $two = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); + + $foo = new Mustache_Test_FiveThree_Functional_Foo; + $foo->name = 'Luigi'; + + $this->assertEquals($foo->name, $one->render($foo)); + $this->assertEquals(sprintf('%s', $foo->name), $two->render($foo)); + } + + public function testViewArrayAnonymousSectionCallback() { + $tpl = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); + + $data = array( + 'name' => 'Bob', + 'wrap' => function($text) { + return sprintf('[[%s]]', $text); + } + ); + + $this->assertEquals(sprintf('[[%s]]', $data['name']), $tpl->render($data)); + } +} + +class Mustache_Test_FiveThree_Functional_Foo { + public $name = 'Justin'; + public $lorem = 'Lorem ipsum dolor sit amet,'; + public $wrap; + + public function __construct() { + $this->wrap = function($text) { + return sprintf('%s', $text); + }; + } +} diff --git a/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php b/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php new file mode 100644 index 0000000..686d2b2 --- /dev/null +++ b/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php @@ -0,0 +1,114 @@ +markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); + } + } + + /** + * @group lambdas + * @dataProvider loadLambdasSpec + */ + public function testLambdasSpec($desc, $source, $partials, $data, $expected) { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template($this->prepareLambdasSpec($data)), $desc); + } + + public function loadLambdasSpec() { + return $this->loadSpec('~lambdas'); + } + + /** + * Extract and lambdafy any 'lambda' values found in the $data array. + */ + private function prepareLambdasSpec($data) { + foreach ($data as $key => $val) { + if ($key === 'lambda') { + if (!isset($val['php'])) { + $this->markTestSkipped(sprintf('PHP lambda test not implemented for this test.')); + } + + $func = $val['php']; + $data[$key] = function($text = null) use ($func) { + return eval($func); + }; + } else if (is_array($val)) { + $data[$key] = $this->prepareLambdasSpec($val); + } + } + + return $data; + } + + /** + * Data provider for the mustache spec test. + * + * Loads YAML files from the spec and converts them to PHPisms. + * + * @access public + * @return array + */ + private function loadSpec($name) { + $filename = dirname(__FILE__) . '/../../../../../vendor/spec/specs/' . $name . '.yml'; + if (!file_exists($filename)) { + return array(); + } + + $data = array(); + $yaml = new sfYamlParser; + $file = file_get_contents($filename); + + // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. + if ($name === '~lambdas') { + $file = str_replace(" !code\n", "\n", $file); + } + + $spec = $yaml->parse($file); + + foreach ($spec['tests'] as $test) { + $data[] = array( + $test['name'] . ': ' . $test['desc'], + $test['template'], + isset($test['partials']) ? $test['partials'] : array(), + $test['data'], + $test['expected'], + ); + } + + return $data; + } + + private static function loadTemplate($source, $partials) { + self::$mustache->setPartials($partials); + + return self::$mustache->loadTemplate($source); + } +} diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index eef60fd..9c48dac 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -21,34 +21,6 @@ class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework $this->mustache = new Mustache_Mustache; } - public function testAnonymousFunctionSectionCallback() { - if (version_compare(PHP_VERSION, '5.3.0', '<')) { - $this->markTestSkipped('Unable to test anonymous function section callbacks in PHP < 5.3'); - return; - } - - $tpl = $this->mustache->loadTemplate('{{#wrapper}}{{name}}{{/wrapper}}'); - - $foo = new Mustache_Test_Functional_Foo; - $foo->name = 'Mario'; - $foo->wrapper = function($text) { - return sprintf('
%s
', $text); - }; - - $this->assertEquals(sprintf('
%s
', $foo->name), $tpl->render($foo)); - } - - public function testSectionCallback() { - $one = $this->mustache->loadTemplate('{{name}}'); - $two = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); - - $foo = new Mustache_Test_Functional_Foo; - $foo->name = 'Luigi'; - - $this->assertEquals($foo->name, $one->render($foo)); - $this->assertEquals(sprintf('%s', $foo->name), $two->render($foo)); - } - public function testRuntimeSectionCallback() { $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); @@ -80,19 +52,6 @@ class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework $this->assertEquals($data['name'], $tpl->render($data)); } - public function testViewArrayAnonymousSectionCallback() { - $tpl = $this->mustache->loadTemplate('{{#wrap}}{{name}}{{/wrap}}'); - - $data = array( - 'name' => 'Bob', - 'wrap' => function($text) { - return sprintf('[[%s]]', $text); - } - ); - - $this->assertEquals(sprintf('[[%s]]', $data['name']), $tpl->render($data)); - } - public function testMonsters() { $tpl = $this->mustache->loadTemplate('{{#title}}{{title}} {{/title}}{{name}}'); @@ -111,13 +70,6 @@ class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework class Mustache_Test_Functional_Foo { public $name = 'Justin'; public $lorem = 'Lorem ipsum dolor sit amet,'; - public $wrap; - - public function __construct() { - $this->wrap = function($text) { - return sprintf('%s', $text); - }; - } public function wrapWithEm($text) { return sprintf('%s', $text); diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index e16bd7f..add5b8d 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -110,9 +110,7 @@ class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_T $tpl = $this->mustache->loadTemplate('{{ a }}'); $data = array( - 'a' => function() { - return '{{ b }}'; - }, + 'a' => array($this, 'lambdaInterpolationCallback'), 'b' => '{{ c }}', 'c' => 'FAIL' ); @@ -120,17 +118,23 @@ class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_T $this->assertEquals('{{ c }}', $tpl->render($data)); } + public static function lambdaInterpolationCallback() { + return '{{ b }}'; + } + public function testLambdaSectionInjection() { $tpl = $this->mustache->loadTemplate('{{# a }}b{{/ a }}'); $data = array( - 'a' => function ($text) { - return '{{ ' . $text . ' }}'; - }, + 'a' => array($this, 'lambdaSectionCallback'), 'b' => '{{ c }}', 'c' => 'FAIL' ); $this->assertEquals('{{ c }}', $tpl->render($data)); } + + public static function lambdaSectionCallback($text) { + return '{{ ' . $text . ' }}'; + } } diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index e10d60c..25493f3 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -86,41 +86,6 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa return $this->loadSpec('inverted'); } - /** - * @group lambdas - * @dataProvider loadLambdasSpec - */ - public function testLambdasSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($this->prepareLambdasSpec($data)), $desc); - } - - public function loadLambdasSpec() { - return $this->loadSpec('~lambdas'); - } - - /** - * Extract and lambdafy any 'lambda' values found in the $data array. - */ - private function prepareLambdasSpec($data) { - foreach ($data as $key => $val) { - if ($key === 'lambda') { - if (!isset($val['php'])) { - $this->markTestSkipped(sprintf('PHP lambda test not implemented for this test.')); - } - - $func = $val['php']; - $data[$key] = function($text = null) use ($func) { - return eval($func); - }; - } else if (is_array($val)) { - $data[$key] = $this->prepareLambdasSpec($val); - } - } - - return $data; - } - /** * @group partials * @dataProvider loadPartialsSpec diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php index 1a643d4..ed3f393 100644 --- a/test/Mustache/Test/HelperCollectionTest.php +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -11,7 +11,7 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $foo = function() { echo 'foo'; }; + $foo = array($this, 'getFoo'); $bar = 'BAR'; $helpers = new Mustache_HelperCollection(array( @@ -23,8 +23,12 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { $this->assertSame($bar, $helpers->get('bar')); } + public static function getFoo() { + echo 'foo'; + } + public function testAccessorsAndMutators() { - $foo = function() { echo 'foo'; }; + $foo = array($this, 'getFoo'); $bar = 'BAR'; $helpers = new Mustache_HelperCollection; @@ -49,7 +53,7 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { } public function testMagicMethods() { - $foo = function() { echo 'foo'; }; + $foo = array($this, 'getFoo'); $bar = 'BAR'; $helpers = new Mustache_HelperCollection; diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index ab7c8af..4a23eb3 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -35,7 +35,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { 'foo' => '{{ foo }}', ), 'helpers' => array( - 'foo' => function() { return 'foo'; }, + 'foo' => array($this, 'getFoo'), 'bar' => 'BAR', ), 'escape' => 'strtoupper', @@ -53,6 +53,10 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { $this->assertFalse($mustache->hasHelper('baz')); } + public static function getFoo() { + return 'foo'; + } + public function testRender() { $source = '{{ foo }}'; $data = array('bar' => 'baz'); @@ -158,7 +162,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } public function testHelpers() { - $foo = function() { return 'foo'; }; + $foo = array($this, 'getFoo'); $bar = 'BAR'; $mustache = new Mustache_Mustache(array('helpers' => array( 'foo' => $foo, @@ -178,7 +182,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { $mustache->addHelper('bar', $bar); $this->assertSame($bar, $mustache->getHelper('bar')); - $baz = function($text) { return '__'.$text.'__'; }; + $baz = array($this, 'wrapWithUnderscores'); $this->assertFalse($mustache->hasHelper('baz')); $this->assertFalse($helpers->has('baz')); @@ -192,6 +196,10 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { $this->assertEquals('foo - BAR - __qux__', $tpl->render(array('qux' => "won't mess things up"))); } + public static function wrapWithUnderscores($text) { + return '__'.$text.'__'; + } + /** * @expectedException \InvalidArgumentException */ From 291ca6d4cbe1e1fad5d9d267255c7f153bc0ca36 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:05:50 -0700 Subject: [PATCH 42/58] Update the test suite config to actually exclude FiveThree --- phpunit.xml.dist | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 462675a..3c620b6 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,8 +1,12 @@ - ./test/Mustache/Test/FiveThree ./test + ./test/Mustache/Test/FiveThree + + + + ./test/Mustache/Test/FiveThree From a47289607ddef757e9c4913c251f40f9c10fa76f Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:08:14 -0700 Subject: [PATCH 43/58] Templates are only callable in 5.3+ --- test/Mustache/Test/Functional/MustacheSpecTest.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 25493f3..39f9536 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -39,7 +39,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testCommentSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadCommentSpec() { @@ -52,7 +52,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testDelimitersSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadDelimitersSpec() { @@ -65,7 +65,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testInterpolationSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadInterpolationSpec() { @@ -79,7 +79,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testInvertedSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadInvertedSpec() { @@ -92,7 +92,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testPartialsSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadPartialsSpec() { @@ -105,7 +105,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa */ public function testSectionsSpec($desc, $source, $partials, $data, $expected) { $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template($data), $desc); + $this->assertEquals($expected, $template->render($data), $desc); } public function loadSectionsSpec() { From 36fbb28387060c54838f1a9e9a7fe3be543503de Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:20:11 -0700 Subject: [PATCH 44/58] Remove namespace from exception. --- src/Mustache/Mustache.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Mustache/Mustache.php b/src/Mustache/Mustache.php index 8c92547..b65f0f3 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Mustache.php @@ -104,7 +104,7 @@ class Mustache_Mustache { if (isset($options['escape'])) { if (!is_callable($options['escape'])) { - throw new \InvalidArgumentException('Mustache Constructor "escape" option must be callable'); + throw new InvalidArgumentException('Mustache Constructor "escape" option must be callable'); } $this->escape = $options['escape']; From 01351077692ff1f3b2cd25f4812aee5e131259f3 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:20:26 -0700 Subject: [PATCH 45/58] Only PHP >= 5.3.0 can call templates directly. --- test/Mustache/Test/TemplateTest.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php index 2b0999d..4f26fbc 100644 --- a/test/Mustache/Test/TemplateTest.php +++ b/test/Mustache/Test/TemplateTest.php @@ -26,7 +26,10 @@ class Mustache_Test_TemplateTest extends PHPUnit_Framework_TestCase { $template->rendered = $rendered; $context = new Mustache_Context; - $this->assertEquals($rendered, $template()); + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + $this->assertEquals($rendered, $template()); + } + $this->assertEquals($rendered, $template->render()); $this->assertEquals($rendered, $template->renderInternal($context)); $this->assertEquals($rendered, $template->render(array('foo' => 'bar'))); From 1ffd7c1a8fd9b3a41312730184522c974ae2b721 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 14:25:02 -0700 Subject: [PATCH 46/58] Remove some more slashes for 5.2. --- test/Mustache/Test/HelperCollectionTest.php | 10 +++++----- test/Mustache/Test/Loader/ArrayLoaderTest.php | 2 +- test/Mustache/Test/Loader/FilesystemLoaderTest.php | 4 ++-- test/Mustache/Test/MustacheTest.php | 6 +++--- test/Mustache/Test/ParserTest.php | 2 +- 5 files changed, 12 insertions(+), 12 deletions(-) diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php index ed3f393..5c66bd5 100644 --- a/test/Mustache/Test/HelperCollectionTest.php +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -105,12 +105,12 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { array( 'not helpers', array(), - '\InvalidArgumentException', + 'InvalidArgumentException', ), array( array(), array('get' => array('foo')), - '\InvalidArgumentException', + 'InvalidArgumentException', ), array( array('foo' => 'FOO'), @@ -120,7 +120,7 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { array( array('foo' => 'FOO'), array('get' => array('bar')), - '\InvalidArgumentException', + 'InvalidArgumentException', ), array( array('foo' => 'FOO'), @@ -144,12 +144,12 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { 'remove' => array('foo'), 'get' => array('foo'), ), - '\InvalidArgumentException', + 'InvalidArgumentException', ), array( array(), array('remove' => array('foo')), - '\InvalidArgumentException', + 'InvalidArgumentException', ), ); } diff --git a/test/Mustache/Test/Loader/ArrayLoaderTest.php b/test/Mustache/Test/Loader/ArrayLoaderTest.php index c5d53a1..0f659da 100644 --- a/test/Mustache/Test/Loader/ArrayLoaderTest.php +++ b/test/Mustache/Test/Loader/ArrayLoaderTest.php @@ -39,7 +39,7 @@ class Mustache_Test_Loader_ArrayLoaderTest extends PHPUnit_Framework_TestCase { } /** - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function testMissingTemplatesThrowExceptions() { $loader = new Mustache_Loader_ArrayLoader; diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php index b01b805..670274f 100644 --- a/test/Mustache/Test/Loader/FilesystemLoaderTest.php +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -28,14 +28,14 @@ class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCa } /** - * @expectedException \RuntimeException + * @expectedException RuntimeException */ public function testMissingBaseDirThrowsException() { $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/not_a_directory'); } /** - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function testMissingTemplateThrowsException() { $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/MustacheTest.php index 4a23eb3..3aa225b 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/MustacheTest.php @@ -125,7 +125,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } /** - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException * @dataProvider getBadEscapers */ public function testNonCallableEscapeThrowsException($escape) { @@ -140,7 +140,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } /** - * @expectedException \RuntimeException + * @expectedException RuntimeException */ public function testImmutablePartialsLoadersThrowException() { $mustache = new Mustache_Mustache(array( @@ -201,7 +201,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } /** - * @expectedException \InvalidArgumentException + * @expectedException InvalidArgumentException */ public function testSetHelpersThrowsExceptions() { $mustache = new Mustache_Mustache; diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php index 52f65a2..192b8aa 100644 --- a/test/Mustache/Test/ParserTest.php +++ b/test/Mustache/Test/ParserTest.php @@ -107,7 +107,7 @@ class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { /** * @dataProvider getBadParseTrees - * @expectedException \LogicException + * @expectedException LogicException */ public function testParserThrowsExceptions($tokens) { $parser = new Mustache_Parser; From be5cfb3e9ec90c2296e883d020660c8ae629924e Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Tue, 1 May 2012 21:30:22 -0700 Subject: [PATCH 47/58] Rename Mustache_Mustache to Mustache_Engine. Because the former was just too absurd to keep typing. --- README.markdown | 4 ++-- src/Mustache/{Mustache.php => Engine.php} | 20 +++++++++---------- src/Mustache/Loader/ArrayLoader.php | 2 +- src/Mustache/Template.php | 8 ++++---- .../Test/{MustacheTest.php => EngineTest.php} | 20 +++++++++---------- .../Functional/HigherOrderSectionsTest.php | 2 +- .../FiveThree/Functional/MustacheSpecTest.php | 2 +- test/Mustache/Test/Functional/CallTest.php | 2 +- .../Mustache/Test/Functional/ExamplesTest.php | 2 +- .../Functional/HigherOrderSectionsTest.php | 2 +- .../Test/Functional/MustacheInjectionTest.php | 2 +- .../Test/Functional/MustacheSpecTest.php | 2 +- .../Test/Functional/ObjectSectionTest.php | 2 +- test/Mustache/Test/TemplateTest.php | 4 ++-- 14 files changed, 37 insertions(+), 37 deletions(-) rename src/Mustache/{Mustache.php => Engine.php} (97%) rename test/Mustache/Test/{MustacheTest.php => EngineTest.php} (92%) diff --git a/README.markdown b/README.markdown index 4f1c0cb..86cebfa 100644 --- a/README.markdown +++ b/README.markdown @@ -12,7 +12,7 @@ A quick example: ```php render('Hello {{planet}}', array('planet' => 'World!')); // "Hello World!" ``` @@ -49,7 +49,7 @@ And render it: ```php render($template, $chris); ``` diff --git a/src/Mustache/Mustache.php b/src/Mustache/Engine.php similarity index 97% rename from src/Mustache/Mustache.php rename to src/Mustache/Engine.php index b65f0f3..a772800 100644 --- a/src/Mustache/Mustache.php +++ b/src/Mustache/Engine.php @@ -21,7 +21,7 @@ * * @author Justin Hileman {@link http://justinhileman.com} */ -class Mustache_Mustache { +class Mustache_Engine { const VERSION = '2.0.0-dev'; const SPEC_VERSION = '1.1.2'; @@ -120,7 +120,7 @@ class Mustache_Mustache { * * Equivalent to calling `$mustache->loadTemplate($template)->render($data);` * - * @see Mustache_Mustache::loadTemplate + * @see Mustache_Engine::loadTemplate * @see Mustache_Template::render * * @param string $template @@ -242,7 +242,7 @@ class Mustache_Mustache { /** * Get the current set of Mustache helpers. * - * @see Mustache_Mustache::setHelpers + * @see Mustache_Engine::setHelpers * * @return Mustache_HelperCollection */ @@ -257,7 +257,7 @@ class Mustache_Mustache { /** * Add a new Mustache helper. * - * @see Mustache_Mustache::setHelpers + * @see Mustache_Engine::setHelpers * * @param string $name * @param mixed $helper @@ -269,7 +269,7 @@ class Mustache_Mustache { /** * Get a Mustache helper by name. * - * @see Mustache_Mustache::setHelpers + * @see Mustache_Engine::setHelpers * * @param string $name * @@ -282,7 +282,7 @@ class Mustache_Mustache { /** * Check whether this Mustache instance has a helper. * - * @see Mustache_Mustache::setHelpers + * @see Mustache_Engine::setHelpers * * @param string $name * @@ -295,7 +295,7 @@ class Mustache_Mustache { /** * Remove a helper by name. * - * @see Mustache_Mustache::setHelpers + * @see Mustache_Engine::setHelpers * * @param string $name */ @@ -443,9 +443,9 @@ class Mustache_Mustache { /** * Instantiate and return a Mustache Template instance by source. * - * @see Mustache_Mustache::loadTemplate - * @see Mustache_Mustache::loadPartial - * @see Mustache_Mustache::loadLambda + * @see Mustache_Engine::loadTemplate + * @see Mustache_Engine::loadPartial + * @see Mustache_Engine::loadLambda * * @param string $source * diff --git a/src/Mustache/Loader/ArrayLoader.php b/src/Mustache/Loader/ArrayLoader.php index 883b5ae..9def8b5 100644 --- a/src/Mustache/Loader/ArrayLoader.php +++ b/src/Mustache/Loader/ArrayLoader.php @@ -21,7 +21,7 @@ * * $tpl = $loader->load('foo'); // '{{ bar }}' * - * The ArrayLoader is used internally as a partials loader by Mustache_Mustache instance when an array of partials + * The ArrayLoader is used internally as a partials loader by Mustache_Engine instance when an array of partials * is set. It can also be used as a quick-and-dirty Template loader. * * @implements Loader diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 97be3b9..5ec4d51 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -17,23 +17,23 @@ abstract class Mustache_Template { /** - * @var Mustache_Mustache + * @var Mustache_Engine */ protected $mustache; /** * Mustache Template constructor. * - * @param Mustache_Mustache $mustache + * @param Mustache_Engine $mustache */ - public function __construct(Mustache_Mustache $mustache) { + public function __construct(Mustache_Engine $mustache) { $this->mustache = $mustache; } /** * Mustache Template instances can be treated as a function and rendered by simply calling them: * - * $m = new Mustache_Mustache; + * $m = new Mustache_Engine; * $tpl = $m->loadTemplate('Hello, {{ name }}!'); * echo $tpl(array('name' => 'World')); // "Hello, World!" * diff --git a/test/Mustache/Test/MustacheTest.php b/test/Mustache/Test/EngineTest.php similarity index 92% rename from test/Mustache/Test/MustacheTest.php rename to test/Mustache/Test/EngineTest.php index 3aa225b..0e299fe 100644 --- a/test/Mustache/Test/MustacheTest.php +++ b/test/Mustache/Test/EngineTest.php @@ -12,7 +12,7 @@ /** * @group unit */ -class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_EngineTest extends PHPUnit_Framework_TestCase { private static $tempDir; @@ -26,7 +26,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { public function testConstructor() { $loader = new Mustache_Loader_StringLoader; $partialsLoader = new Mustache_Loader_ArrayLoader; - $mustache = new Mustache_Mustache(array( + $mustache = new Mustache_Engine(array( 'template_class_prefix' => '__whot__', 'cache' => self::$tempDir, 'loader' => $loader, @@ -83,7 +83,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { $tokenizer = new Mustache_Tokenizer; $parser = new Mustache_Parser; $compiler = new Mustache_Compiler; - $mustache = new Mustache_Mustache; + $mustache = new Mustache_Engine; $this->assertNotSame($loader, $mustache->getLoader()); $mustache->setLoader($loader); @@ -110,7 +110,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { * @group functional */ public function testCache() { - $mustache = new Mustache_Mustache(array( + $mustache = new Mustache_Engine(array( 'template_class_prefix' => '__whot__', 'cache' => self::$tempDir, )); @@ -129,7 +129,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { * @dataProvider getBadEscapers */ public function testNonCallableEscapeThrowsException($escape) { - new Mustache_Mustache(array('escape' => $escape)); + new Mustache_Engine(array('escape' => $escape)); } public function getBadEscapers() { @@ -143,7 +143,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { * @expectedException RuntimeException */ public function testImmutablePartialsLoadersThrowException() { - $mustache = new Mustache_Mustache(array( + $mustache = new Mustache_Engine(array( 'partials_loader' => new Mustache_Loader_StringLoader, )); @@ -151,7 +151,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } public function testMissingPartialsTreatedAsEmptyString() { - $mustache = new Mustache_Mustache(array( + $mustache = new Mustache_Engine(array( 'partials_loader' => new Mustache_Loader_ArrayLoader(array( 'foo' => 'FOO', 'baz' => 'BAZ', @@ -164,7 +164,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { public function testHelpers() { $foo = array($this, 'getFoo'); $bar = 'BAR'; - $mustache = new Mustache_Mustache(array('helpers' => array( + $mustache = new Mustache_Engine(array('helpers' => array( 'foo' => $foo, 'bar' => $bar, ))); @@ -204,7 +204,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { * @expectedException InvalidArgumentException */ public function testSetHelpersThrowsExceptions() { - $mustache = new Mustache_Mustache; + $mustache = new Mustache_Engine; $mustache->setHelpers('monkeymonkeymonkey'); } @@ -229,7 +229,7 @@ class Mustache_Test_MustacheTest extends PHPUnit_Framework_TestCase { } } -class MustacheStub extends Mustache_Mustache { +class MustacheStub extends Mustache_Engine { public $source; public $template; public function loadTemplate($source) { diff --git a/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php index dc3a39a..8453c93 100644 --- a/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php @@ -18,7 +18,7 @@ class Mustache_Test_FiveThree_Functional_HigherOrderSectionsTest extends PHPUnit private $mustache; public function setUp() { - $this->mustache = new Mustache_Mustache; + $this->mustache = new Mustache_Engine; } public function testAnonymousFunctionSectionCallback() { diff --git a/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php b/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php index 686d2b2..cf26ae1 100644 --- a/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/FiveThree/Functional/MustacheSpecTest.php @@ -20,7 +20,7 @@ class Mustache_Test_FiveThree_Functional_MustacheSpecTest extends PHPUnit_Framew private static $mustache; public static function setUpBeforeClass() { - self::$mustache = new Mustache_Mustache; + self::$mustache = new Mustache_Engine; } /** diff --git a/test/Mustache/Test/Functional/CallTest.php b/test/Mustache/Test/Functional/CallTest.php index bb89e43..8658490 100644 --- a/test/Mustache/Test/Functional/CallTest.php +++ b/test/Mustache/Test/Functional/CallTest.php @@ -16,7 +16,7 @@ class Mustache_Test_Functional_CallTest extends PHPUnit_Framework_TestCase { public function testCallEatsContext() { - $m = new Mustache_Mustache; + $m = new Mustache_Engine; $tpl = $m->loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); $foo = new Mustache_Test_Functional_ClassWithCall(); diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index 32f0fa0..a16e459 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -26,7 +26,7 @@ class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase { * @param string $expected */ public function testExamples($context, $source, $partials, $expected) { - $mustache = new Mustache_Mustache(array( + $mustache = new Mustache_Engine(array( 'partials' => $partials )); $this->assertEquals($expected, $mustache->loadTemplate($source)->render($context)); diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 9c48dac..22bab17 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -18,7 +18,7 @@ class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework private $mustache; public function setUp() { - $this->mustache = new Mustache_Mustache; + $this->mustache = new Mustache_Engine; } public function testRuntimeSectionCallback() { diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index add5b8d..679cd47 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -18,7 +18,7 @@ class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_T private $mustache; public function setUp() { - $this->mustache = new Mustache_Mustache; + $this->mustache = new Mustache_Engine; } // interpolation diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 39f9536..67bbb73 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -20,7 +20,7 @@ class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCa private static $mustache; public static function setUpBeforeClass() { - self::$mustache = new Mustache_Mustache; + self::$mustache = new Mustache_Engine; } /** diff --git a/test/Mustache/Test/Functional/ObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php index e9decf0..a8995a1 100644 --- a/test/Mustache/Test/Functional/ObjectSectionTest.php +++ b/test/Mustache/Test/Functional/ObjectSectionTest.php @@ -17,7 +17,7 @@ class Mustache_Test_Functional_ObjectSectionTest extends PHPUnit_Framework_TestC private $mustache; public function setUp() { - $this->mustache = new Mustache_Mustache; + $this->mustache = new Mustache_Engine; } public function testBasicObject() { diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php index 4f26fbc..69ce3f6 100644 --- a/test/Mustache/Test/TemplateTest.php +++ b/test/Mustache/Test/TemplateTest.php @@ -14,14 +14,14 @@ */ class Mustache_Test_TemplateTest extends PHPUnit_Framework_TestCase { public function testConstructor() { - $mustache = new Mustache_Mustache; + $mustache = new Mustache_Engine; $template = new Mustache_Test_TemplateStub($mustache); $this->assertSame($mustache, $template->getMustache()); } public function testRendering() { $rendered = '<< wheee >>'; - $mustache = new Mustache_Mustache; + $mustache = new Mustache_Engine; $template = new Mustache_Test_TemplateStub($mustache); $template->rendered = $rendered; $context = new Mustache_Context; From 2448992cc88553c0395c64cc3cded8307f97b384 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Sat, 24 Mar 2012 14:12:20 -0700 Subject: [PATCH 48/58] Update to proposed PSR-1 coding standard. * 4 space (no tab) indent * K&R-style braces --- bin/create_example.php | 66 +- src/Mustache/Autoloader.php | 90 +- src/Mustache/Compiler.php | 627 +++++------ src/Mustache/Context.php | 238 ++--- src/Mustache/Engine.php | 976 +++++++++--------- src/Mustache/HelperCollection.php | 266 ++--- src/Mustache/Loader.php | 19 +- src/Mustache/Loader/ArrayLoader.php | 83 +- src/Mustache/Loader/FilesystemLoader.php | 153 +-- src/Mustache/Loader/MutableLoader.php | 29 +- src/Mustache/Loader/StringLoader.php | 24 +- src/Mustache/Parser.php | 115 ++- src/Mustache/Template.php | 236 ++--- src/Mustache/Tokenizer.php | 473 ++++----- test/Mustache/Test/AutoloaderTest.php | 31 +- test/Mustache/Test/CompilerTest.php | 155 +-- test/Mustache/Test/ContextTest.php | 156 +-- test/Mustache/Test/EngineTest.php | 388 +++---- test/Mustache/Test/Functional/CallTest.php | 32 +- .../Mustache/Test/Functional/ExamplesTest.php | 215 ++-- .../Functional/HigherOrderSectionsTest.php | 122 ++- .../Test/Functional/MustacheInjectionTest.php | 190 ++-- .../Test/Functional/MustacheSpecTest.php | 251 ++--- .../Test/Functional/ObjectSectionTest.php | 134 +-- test/Mustache/Test/HelperCollectionTest.php | 43 +- test/Mustache/Test/Loader/ArrayLoaderTest.php | 60 +- .../Test/Loader/FilesystemLoaderTest.php | 59 +- .../Mustache/Test/Loader/StringLoaderTest.php | 16 +- test/Mustache/Test/ParserTest.php | 309 +++--- test/Mustache/Test/TemplateTest.php | 60 +- test/Mustache/Test/TokenizerTest.php | 239 ++--- test/fixtures/autoloader/Mustache/Bar.php | 5 +- test/fixtures/autoloader/Mustache/Foo.php | 5 +- test/fixtures/autoloader/NonMustacheClass.php | 5 +- .../examples/child_context/ChildContext.php | 19 +- test/fixtures/examples/comments/Comments.php | 10 +- test/fixtures/examples/complex/complex.php | 29 +- .../examples/delimiters/Delimiters.php | 20 +- .../examples/dot_notation/DotNotation.php | 21 +- .../examples/double_section/DoubleSection.php | 12 +- test/fixtures/examples/escaped/Escaped.php | 5 +- .../GrandParentContext.php | 34 +- test/fixtures/examples/i18n/I18n.php | 6 +- .../implicit_iterator/ImplicitIterator.php | 5 +- .../InvertedDoubleSection.php | 7 +- .../inverted_section/InvertedSection.php | 5 +- .../recursive_partials/RecursivePartials.php | 19 +- .../SectionIteratorObjects.php | 22 +- .../SectionMagicObjects.php | 39 +- .../section_objects/SectionObjects.php | 21 +- test/fixtures/examples/sections/Sections.php | 20 +- .../sections_nested/SectionsNested.php | 60 +- test/fixtures/examples/simple/Simple.php | 16 +- .../fixtures/examples/unescaped/Unescaped.php | 5 +- test/fixtures/examples/utf8/UTF8.php | 5 +- .../examples/utf8_unescaped/UTF8Unescaped.php | 5 +- .../examples/whitespace/Whitespace.php | 37 +- 57 files changed, 3283 insertions(+), 3009 deletions(-) diff --git a/bin/create_example.php b/bin/create_example.php index 306eae0..05e52b3 100755 --- a/bin/create_example.php +++ b/bin/create_example.php @@ -38,10 +38,10 @@ define('EXAMPLE_PATH', realpath(dirname(__FILE__) . '/../test/fixtures/examples' * @return string */ function getLowerCaseName($name) { - return preg_replace_callback("/([A-Z])/", create_function ( - '$match', - 'return "_" . strtolower($match[1]);' - ), lcfirst($name)); + return preg_replace_callback("/([A-Z])/", create_function ( + '$match', + 'return "_" . strtolower($match[1]);' + ), lcfirst($name)); } /** @@ -57,10 +57,10 @@ function getLowerCaseName($name) { * @return string */ function getUpperCaseName($name) { - return preg_replace_callback("/_([a-z])/", create_function ( - '$match', - 'return strtoupper($match{1});' - ), ucfirst($name)); + return preg_replace_callback("/_([a-z])/", create_function ( + '$match', + 'return strtoupper($match{1});' + ), ucfirst($name)); } @@ -72,8 +72,8 @@ function getUpperCaseName($name) { * @return mixed */ function out($value) { - echo $value . "\n"; - return $value; + echo $value . "\n"; + return $value; } /** @@ -89,8 +89,8 @@ function out($value) { * @return string */ function buildPath($directory, $filename = null, $extension = null) { - return out(EXAMPLE_PATH . '/' . $directory. - ($extension !== null && $filename !== null ? '/' . $filename. "." . $extension : "")); + return out(EXAMPLE_PATH . '/' . $directory. + ($extension !== null && $filename !== null ? '/' . $filename. "." . $extension : "")); } /** @@ -102,9 +102,9 @@ function buildPath($directory, $filename = null, $extension = null) { * @return void */ function createDirectory($directory) { - if(!@mkdir(buildPath($directory))) { - die("FAILED to create directory\n"); - } + if(!@mkdir(buildPath($directory))) { + die("FAILED to create directory\n"); + } } /** @@ -119,13 +119,13 @@ function createDirectory($directory) { * @return void */ function createFile($directory, $filename, $extension, $content = "") { - $handle = @fopen(buildPath($directory, $filename, $extension), "w"); - if($handle) { - fwrite($handle, $content); - fclose($handle); - } else { - die("FAILED to create file\n"); - } + $handle = @fopen(buildPath($directory, $filename, $extension), "w"); + if($handle) { + fwrite($handle, $content); + fclose($handle); + } else { + die("FAILED to create file\n"); + } } @@ -143,12 +143,12 @@ function createFile($directory, $filename, $extension, $content = "") { * @return void */ function main($example_name) { - $lowercase = getLowerCaseName($example_name); - $uppercase = getUpperCaseName($example_name); - createDirectory($lowercase); - createFile($lowercase, $lowercase, "mustache"); - createFile($lowercase, $lowercase, "txt"); - createFile($lowercase, $uppercase, "php", << 1) { - // get the name of the example - $example_name = $argv[1]; + // get the name of the example + $example_name = $argv[1]; - main($example_name); + main($example_name); } else { - echo USAGE; + echo USAGE; } diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index dc39772..5d70a8e 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -12,54 +12,58 @@ /** * Mustache class autoloader. */ -class Mustache_Autoloader { +class Mustache_Autoloader +{ - private $baseDir; + private $baseDir; - /** - * Autoloader constructor. - * - * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') - */ - public function __construct($baseDir = null) { - if ($baseDir === null) { - $this->baseDir = dirname(__FILE__).'/..'; - } else { - $this->baseDir = rtrim($baseDir, '/'); - } - } + /** + * Autoloader constructor. + * + * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') + */ + public function __construct($baseDir = null) + { + if ($baseDir === null) { + $this->baseDir = dirname(__FILE__).'/..'; + } else { + $this->baseDir = rtrim($baseDir, '/'); + } + } - /** - * Register a new instance as an SPL autoloader. - * - * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') - * - * @return Mustache_Autoloader Registered Autoloader instance - */ - static public function register($baseDir = null) { - $loader = new self($baseDir); - spl_autoload_register(array($loader, 'autoload')); + /** + * Register a new instance as an SPL autoloader. + * + * @param string $baseDir Mustache library base directory (default: dirname(__FILE__).'/..') + * + * @return Mustache_Autoloader Registered Autoloader instance + */ + static public function register($baseDir = null) + { + $loader = new self($baseDir); + spl_autoload_register(array($loader, 'autoload')); - return $loader; - } + return $loader; + } - /** - * Autoload Mustache classes. - * - * @param string $class - */ - public function autoload($class) { - if ($class[0] === '\\') { - $class = substr($class, 1); - } + /** + * Autoload Mustache classes. + * + * @param string $class + */ + public function autoload($class) + { + if ($class[0] === '\\') { + $class = substr($class, 1); + } - if (strpos($class, 'Mustache') !== 0) { - return; - } + if (strpos($class, 'Mustache') !== 0) { + return; + } - $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class)); - if (is_file($file)) { - require $file; - } - } + $file = sprintf('%s/%s.php', $this->baseDir, str_replace('_', '/', $class)); + if (is_file($file)) { + require $file; + } + } } diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 0ea567b..db152e4 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -14,355 +14,370 @@ * * This class is responsible for turning a Mustache token parse tree into normal PHP source code. */ -class Mustache_Compiler { +class Mustache_Compiler +{ - private $sections; - private $source; - private $indentNextLine; - private $customEscape; - private $charset; + private $sections; + private $source; + private $indentNextLine; + private $customEscape; + private $charset; - /** - * Compile a Mustache token parse tree into PHP source code. - * - * @param string $source Mustache Template source code - * @param string $tree Parse tree of Mustache tokens - * @param string $name Mustache Template class name - * - * @return string Generated PHP source code - */ - public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8') { - $this->sections = array(); - $this->source = $source; - $this->indentNextLine = true; - $this->customEscape = $customEscape; - $this->charset = $charset; + /** + * Compile a Mustache token parse tree into PHP source code. + * + * @param string $source Mustache Template source code + * @param string $tree Parse tree of Mustache tokens + * @param string $name Mustache Template class name + * + * @return string Generated PHP source code + */ + public function compile($source, array $tree, $name, $customEscape = false, $charset = 'UTF-8') + { + $this->sections = array(); + $this->source = $source; + $this->indentNextLine = true; + $this->customEscape = $customEscape; + $this->charset = $charset; - return $this->writeCode($tree, $name); - } + return $this->writeCode($tree, $name); + } - /** - * Helper function for walking the Mustache token parse tree. - * - * @throws InvalidArgumentException upon encountering unknown token types. - * - * @param array $tree Parse tree of Mustache tokens - * @param int $level (default: 0) - * - * @return string Generated PHP source code; - */ - private function walk(array $tree, $level = 0) { - $code = ''; - $level++; - foreach ($tree as $node) { - switch ($node[Mustache_Tokenizer::TYPE]) { - case Mustache_Tokenizer::T_SECTION: - $code .= $this->section( - $node[Mustache_Tokenizer::NODES], - $node[Mustache_Tokenizer::NAME], - $node[Mustache_Tokenizer::INDEX], - $node[Mustache_Tokenizer::END], - $node[Mustache_Tokenizer::OTAG], - $node[Mustache_Tokenizer::CTAG], - $level - ); - break; + /** + * Helper function for walking the Mustache token parse tree. + * + * @throws InvalidArgumentException upon encountering unknown token types. + * + * @param array $tree Parse tree of Mustache tokens + * @param int $level (default: 0) + * + * @return string Generated PHP source code; + */ + private function walk(array $tree, $level = 0) + { + $code = ''; + $level++; + foreach ($tree as $node) { + switch ($node[Mustache_Tokenizer::TYPE]) { + case Mustache_Tokenizer::T_SECTION: + $code .= $this->section( + $node[Mustache_Tokenizer::NODES], + $node[Mustache_Tokenizer::NAME], + $node[Mustache_Tokenizer::INDEX], + $node[Mustache_Tokenizer::END], + $node[Mustache_Tokenizer::OTAG], + $node[Mustache_Tokenizer::CTAG], + $level + ); + break; - case Mustache_Tokenizer::T_INVERTED: - $code .= $this->invertedSection( - $node[Mustache_Tokenizer::NODES], - $node[Mustache_Tokenizer::NAME], - $level - ); - break; + case Mustache_Tokenizer::T_INVERTED: + $code .= $this->invertedSection( + $node[Mustache_Tokenizer::NODES], + $node[Mustache_Tokenizer::NAME], + $level + ); + break; - case Mustache_Tokenizer::T_PARTIAL: - case Mustache_Tokenizer::T_PARTIAL_2: - $code .= $this->partial( - $node[Mustache_Tokenizer::NAME], - isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', - $level - ); - break; + case Mustache_Tokenizer::T_PARTIAL: + case Mustache_Tokenizer::T_PARTIAL_2: + $code .= $this->partial( + $node[Mustache_Tokenizer::NAME], + isset($node[Mustache_Tokenizer::INDENT]) ? $node[Mustache_Tokenizer::INDENT] : '', + $level + ); + break; - case Mustache_Tokenizer::T_UNESCAPED: - case Mustache_Tokenizer::T_UNESCAPED_2: - $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level); - break; + case Mustache_Tokenizer::T_UNESCAPED: + case Mustache_Tokenizer::T_UNESCAPED_2: + $code .= $this->variable($node[Mustache_Tokenizer::NAME], false, $level); + break; - case Mustache_Tokenizer::T_COMMENT: - break; + case Mustache_Tokenizer::T_COMMENT: + break; - case Mustache_Tokenizer::T_ESCAPED: - $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level); - break; + case Mustache_Tokenizer::T_ESCAPED: + $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level); + break; - case Mustache_Tokenizer::T_TEXT: - $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); - break; + case Mustache_Tokenizer::T_TEXT: + $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); + break; - default: - throw new InvalidArgumentException('Unknown node type: '.json_encode($node)); - } - } + default: + throw new InvalidArgumentException('Unknown node type: '.json_encode($node)); + } + } - return $code; - } + return $code; + } - const KLASS = 'walk($tree); - $sections = implode("\n", $this->sections); + /** + * Generate Mustache Template class PHP source. + * + * @param array $tree Parse tree of Mustache tokens + * @param string $name Mustache Template class name + * + * @return string Generated PHP source code + */ + private function writeCode($tree, $name) + { + $code = $this->walk($tree); + $sections = implode("\n", $this->sections); - return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $this->getEscape('$buffer'), $sections); - } + return sprintf($this->prepare(self::KLASS, 0, false), $name, $code, $this->getEscape('$buffer'), $sections); + } - const SECTION_CALL = ' - // %s section - $buffer .= $this->section%s($context, $indent, $context->%s(%s)); - '; + const SECTION_CALL = ' + // %s section + $buffer .= $this->section%s($context, $indent, $context->%s(%s)); + '; - const SECTION = ' - private function section%s(Mustache_Context $context, $indent, $value) { - $buffer = \'\'; - if (!is_string($value) && is_callable($value)) { - $source = %s; - $buffer .= $this->mustache - ->loadLambda((string) call_user_func($value, $source)%s) - ->renderInternal($context, $indent); - } elseif (!empty($value)) { - $values = $this->isIterable($value) ? $value : array($value); - foreach ($values as $value) { - $context->push($value);%s - $context->pop(); - } - } + const SECTION = ' + private function section%s(Mustache_Context $context, $indent, $value) { + $buffer = \'\'; + if (!is_string($value) && is_callable($value)) { + $source = %s; + $buffer .= $this->mustache + ->loadLambda((string) call_user_func($value, $source)%s) + ->renderInternal($context, $indent); + } elseif (!empty($value)) { + $values = $this->isIterable($value) ? $value : array($value); + foreach ($values as $value) { + $context->push($value);%s + $context->pop(); + } + } - return $buffer; - }'; + return $buffer; + }'; - /** - * Generate Mustache Template section PHP source. - * - * @param array $nodes Array of child tokens - * @param string $id Section name - * @param int $start Section start offset - * @param int $end Section end offset - * @param string $otag Current Mustache opening tag - * @param string $ctag Current Mustache closing tag - * @param int $level - * - * @return string Generated section PHP source code - */ - private function section($nodes, $id, $start, $end, $otag, $ctag, $level) { - $method = $this->getFindMethod($id); - $id = var_export($id, true); - $source = var_export(substr($this->source, $start, $end - $start), true); + /** + * Generate Mustache Template section PHP source. + * + * @param array $nodes Array of child tokens + * @param string $id Section name + * @param int $start Section start offset + * @param int $end Section end offset + * @param string $otag Current Mustache opening tag + * @param string $ctag Current Mustache closing tag + * @param int $level + * + * @return string Generated section PHP source code + */ + private function section($nodes, $id, $start, $end, $otag, $ctag, $level) + { + $method = $this->getFindMethod($id); + $id = var_export($id, true); + $source = var_export(substr($this->source, $start, $end - $start), true); - if ($otag !== '{{' || $ctag !== '}}') { - $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true); - } else { - $delims = ''; - } + if ($otag !== '{{' || $ctag !== '}}') { + $delims = ', '.var_export(sprintf('{{= %s %s =}}', $otag, $ctag), true); + } else { + $delims = ''; + } - $key = ucfirst(md5($delims."\n".$source)); + $key = ucfirst(md5($delims."\n".$source)); - if (!isset($this->sections[$key])) { - $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $source, $delims, $this->walk($nodes, 2)); - } + if (!isset($this->sections[$key])) { + $this->sections[$key] = sprintf($this->prepare(self::SECTION), $key, $source, $delims, $this->walk($nodes, 2)); + } - return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id); - } + return sprintf($this->prepare(self::SECTION_CALL, $level), $id, $key, $method, $id); + } - const INVERTED_SECTION = ' - // %s inverted section - $value = $context->%s(%s); - if (empty($value)) { - %s - }'; + const INVERTED_SECTION = ' + // %s inverted section + $value = $context->%s(%s); + if (empty($value)) { + %s + }'; - /** - * Generate Mustache Template inverted section PHP source. - * - * @param array $nodes Array of child tokens - * @param string $id Section name - * @param int $level - * - * @return string Generated inverted section PHP source code - */ - private function invertedSection($nodes, $id, $level) { - $method = $this->getFindMethod($id); - $id = var_export($id, true); + /** + * Generate Mustache Template inverted section PHP source. + * + * @param array $nodes Array of child tokens + * @param string $id Section name + * @param int $level + * + * @return string Generated inverted section PHP source code + */ + private function invertedSection($nodes, $id, $level) + { + $method = $this->getFindMethod($id); + $id = var_export($id, true); - return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); - } + return sprintf($this->prepare(self::INVERTED_SECTION, $level), $id, $method, $id, $this->walk($nodes, $level)); + } - const PARTIAL = ' - if ($partial = $this->mustache->loadPartial(%s)) { - $buffer .= $partial->renderInternal($context, %s); - } - '; + const PARTIAL = ' + if ($partial = $this->mustache->loadPartial(%s)) { + $buffer .= $partial->renderInternal($context, %s); + } + '; - /** - * Generate Mustache Template partial call PHP source. - * - * @param string $id Partial name - * @param string $indent Whitespace indent to apply to partial - * @param int $level - * - * @return string Generated partial call PHP source code - */ - private function partial($id, $indent, $level) { - return sprintf( - $this->prepare(self::PARTIAL, $level), - var_export($id, true), - var_export($indent, true) - ); - } + /** + * Generate Mustache Template partial call PHP source. + * + * @param string $id Partial name + * @param string $indent Whitespace indent to apply to partial + * @param int $level + * + * @return string Generated partial call PHP source code + */ + private function partial($id, $indent, $level) + { + return sprintf( + $this->prepare(self::PARTIAL, $level), + var_export($id, true), + var_export($indent, true) + ); + } - const VARIABLE = ' - $value = $context->%s(%s); - if (!is_string($value) && is_callable($value)) { - $value = $this->mustache - ->loadLambda((string) call_user_func($value)) - ->renderInternal($context, $indent); - } - $buffer .= %s%s; - '; + const VARIABLE = ' + $value = $context->%s(%s); + if (!is_string($value) && is_callable($value)) { + $value = $this->mustache + ->loadLambda((string) call_user_func($value)) + ->renderInternal($context, $indent); + } + $buffer .= %s%s; + '; - /** - * Generate Mustache Template variable interpolation PHP source. - * - * @param string $id Variable name - * @param boolean $escape Escape the variable value for output? - * @param int $level - * - * @return string Generated variable interpolation PHP source - */ - private function variable($id, $escape, $level) { - $method = $this->getFindMethod($id); - $id = ($method !== 'last') ? var_export($id, true) : ''; - $value = $escape ? $this->getEscape() : '$value'; + /** + * Generate Mustache Template variable interpolation PHP source. + * + * @param string $id Variable name + * @param boolean $escape Escape the variable value for output? + * @param int $level + * + * @return string Generated variable interpolation PHP source + */ + private function variable($id, $escape, $level) + { + $method = $this->getFindMethod($id); + $id = ($method !== 'last') ? var_export($id, true) : ''; + $value = $escape ? $this->getEscape() : '$value'; - return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $this->flushIndent(), $value); - } + return sprintf($this->prepare(self::VARIABLE, $level), $method, $id, $this->flushIndent(), $value); + } - const LINE = '$buffer .= "\n";'; - const TEXT = '$buffer .= %s%s;'; + const LINE = '$buffer .= "\n";'; + const TEXT = '$buffer .= %s%s;'; - /** - * Generate Mustache Template output Buffer call PHP source. - * - * @param string $text - * @param int $level - * - * @return string Generated output Buffer call PHP source - */ - private function text($text, $level) { - if ($text === "\n") { - $this->indentNextLine = true; + /** + * Generate Mustache Template output Buffer call PHP source. + * + * @param string $text + * @param int $level + * + * @return string Generated output Buffer call PHP source + */ + private function text($text, $level) + { + if ($text === "\n") { + $this->indentNextLine = true; - return $this->prepare(self::LINE, $level); - } else { - return sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true)); - } - } + return $this->prepare(self::LINE, $level); + } else { + return sprintf($this->prepare(self::TEXT, $level), $this->flushIndent(), var_export($text, true)); + } + } - /** - * Prepare PHP source code snippet for output. - * - * @param string $text - * @param int $bonus Additional indent level (default: 0) - * @param boolean $prependNewline Prepend a newline to the snippet? (default: true) - * - * @return string PHP source code snippet - */ - private function prepare($text, $bonus = 0, $prependNewline = true) { - $text = ($prependNewline ? "\n" : '').trim($text); - if ($prependNewline) { - $bonus++; - } + /** + * Prepare PHP source code snippet for output. + * + * @param string $text + * @param int $bonus Additional indent level (default: 0) + * @param boolean $prependNewline Prepend a newline to the snippet? (default: true) + * + * @return string PHP source code snippet + */ + private function prepare($text, $bonus = 0, $prependNewline = true) + { + $text = ($prependNewline ? "\n" : '').trim($text); + if ($prependNewline) { + $bonus++; + } - return preg_replace("/\n(\t\t)?/", "\n".str_repeat("\t", $bonus), $text); - } + return preg_replace("/\n( {8})?/", "\n".str_repeat(" ", $bonus * 4), $text); + } - const DEFAULT_ESCAPE = 'htmlspecialchars(%s, ENT_COMPAT, %s)'; - const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)'; + const DEFAULT_ESCAPE = 'htmlspecialchars(%s, ENT_COMPAT, %s)'; + const CUSTOM_ESCAPE = 'call_user_func($this->mustache->getEscape(), %s)'; - /** - * Get the current escaper. - * - * @return string Either a custom callback, or an inline call to `htmlspecialchars` - */ - private function getEscape($value = '$value') { - if ($this->customEscape) { - return sprintf(self::CUSTOM_ESCAPE, $value); - } else { - return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->charset, true)); - } - } + /** + * Get the current escaper. + * + * @return string Either a custom callback, or an inline call to `htmlspecialchars` + */ + private function getEscape($value = '$value') + { + if ($this->customEscape) { + return sprintf(self::CUSTOM_ESCAPE, $value); + } else { + return sprintf(self::DEFAULT_ESCAPE, $value, var_export($this->charset, true)); + } + } - /** - * Select the appropriate Context `find` method for a given $id. - * - * The return value will be one of `find`, `findDot` or `last`. - * - * @see Mustache_Context::find - * @see Mustache_Context::findDot - * @see Mustache_Context::last - * - * @param string $id Variable name - * - * @return string `find` method name - */ - private function getFindMethod($id) { - if ($id === '.') { - return 'last'; - } elseif (strpos($id, '.') === false) { - return 'find'; - } else { - return 'findDot'; - } - } + /** + * Select the appropriate Context `find` method for a given $id. + * + * The return value will be one of `find`, `findDot` or `last`. + * + * @see Mustache_Context::find + * @see Mustache_Context::findDot + * @see Mustache_Context::last + * + * @param string $id Variable name + * + * @return string `find` method name + */ + private function getFindMethod($id) + { + if ($id === '.') { + return 'last'; + } elseif (strpos($id, '.') === false) { + return 'find'; + } else { + return 'findDot'; + } + } - const LINE_INDENT = '$indent . '; + const LINE_INDENT = '$indent . '; - /** - * Get the current $indent prefix to write to the buffer. - * - * @return string "$indent . " or "" - */ - private function flushIndent() { - if ($this->indentNextLine) { - $this->indentNextLine = false; + /** + * Get the current $indent prefix to write to the buffer. + * + * @return string "$indent . " or "" + */ + private function flushIndent() + { + if ($this->indentNextLine) { + $this->indentNextLine = false; - return self::LINE_INDENT; - } else { - return ''; - } - } + return self::LINE_INDENT; + } else { + return ''; + } + } } diff --git a/src/Mustache/Context.php b/src/Mustache/Context.php index ef41e9a..6a2d57c 100644 --- a/src/Mustache/Context.php +++ b/src/Mustache/Context.php @@ -12,130 +12,138 @@ /** * Mustache Template rendering Context. */ -class Mustache_Context { - private $stack = array(); +class Mustache_Context +{ + private $stack = array(); - /** - * Mustache rendering Context constructor. - * - * @param mixed $context Default rendering context (default: null) - */ - public function __construct($context = null) { - if ($context !== null) { - $this->stack = array($context); - } - } + /** + * Mustache rendering Context constructor. + * + * @param mixed $context Default rendering context (default: null) + */ + public function __construct($context = null) + { + if ($context !== null) { + $this->stack = array($context); + } + } - /** - * Push a new Context frame onto the stack. - * - * @param mixed $value Object or array to use for context - */ - public function push($value) { - array_push($this->stack, $value); - } + /** + * Push a new Context frame onto the stack. + * + * @param mixed $value Object or array to use for context + */ + public function push($value) + { + array_push($this->stack, $value); + } - /** - * Pop the last Context frame from the stack. - * - * @return mixed Last Context frame (object or array) - */ - public function pop() { - return array_pop($this->stack); - } + /** + * Pop the last Context frame from the stack. + * + * @return mixed Last Context frame (object or array) + */ + public function pop() + { + return array_pop($this->stack); + } - /** - * Get the last Context frame. - * - * @return mixed Last Context frame (object or array) - */ - public function last() { - return end($this->stack); - } + /** + * Get the last Context frame. + * + * @return mixed Last Context frame (object or array) + */ + public function last() + { + return end($this->stack); + } - /** - * Find a variable in the Context stack. - * - * Starting with the last Context frame (the context of the innermost section), and working back to the top-level - * rendering context, look for a variable with the given name: - * - * * If the Context frame is an associative array which contains the key $id, returns the value of that element. - * * If the Context frame is an object, this will check first for a public method, then a public property named - * $id. Failing both of these, it will try `__isset` and `__get` magic methods. - * * If a value named $id is not found in any Context frame, returns an empty string. - * - * @param string $id Variable name - * - * @return mixed Variable value, or '' if not found - */ - public function find($id) { - return $this->findVariableInStack($id, $this->stack); - } + /** + * Find a variable in the Context stack. + * + * Starting with the last Context frame (the context of the innermost section), and working back to the top-level + * rendering context, look for a variable with the given name: + * + * * If the Context frame is an associative array which contains the key $id, returns the value of that element. + * * If the Context frame is an object, this will check first for a public method, then a public property named + * $id. Failing both of these, it will try `__isset` and `__get` magic methods. + * * If a value named $id is not found in any Context frame, returns an empty string. + * + * @param string $id Variable name + * + * @return mixed Variable value, or '' if not found + */ + public function find($id) + { + return $this->findVariableInStack($id, $this->stack); + } - /** - * Find a 'dot notation' variable in the Context stack. - * - * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding - * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous - * result. For example, given the following context stack: - * - * $data = array( - * 'name' => 'Fred', - * 'child' => array( - * 'name' => 'Bob' - * ), - * ); - * - * ... and the Mustache following template: - * - * {{ child.name }} - * - * ... the `name` value is only searched for within the `child` value of the global Context, not within parent - * Context frames. - * - * @param string $id Dotted variable selector - * - * @return mixed Variable value, or '' if not found - */ - public function findDot($id) { - $chunks = explode('.', $id); - $first = array_shift($chunks); - $value = $this->findVariableInStack($first, $this->stack); + /** + * Find a 'dot notation' variable in the Context stack. + * + * Note that dot notation traversal bubbles through scope differently than the regular find method. After finding + * the initial chunk of the dotted name, each subsequent chunk is searched for only within the value of the previous + * result. For example, given the following context stack: + * + * $data = array( + * 'name' => 'Fred', + * 'child' => array( + * 'name' => 'Bob' + * ), + * ); + * + * ... and the Mustache following template: + * + * {{ child.name }} + * + * ... the `name` value is only searched for within the `child` value of the global Context, not within parent + * Context frames. + * + * @param string $id Dotted variable selector + * + * @return mixed Variable value, or '' if not found + */ + public function findDot($id) + { + $chunks = explode('.', $id); + $first = array_shift($chunks); + $value = $this->findVariableInStack($first, $this->stack); - foreach ($chunks as $chunk) { - if ($value === '') { - return $value; - } + foreach ($chunks as $chunk) { + if ($value === '') { + return $value; + } - $value = $this->findVariableInStack($chunk, array($value)); - } + $value = $this->findVariableInStack($chunk, array($value)); + } - return $value; - } + return $value; + } - /** - * Helper function to find a variable in the Context stack. - * - * @see Mustache_Context::find - * - * @param string $id Variable name - * @param array $stack Context stack - * - * @return mixed Variable value, or '' if not found - */ - private function findVariableInStack($id, array $stack) { - for ($i = count($stack) - 1; $i >= 0; $i--) { - if (is_object($stack[$i])) { - if (method_exists($stack[$i], $id)) { - return $stack[$i]->$id(); - } elseif (isset($stack[$i]->$id)) { - return $stack[$i]->$id; - } - } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) { - return $stack[$i][$id]; - } - } + /** + * Helper function to find a variable in the Context stack. + * + * @see Mustache_Context::find + * + * @param string $id Variable name + * @param array $stack Context stack + * + * @return mixed Variable value, or '' if not found + */ + private function findVariableInStack($id, array $stack) + { + for ($i = count($stack) - 1; $i >= 0; $i--) { + if (is_object($stack[$i])) { + if (method_exists($stack[$i], $id)) { + return $stack[$i]->$id(); + } elseif (isset($stack[$i]->$id)) { + return $stack[$i]->$id; + } + } elseif (is_array($stack[$i]) && array_key_exists($id, $stack[$i])) { + return $stack[$i][$id]; + } + } - return ''; - } + return ''; + } } diff --git a/src/Mustache/Engine.php b/src/Mustache/Engine.php index a772800..94ea124 100644 --- a/src/Mustache/Engine.php +++ b/src/Mustache/Engine.php @@ -21,535 +21,567 @@ * * @author Justin Hileman {@link http://justinhileman.com} */ -class Mustache_Engine { - const VERSION = '2.0.0-dev'; - const SPEC_VERSION = '1.1.2'; +class Mustache_Engine +{ + const VERSION = '2.0.0-dev'; + const SPEC_VERSION = '1.1.2'; - // Template cache - private $templates = array(); + // Template cache + private $templates = array(); - // Environment - private $templateClassPrefix = '__Mustache_'; - private $cache = null; - private $loader; - private $partialsLoader; - private $helpers; - private $escape; - private $charset = 'UTF-8'; + // Environment + private $templateClassPrefix = '__Mustache_'; + private $cache = null; + private $loader; + private $partialsLoader; + private $helpers; + private $escape; + private $charset = 'UTF-8'; - /** - * Mustache class constructor. - * - * Passing an $options array allows overriding certain Mustache options during instantiation: - * - * $options = array( - * // The class prefix for compiled templates. Defaults to '__Mustache_' - * 'template_class_prefix' => '__MyTemplates_', - * - * // A cache directory for compiled templates. Mustache will not cache templates unless this is set - * 'cache' => dirname(__FILE__).'/tmp/cache/mustache', - * - * // A Mustache template loader instance. Uses a StringLoader if not specified - * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), - * - * // A Mustache loader instance for partials. - * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), - * - * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as - * // efficient or lazy as a Filesystem (or database) loader. - * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')), - * - * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order - * // sections), or any other valid Mustache context value. They will be prepended to the context stack, - * // so they will be available in any template loaded by this Mustache instance. - * 'helpers' => array('i18n' => function($text) { - * // do something translatey here... - * }), - * - * // An 'escape' callback, responsible for escaping double-mustache variables. - * 'escape' => function($value) { - * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8'); - * }, - * - * // character set for `htmlspecialchars`. Defaults to 'UTF-8' - * 'charset' => 'ISO-8859-1', - * ); - * - * @param array $options (default: array()) - */ - public function __construct(array $options = array()) { - if (isset($options['template_class_prefix'])) { - $this->templateClassPrefix = $options['template_class_prefix']; - } + /** + * Mustache class constructor. + * + * Passing an $options array allows overriding certain Mustache options during instantiation: + * + * $options = array( + * // The class prefix for compiled templates. Defaults to '__Mustache_' + * 'template_class_prefix' => '__MyTemplates_', + * + * // A cache directory for compiled templates. Mustache will not cache templates unless this is set + * 'cache' => dirname(__FILE__).'/tmp/cache/mustache', + * + * // A Mustache template loader instance. Uses a StringLoader if not specified + * 'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views'), + * + * // A Mustache loader instance for partials. + * 'partials_loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views/partials'), + * + * // An array of Mustache partials. Useful for quick-and-dirty string template loading, but not as + * // efficient or lazy as a Filesystem (or database) loader. + * 'partials' => array('foo' => file_get_contents(dirname(__FILE__).'/views/partials/foo.mustache')), + * + * // An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order + * // sections), or any other valid Mustache context value. They will be prepended to the context stack, + * // so they will be available in any template loaded by this Mustache instance. + * 'helpers' => array('i18n' => function($text) { + * // do something translatey here... + * }), + * + * // An 'escape' callback, responsible for escaping double-mustache variables. + * 'escape' => function($value) { + * return htmlspecialchars($buffer, ENT_COMPAT, 'UTF-8'); + * }, + * + * // character set for `htmlspecialchars`. Defaults to 'UTF-8' + * 'charset' => 'ISO-8859-1', + * ); + * + * @param array $options (default: array()) + */ + public function __construct(array $options = array()) + { + if (isset($options['template_class_prefix'])) { + $this->templateClassPrefix = $options['template_class_prefix']; + } - if (isset($options['cache'])) { - $this->cache = $options['cache']; - } + if (isset($options['cache'])) { + $this->cache = $options['cache']; + } - if (isset($options['loader'])) { - $this->setLoader($options['loader']); - } + if (isset($options['loader'])) { + $this->setLoader($options['loader']); + } - if (isset($options['partials_loader'])) { - $this->setPartialsLoader($options['partials_loader']); - } + if (isset($options['partials_loader'])) { + $this->setPartialsLoader($options['partials_loader']); + } - if (isset($options['partials'])) { - $this->setPartials($options['partials']); - } + if (isset($options['partials'])) { + $this->setPartials($options['partials']); + } - if (isset($options['helpers'])) { - $this->setHelpers($options['helpers']); - } + if (isset($options['helpers'])) { + $this->setHelpers($options['helpers']); + } - if (isset($options['escape'])) { - if (!is_callable($options['escape'])) { - throw new InvalidArgumentException('Mustache Constructor "escape" option must be callable'); - } + if (isset($options['escape'])) { + if (!is_callable($options['escape'])) { + throw new InvalidArgumentException('Mustache Constructor "escape" option must be callable'); + } - $this->escape = $options['escape']; - } + $this->escape = $options['escape']; + } - if (isset($options['charset'])) { - $this->charset = $options['charset']; - } - } + if (isset($options['charset'])) { + $this->charset = $options['charset']; + } + } - /** - * Shortcut 'render' invocation. - * - * Equivalent to calling `$mustache->loadTemplate($template)->render($data);` - * - * @see Mustache_Engine::loadTemplate - * @see Mustache_Template::render - * - * @param string $template - * @param mixed $data - * - * @return string Rendered template - */ - public function render($template, $data) { - return $this->loadTemplate($template)->render($data); - } + /** + * Shortcut 'render' invocation. + * + * Equivalent to calling `$mustache->loadTemplate($template)->render($data);` + * + * @see Mustache_Engine::loadTemplate + * @see Mustache_Template::render + * + * @param string $template + * @param mixed $data + * + * @return string Rendered template + */ + public function render($template, $data) + { + return $this->loadTemplate($template)->render($data); + } - /** - * Get the current Mustache escape callback. - * - * @return mixed Callable or null - */ - public function getEscape() { - return $this->escape; - } + /** + * Get the current Mustache escape callback. + * + * @return mixed Callable or null + */ + public function getEscape() + { + return $this->escape; + } - /** - * Get the current Mustache character set. - * - * @return string - */ - public function getCharset() { - return $this->charset; - } + /** + * Get the current Mustache character set. + * + * @return string + */ + public function getCharset() + { + return $this->charset; + } - /** - * Set the Mustache template Loader instance. - * - * @param Mustache_Loader $loader - */ - public function setLoader(Mustache_Loader $loader) { - $this->loader = $loader; - } + /** + * Set the Mustache template Loader instance. + * + * @param Mustache_Loader $loader + */ + public function setLoader(Mustache_Loader $loader) + { + $this->loader = $loader; + } - /** - * Get the current Mustache template Loader instance. - * - * If no Loader instance has been explicitly specified, this method will instantiate and return - * a StringLoader instance. - * - * @return Mustache_Loader - */ - public function getLoader() { - if (!isset($this->loader)) { - $this->loader = new Mustache_Loader_StringLoader; - } + /** + * Get the current Mustache template Loader instance. + * + * If no Loader instance has been explicitly specified, this method will instantiate and return + * a StringLoader instance. + * + * @return Mustache_Loader + */ + public function getLoader() + { + if (!isset($this->loader)) { + $this->loader = new Mustache_Loader_StringLoader; + } - return $this->loader; - } + return $this->loader; + } - /** - * Set the Mustache partials Loader instance. - * - * @param Mustache_Loader $partialsLoader - */ - public function setPartialsLoader(Mustache_Loader $partialsLoader) { - $this->partialsLoader = $partialsLoader; - } + /** + * Set the Mustache partials Loader instance. + * + * @param Mustache_Loader $partialsLoader + */ + public function setPartialsLoader(Mustache_Loader $partialsLoader) + { + $this->partialsLoader = $partialsLoader; + } - /** - * Get the current Mustache partials Loader instance. - * - * If no Loader instance has been explicitly specified, this method will instantiate and return - * an ArrayLoader instance. - * - * @return Mustache_Loader - */ - public function getPartialsLoader() { - if (!isset($this->partialsLoader)) { - $this->partialsLoader = new Mustache_Loader_ArrayLoader; - } + /** + * Get the current Mustache partials Loader instance. + * + * If no Loader instance has been explicitly specified, this method will instantiate and return + * an ArrayLoader instance. + * + * @return Mustache_Loader + */ + public function getPartialsLoader() + { + if (!isset($this->partialsLoader)) { + $this->partialsLoader = new Mustache_Loader_ArrayLoader; + } - return $this->partialsLoader; - } + return $this->partialsLoader; + } - /** - * Set partials for the current partials Loader instance. - * - * @throws RuntimeException If the current Loader instance is immutable - * - * @param array $partials (default: array()) - */ - public function setPartials(array $partials = array()) { - $loader = $this->getPartialsLoader(); - if (!$loader instanceof Mustache_Loader_MutableLoader) { - throw new RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); - } + /** + * Set partials for the current partials Loader instance. + * + * @throws RuntimeException If the current Loader instance is immutable + * + * @param array $partials (default: array()) + */ + public function setPartials(array $partials = array()) + { + $loader = $this->getPartialsLoader(); + if (!$loader instanceof Mustache_Loader_MutableLoader) { + throw new RuntimeException('Unable to set partials on an immutable Mustache Loader instance'); + } - $loader->setTemplates($partials); - } + $loader->setTemplates($partials); + } - /** - * Set an array of Mustache helpers. - * - * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or - * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in - * any template loaded by this Mustache instance. - * - * @throws InvalidArgumentException if $helpers is not an array or Traversable - * - * @param array|Traversable $helpers - */ - public function setHelpers($helpers) { - if (!is_array($helpers) && !$helpers instanceof Traversable) { - throw new InvalidArgumentException('setHelpers expects an array of helpers'); - } + /** + * Set an array of Mustache helpers. + * + * An array of 'helpers'. Helpers can be global variables or objects, closures (e.g. for higher order sections), or + * any other valid Mustache context value. They will be prepended to the context stack, so they will be available in + * any template loaded by this Mustache instance. + * + * @throws InvalidArgumentException if $helpers is not an array or Traversable + * + * @param array|Traversable $helpers + */ + public function setHelpers($helpers) + { + if (!is_array($helpers) && !$helpers instanceof Traversable) { + throw new InvalidArgumentException('setHelpers expects an array of helpers'); + } - $this->getHelpers()->clear(); + $this->getHelpers()->clear(); - foreach ($helpers as $name => $helper) { - $this->addHelper($name, $helper); - } - } + foreach ($helpers as $name => $helper) { + $this->addHelper($name, $helper); + } + } - /** - * Get the current set of Mustache helpers. - * - * @see Mustache_Engine::setHelpers - * - * @return Mustache_HelperCollection - */ - public function getHelpers() { - if (!isset($this->helpers)) { - $this->helpers = new Mustache_HelperCollection; - } + /** + * Get the current set of Mustache helpers. + * + * @see Mustache_Engine::setHelpers + * + * @return Mustache_HelperCollection + */ + public function getHelpers() + { + if (!isset($this->helpers)) { + $this->helpers = new Mustache_HelperCollection; + } - return $this->helpers; - } + return $this->helpers; + } - /** - * Add a new Mustache helper. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * @param mixed $helper - */ - public function addHelper($name, $helper) { - $this->getHelpers()->add($name, $helper); - } + /** + * Add a new Mustache helper. + * + * @see Mustache_Engine::setHelpers + * + * @param string $name + * @param mixed $helper + */ + public function addHelper($name, $helper) + { + $this->getHelpers()->add($name, $helper); + } - /** - * Get a Mustache helper by name. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * - * @return mixed Helper - */ - public function getHelper($name) { - return $this->getHelpers()->get($name); - } + /** + * Get a Mustache helper by name. + * + * @see Mustache_Engine::setHelpers + * + * @param string $name + * + * @return mixed Helper + */ + public function getHelper($name) + { + return $this->getHelpers()->get($name); + } - /** - * Check whether this Mustache instance has a helper. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - * - * @return boolean True if the helper is present - */ - public function hasHelper($name) { - return $this->getHelpers()->has($name); - } + /** + * Check whether this Mustache instance has a helper. + * + * @see Mustache_Engine::setHelpers + * + * @param string $name + * + * @return boolean True if the helper is present + */ + public function hasHelper($name) + { + return $this->getHelpers()->has($name); + } - /** - * Remove a helper by name. - * - * @see Mustache_Engine::setHelpers - * - * @param string $name - */ - public function removeHelper($name) { - $this->getHelpers()->remove($name); - } + /** + * Remove a helper by name. + * + * @see Mustache_Engine::setHelpers + * + * @param string $name + */ + public function removeHelper($name) + { + $this->getHelpers()->remove($name); + } - /** - * Set the Mustache Tokenizer instance. - * - * @param Mustache_Tokenizer $tokenizer - */ - public function setTokenizer(Mustache_Tokenizer $tokenizer) { - $this->tokenizer = $tokenizer; - } + /** + * Set the Mustache Tokenizer instance. + * + * @param Mustache_Tokenizer $tokenizer + */ + public function setTokenizer(Mustache_Tokenizer $tokenizer) + { + $this->tokenizer = $tokenizer; + } - /** - * Get the current Mustache Tokenizer instance. - * - * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Tokenizer - */ - public function getTokenizer() { - if (!isset($this->tokenizer)) { - $this->tokenizer = new Mustache_Tokenizer; - } + /** + * Get the current Mustache Tokenizer instance. + * + * If no Tokenizer instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return Mustache_Tokenizer + */ + public function getTokenizer() + { + if (!isset($this->tokenizer)) { + $this->tokenizer = new Mustache_Tokenizer; + } - return $this->tokenizer; - } + return $this->tokenizer; + } - /** - * Set the Mustache Parser instance. - * - * @param Mustache_Parser $parser - */ - public function setParser(Mustache_Parser $parser) { - $this->parser = $parser; - } + /** + * Set the Mustache Parser instance. + * + * @param Mustache_Parser $parser + */ + public function setParser(Mustache_Parser $parser) + { + $this->parser = $parser; + } - /** - * Get the current Mustache Parser instance. - * - * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Parser - */ - public function getParser() { - if (!isset($this->parser)) { - $this->parser = new Mustache_Parser; - } + /** + * Get the current Mustache Parser instance. + * + * If no Parser instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return Mustache_Parser + */ + public function getParser() + { + if (!isset($this->parser)) { + $this->parser = new Mustache_Parser; + } - return $this->parser; - } + return $this->parser; + } - /** - * Set the Mustache Compiler instance. - * - * @param Mustache_Compiler $compiler - */ - public function setCompiler(Mustache_Compiler $compiler) { - $this->compiler = $compiler; - } + /** + * Set the Mustache Compiler instance. + * + * @param Mustache_Compiler $compiler + */ + public function setCompiler(Mustache_Compiler $compiler) + { + $this->compiler = $compiler; + } - /** - * Get the current Mustache Compiler instance. - * - * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. - * - * @return Mustache_Compiler - */ - public function getCompiler() { - if (!isset($this->compiler)) { - $this->compiler = new Mustache_Compiler; - } + /** + * Get the current Mustache Compiler instance. + * + * If no Compiler instance has been explicitly specified, this method will instantiate and return a new one. + * + * @return Mustache_Compiler + */ + public function getCompiler() + { + if (!isset($this->compiler)) { + $this->compiler = new Mustache_Compiler; + } - return $this->compiler; - } + return $this->compiler; + } - /** - * Helper method to generate a Mustache template class. - * - * @param string $source - * - * @return string Mustache Template class name - */ - public function getTemplateClassName($source) { - return $this->templateClassPrefix . md5(sprintf( - 'version:%s,escape:%s,charset:%s,source:%s', - self::VERSION, - isset($this->escape) ? 'custom' : 'default', - $this->charset, - $source - )); - } + /** + * Helper method to generate a Mustache template class. + * + * @param string $source + * + * @return string Mustache Template class name + */ + public function getTemplateClassName($source) + { + return $this->templateClassPrefix . md5(sprintf( + 'version:%s,escape:%s,charset:%s,source:%s', + self::VERSION, + isset($this->escape) ? 'custom' : 'default', + $this->charset, + $source + )); + } - /** - * Load a Mustache Template by name. - * - * @param string $name - * - * @return Mustache_Template - */ - public function loadTemplate($name) { - return $this->loadSource($this->getLoader()->load($name)); - } + /** + * Load a Mustache Template by name. + * + * @param string $name + * + * @return Mustache_Template + */ + public function loadTemplate($name) + { + return $this->loadSource($this->getLoader()->load($name)); + } - /** - * Load a Mustache partial Template by name. - * - * This is a helper method used internally by Template instances for loading partial templates. You can most likely - * ignore it completely. - * - * @param string $name - * - * @return Mustache_Template - */ - public function loadPartial($name) { - try { - return $this->loadSource($this->getPartialsLoader()->load($name)); - } catch (InvalidArgumentException $e) { - // If the named partial cannot be found, return null. - } - } + /** + * Load a Mustache partial Template by name. + * + * This is a helper method used internally by Template instances for loading partial templates. You can most likely + * ignore it completely. + * + * @param string $name + * + * @return Mustache_Template + */ + public function loadPartial($name) + { + try { + return $this->loadSource($this->getPartialsLoader()->load($name)); + } catch (InvalidArgumentException $e) { + // If the named partial cannot be found, return null. + } + } - /** - * Load a Mustache lambda Template by source. - * - * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most - * likely ignore it completely. - * - * @param string $source - * @param string $delims (default: null) - * - * @return Mustache_Template - */ - public function loadLambda($source, $delims = null) { - if ($delims !== null) { - $source = $delims . "\n" . $source; - } + /** + * Load a Mustache lambda Template by source. + * + * This is a helper method used by Template instances to generate subtemplates for Lambda sections. You can most + * likely ignore it completely. + * + * @param string $source + * @param string $delims (default: null) + * + * @return Mustache_Template + */ + public function loadLambda($source, $delims = null) + { + if ($delims !== null) { + $source = $delims . "\n" . $source; + } - return $this->loadSource($source); - } + return $this->loadSource($source); + } - /** - * Instantiate and return a Mustache Template instance by source. - * - * @see Mustache_Engine::loadTemplate - * @see Mustache_Engine::loadPartial - * @see Mustache_Engine::loadLambda - * - * @param string $source - * - * @return Mustache_Template - */ - private function loadSource($source) { - $className = $this->getTemplateClassName($source); + /** + * Instantiate and return a Mustache Template instance by source. + * + * @see Mustache_Engine::loadTemplate + * @see Mustache_Engine::loadPartial + * @see Mustache_Engine::loadLambda + * + * @param string $source + * + * @return Mustache_Template + */ + private function loadSource($source) + { + $className = $this->getTemplateClassName($source); - if (!isset($this->templates[$className])) { - if (!class_exists($className, false)) { - if ($fileName = $this->getCacheFilename($source)) { - if (!is_file($fileName)) { - $this->writeCacheFile($fileName, $this->compile($source)); - } + if (!isset($this->templates[$className])) { + if (!class_exists($className, false)) { + if ($fileName = $this->getCacheFilename($source)) { + if (!is_file($fileName)) { + $this->writeCacheFile($fileName, $this->compile($source)); + } - require_once $fileName; - } else { - eval('?>'.$this->compile($source)); - } - } + require_once $fileName; + } else { + eval('?>'.$this->compile($source)); + } + } - $this->templates[$className] = new $className($this); - } + $this->templates[$className] = new $className($this); + } - return $this->templates[$className]; - } + return $this->templates[$className]; + } - /** - * Helper method to tokenize a Mustache template. - * - * @see Mustache_Tokenizer::scan - * - * @param string $source - * - * @return array Tokens - */ - private function tokenize($source) { - return $this->getTokenizer()->scan($source); - } + /** + * Helper method to tokenize a Mustache template. + * + * @see Mustache_Tokenizer::scan + * + * @param string $source + * + * @return array Tokens + */ + private function tokenize($source) + { + return $this->getTokenizer()->scan($source); + } - /** - * Helper method to parse a Mustache template. - * - * @see Mustache_Parser::parse - * - * @param string $source - * - * @return array Token tree - */ - private function parse($source) { - return $this->getParser()->parse($this->tokenize($source)); - } + /** + * Helper method to parse a Mustache template. + * + * @see Mustache_Parser::parse + * + * @param string $source + * + * @return array Token tree + */ + private function parse($source) + { + return $this->getParser()->parse($this->tokenize($source)); + } - /** - * Helper method to compile a Mustache template. - * - * @see Mustache_Compiler::compile - * - * @param string $source - * - * @return string generated Mustache template class code - */ - private function compile($source) { - $tree = $this->parse($source); - $name = $this->getTemplateClassName($source); + /** + * Helper method to compile a Mustache template. + * + * @see Mustache_Compiler::compile + * + * @param string $source + * + * @return string generated Mustache template class code + */ + private function compile($source) + { + $tree = $this->parse($source); + $name = $this->getTemplateClassName($source); - return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset); - } + return $this->getCompiler()->compile($source, $tree, $name, isset($this->escape), $this->charset); + } - /** - * Helper method to generate a Mustache Template class cache filename. - * - * @param string $source - * - * @return string Mustache Template class cache filename - */ - private function getCacheFilename($source) { - if ($this->cache) { - return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source)); - } - } + /** + * Helper method to generate a Mustache Template class cache filename. + * + * @param string $source + * + * @return string Mustache Template class cache filename + */ + private function getCacheFilename($source) + { + if ($this->cache) { + return sprintf('%s/%s.php', $this->cache, $this->getTemplateClassName($source)); + } + } - /** - * Helper method to dump a generated Mustache Template subclass to the file cache. - * - * @throws RuntimeException if unable to write to $fileName. - * - * @param string $fileName - * @param string $source - */ - private function writeCacheFile($fileName, $source) { - if (!is_dir(dirname($fileName))) { - mkdir(dirname($fileName), 0777, true); - } + /** + * Helper method to dump a generated Mustache Template subclass to the file cache. + * + * @throws RuntimeException if unable to write to $fileName. + * + * @param string $fileName + * @param string $source + */ + private function writeCacheFile($fileName, $source) + { + if (!is_dir(dirname($fileName))) { + mkdir(dirname($fileName), 0777, true); + } - $tempFile = tempnam(dirname($fileName), basename($fileName)); - if (false !== @file_put_contents($tempFile, $source)) { - if (@rename($tempFile, $fileName)) { - chmod($fileName, 0644); + $tempFile = tempnam(dirname($fileName), basename($fileName)); + if (false !== @file_put_contents($tempFile, $source)) { + if (@rename($tempFile, $fileName)) { + chmod($fileName, 0644); - return; - } - } + return; + } + } - throw new RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); - } + throw new RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); + } } diff --git a/src/Mustache/HelperCollection.php b/src/Mustache/HelperCollection.php index 366556e..f6354e6 100644 --- a/src/Mustache/HelperCollection.php +++ b/src/Mustache/HelperCollection.php @@ -12,145 +12,157 @@ /** * A collection of helpers for a Mustache instance. */ -class Mustache_HelperCollection { - private $helpers = array(); +class Mustache_HelperCollection +{ + private $helpers = array(); - /** - * Helper Collection constructor. - * - * Optionally accepts an array (or Traversable) of `$name => $helper` pairs. - * - * @throws InvalidArgumentException if the $helpers argument isn't an array or Traversable - * - * @param array|Traversable $helpers (default: null) - */ - public function __construct($helpers = null) { - if ($helpers !== null) { - if (!is_array($helpers) && !$helpers instanceof Traversable) { - throw new InvalidArgumentException('HelperCollection constructor expects an array of helpers'); - } + /** + * Helper Collection constructor. + * + * Optionally accepts an array (or Traversable) of `$name => $helper` pairs. + * + * @throws InvalidArgumentException if the $helpers argument isn't an array or Traversable + * + * @param array|Traversable $helpers (default: null) + */ + public function __construct($helpers = null) + { + if ($helpers !== null) { + if (!is_array($helpers) && !$helpers instanceof Traversable) { + throw new InvalidArgumentException('HelperCollection constructor expects an array of helpers'); + } - foreach ($helpers as $name => $helper) { - $this->add($name, $helper); - } - } - } + foreach ($helpers as $name => $helper) { + $this->add($name, $helper); + } + } + } - /** - * Magic mutator. - * - * @see Mustache_HelperCollection::add - * - * @param string $name - * @param mixed $helper - */ - public function __set($name, $helper) { - $this->add($name, $helper); - } + /** + * Magic mutator. + * + * @see Mustache_HelperCollection::add + * + * @param string $name + * @param mixed $helper + */ + public function __set($name, $helper) + { + $this->add($name, $helper); + } - /** - * Add a helper to this collection. - * - * @param string $name - * @param mixed $helper - */ - public function add($name, $helper) { - $this->helpers[$name] = $helper; - } + /** + * Add a helper to this collection. + * + * @param string $name + * @param mixed $helper + */ + public function add($name, $helper) + { + $this->helpers[$name] = $helper; + } - /** - * Magic accessor. - * - * @see Mustache_HelperCollection::get - * - * @param string $name - * - * @return mixed Helper - */ - public function __get($name) { - return $this->get($name); - } + /** + * Magic accessor. + * + * @see Mustache_HelperCollection::get + * + * @param string $name + * + * @return mixed Helper + */ + public function __get($name) + { + return $this->get($name); + } - /** - * Get a helper by name. - * - * @param string $name - * - * @return mixed Helper - */ - public function get($name) { - if (!$this->has($name)) { - throw new InvalidArgumentException('Unknown helper: '.$name); - } + /** + * Get a helper by name. + * + * @param string $name + * + * @return mixed Helper + */ + public function get($name) + { + if (!$this->has($name)) { + throw new InvalidArgumentException('Unknown helper: '.$name); + } - return $this->helpers[$name]; - } + return $this->helpers[$name]; + } - /** - * Magic isset(). - * - * @see Mustache_HelperCollection::has - * - * @param string $name - * - * @return boolean True if helper is present - */ - public function __isset($name) { - return $this->has($name); - } + /** + * Magic isset(). + * + * @see Mustache_HelperCollection::has + * + * @param string $name + * + * @return boolean True if helper is present + */ + public function __isset($name) + { + return $this->has($name); + } - /** - * Check whether a given helper is present in the collection. - * - * @param string $name - * - * @return boolean True if helper is present - */ - public function has($name) { - return array_key_exists($name, $this->helpers); - } + /** + * Check whether a given helper is present in the collection. + * + * @param string $name + * + * @return boolean True if helper is present + */ + public function has($name) + { + return array_key_exists($name, $this->helpers); + } - /** - * Magic unset(). - * - * @see Mustache_HelperCollection::remove - * - * @param string $name - */ - public function __unset($name) { - $this->remove($name); - } + /** + * Magic unset(). + * + * @see Mustache_HelperCollection::remove + * + * @param string $name + */ + public function __unset($name) + { + $this->remove($name); + } - /** - * Check whether a given helper is present in the collection. - * - * @throws InvalidArgumentException if the requested helper is not present. - * - * @param string $name - */ - public function remove($name) { - if (!$this->has($name)) { - throw new InvalidArgumentException('Unknown helper: '.$name); - } + /** + * Check whether a given helper is present in the collection. + * + * @throws InvalidArgumentException if the requested helper is not present. + * + * @param string $name + */ + public function remove($name) + { + if (!$this->has($name)) { + throw new InvalidArgumentException('Unknown helper: '.$name); + } - unset($this->helpers[$name]); - } + unset($this->helpers[$name]); + } - /** - * Clear the helper collection. - * - * Removes all helpers from this collection - */ - public function clear() { - $this->helpers = array(); - } + /** + * Clear the helper collection. + * + * Removes all helpers from this collection + */ + public function clear() + { + $this->helpers = array(); + } - /** - * Check whether the helper collection is empty. - * - * @return boolean True if the collection is empty - */ - public function isEmpty() { - return empty($this->helpers); - } + /** + * Check whether the helper collection is empty. + * + * @return boolean True if the collection is empty + */ + public function isEmpty() + { + return empty($this->helpers); + } } diff --git a/src/Mustache/Loader.php b/src/Mustache/Loader.php index bdd2817..21229d1 100644 --- a/src/Mustache/Loader.php +++ b/src/Mustache/Loader.php @@ -12,14 +12,15 @@ /** * Mustache Template Loader interface. */ -interface Mustache_Loader { +interface Mustache_Loader +{ - /** - * Load a Template by name. - * - * @param string $name - * - * @return string Mustache Template source - */ - function load($name); + /** + * Load a Template by name. + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name); } diff --git a/src/Mustache/Loader/ArrayLoader.php b/src/Mustache/Loader/ArrayLoader.php index 9def8b5..1ce6e20 100644 --- a/src/Mustache/Loader/ArrayLoader.php +++ b/src/Mustache/Loader/ArrayLoader.php @@ -27,48 +27,53 @@ * @implements Loader * @implements MutableLoader */ -class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader { +class Mustache_Loader_ArrayLoader implements Mustache_Loader, Mustache_Loader_MutableLoader +{ - /** - * ArrayLoader constructor. - * - * @param array $templates Associative array of Template source (default: array()) - */ - public function __construct(array $templates = array()) { - $this->templates = $templates; - } + /** + * ArrayLoader constructor. + * + * @param array $templates Associative array of Template source (default: array()) + */ + public function __construct(array $templates = array()) + { + $this->templates = $templates; + } - /** - * Load a Template. - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) { - if (!isset($this->templates[$name])) { - throw new InvalidArgumentException('Template '.$name.' not found.'); - } + /** + * Load a Template. + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name) + { + if (!isset($this->templates[$name])) { + throw new InvalidArgumentException('Template '.$name.' not found.'); + } - return $this->templates[$name]; - } + return $this->templates[$name]; + } - /** - * Set an associative array of Template sources for this loader. - * - * @param array $templates - */ - public function setTemplates(array $templates) { - $this->templates = $templates; - } + /** + * Set an associative array of Template sources for this loader. + * + * @param array $templates + */ + public function setTemplates(array $templates) + { + $this->templates = $templates; + } - /** - * Set a Template source by name. - * - * @param string $name - * @param string $template Mustache Template source - */ - public function setTemplate($name, $template) { - $this->templates[$name] = $template; - } + /** + * Set a Template source by name. + * + * @param string $name + * @param string $template Mustache Template source + */ + public function setTemplate($name, $template) + { + $this->templates[$name] = $template; + } } diff --git a/src/Mustache/Loader/FilesystemLoader.php b/src/Mustache/Loader/FilesystemLoader.php index ecb98c8..dc488f2 100644 --- a/src/Mustache/Loader/FilesystemLoader.php +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -26,88 +26,93 @@ * * @implements Loader */ -class Mustache_Loader_FilesystemLoader implements Mustache_Loader { - private $baseDir; - private $extension = '.mustache'; - private $templates = array(); +class Mustache_Loader_FilesystemLoader implements Mustache_Loader +{ + private $baseDir; + private $extension = '.mustache'; + private $templates = array(); - /** - * Mustache filesystem Loader constructor. - * - * Passing an $options array allows overriding certain Loader options during instantiation: - * - * $options = array( - * // The filename extension used for Mustache templates. Defaults to '.mustache' - * 'extension' => '.ms', - * ); - * - * @throws RuntimeException if $baseDir does not exist. - * - * @param string $baseDir Base directory containing Mustache template files. - * @param array $options Array of Loader options (default: array()) - */ - public function __construct($baseDir, array $options = array()) { - $this->baseDir = rtrim(realpath($baseDir), '/'); + /** + * Mustache filesystem Loader constructor. + * + * Passing an $options array allows overriding certain Loader options during instantiation: + * + * $options = array( + * // The filename extension used for Mustache templates. Defaults to '.mustache' + * 'extension' => '.ms', + * ); + * + * @throws RuntimeException if $baseDir does not exist. + * + * @param string $baseDir Base directory containing Mustache template files. + * @param array $options Array of Loader options (default: array()) + */ + public function __construct($baseDir, array $options = array()) + { + $this->baseDir = rtrim(realpath($baseDir), '/'); - if (!is_dir($this->baseDir)) { - throw new RuntimeException('FilesystemLoader baseDir must be a directory: '.$baseDir); - } + if (!is_dir($this->baseDir)) { + throw new RuntimeException('FilesystemLoader baseDir must be a directory: '.$baseDir); + } - if (isset($options['extension'])) { - $this->extension = '.' . ltrim($options['extension'], '.'); - } - } + if (isset($options['extension'])) { + $this->extension = '.' . ltrim($options['extension'], '.'); + } + } - /** - * Load a Template by name. - * - * $loader = new FilesystemLoader(dirname(__FILE__).'/views'); - * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; - * - * @param string $name - * - * @return string Mustache Template source - */ - public function load($name) { - if (!isset($this->templates[$name])) { - $this->templates[$name] = $this->loadFile($name); - } + /** + * Load a Template by name. + * + * $loader = new FilesystemLoader(dirname(__FILE__).'/views'); + * $loader->load('admin/dashboard'); // loads "./views/admin/dashboard.mustache"; + * + * @param string $name + * + * @return string Mustache Template source + */ + public function load($name) + { + if (!isset($this->templates[$name])) { + $this->templates[$name] = $this->loadFile($name); + } - return $this->templates[$name]; - } + return $this->templates[$name]; + } - /** - * Helper function for loading a Mustache file by name. - * - * @throws InvalidArgumentException if a template file is not found. - * - * @param string $name - * - * @return string Mustache Template source - */ - private function loadFile($name) { - $fileName = $this->getFileName($name); + /** + * Helper function for loading a Mustache file by name. + * + * @throws InvalidArgumentException if a template file is not found. + * + * @param string $name + * + * @return string Mustache Template source + */ + private function loadFile($name) + { + $fileName = $this->getFileName($name); - if (!file_exists($fileName)) { - throw new InvalidArgumentException('Template '.$name.' not found.'); - } + if (!file_exists($fileName)) { + throw new InvalidArgumentException('Template '.$name.' not found.'); + } - return file_get_contents($fileName); - } + return file_get_contents($fileName); + } - /** - * Helper function for getting a Mustache template file name. - * - * @param string $name - * - * @return string Template file name - */ - private function getFileName($name) { - $fileName = $this->baseDir . '/' . $name; - if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) { - $fileName .= $this->extension; - } + /** + * Helper function for getting a Mustache template file name. + * + * @param string $name + * + * @return string Template file name + */ + private function getFileName($name) + { + $fileName = $this->baseDir . '/' . $name; + if (substr($fileName, 0 - strlen($this->extension)) !== $this->extension) { + $fileName .= $this->extension; + } - return $fileName; - } + return $fileName; + } } diff --git a/src/Mustache/Loader/MutableLoader.php b/src/Mustache/Loader/MutableLoader.php index 0af14c2..02bb207 100644 --- a/src/Mustache/Loader/MutableLoader.php +++ b/src/Mustache/Loader/MutableLoader.php @@ -12,20 +12,21 @@ /** * Mustache Template mutable Loader interface. */ -interface Mustache_Loader_MutableLoader { +interface Mustache_Loader_MutableLoader +{ - /** - * Set an associative array of Template sources for this loader. - * - * @param array $templates - */ - function setTemplates(array $templates); + /** + * Set an associative array of Template sources for this loader. + * + * @param array $templates + */ + public function setTemplates(array $templates); - /** - * Set a Template source by name. - * - * @param string $name - * @param string $template Mustache Template source - */ - function setTemplate($name, $template); + /** + * Set a Template source by name. + * + * @param string $name + * @param string $template Mustache Template source + */ + public function setTemplate($name, $template); } diff --git a/src/Mustache/Loader/StringLoader.php b/src/Mustache/Loader/StringLoader.php index 88b253f..aa8fcf7 100644 --- a/src/Mustache/Loader/StringLoader.php +++ b/src/Mustache/Loader/StringLoader.php @@ -25,16 +25,18 @@ * * @implements Loader */ -class Mustache_Loader_StringLoader implements Mustache_Loader { +class Mustache_Loader_StringLoader implements Mustache_Loader +{ - /** - * Load a Template by source. - * - * @param string $name Mustache Template source - * - * @return string Mustache Template source - */ - public function load($name) { - return $name; - } + /** + * Load a Template by source. + * + * @param string $name Mustache Template source + * + * @return string Mustache Template source + */ + public function load($name) + { + return $name; + } } diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index eb71859..5b31823 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -14,72 +14,75 @@ * * This class is responsible for turning a set of Mustache tokens into a parse tree. */ -class Mustache_Parser { +class Mustache_Parser +{ - /** - * Process an array of Mustache tokens and convert them into a parse tree. - * - * @param array $tokens Set of Mustache tokens - * - * @return array Mustache token parse tree - */ - public function parse(array $tokens = array()) { - return $this->buildTree(new ArrayIterator($tokens)); - } + /** + * Process an array of Mustache tokens and convert them into a parse tree. + * + * @param array $tokens Set of Mustache tokens + * + * @return array Mustache token parse tree + */ + public function parse(array $tokens = array()) + { + return $this->buildTree(new ArrayIterator($tokens)); + } - /** - * Helper method for recursively building a parse tree. - * - * @throws LogicException when nesting errors or mismatched section tags are encountered. - * - * @param ArrayIterator $tokens Stream of Mustache tokens - * @param array $parent Parent token (default: null) - * - * @return array Mustache Token parse tree - */ - private function buildTree(ArrayIterator $tokens, array $parent = null) { - $nodes = array(); + /** + * Helper method for recursively building a parse tree. + * + * @throws LogicException when nesting errors or mismatched section tags are encountered. + * + * @param ArrayIterator $tokens Stream of Mustache tokens + * @param array $parent Parent token (default: null) + * + * @return array Mustache Token parse tree + */ + private function buildTree(ArrayIterator $tokens, array $parent = null) + { + $nodes = array(); - do { - $token = $tokens->current(); - $tokens->next(); + do { + $token = $tokens->current(); + $tokens->next(); - if ($token === null) { - continue; - } else { - switch ($token[Mustache_Tokenizer::TYPE]) { - case Mustache_Tokenizer::T_SECTION: - case Mustache_Tokenizer::T_INVERTED: - $nodes[] = $this->buildTree($tokens, $token); - break; + if ($token === null) { + continue; + } else { + switch ($token[Mustache_Tokenizer::TYPE]) { + case Mustache_Tokenizer::T_SECTION: + case Mustache_Tokenizer::T_INVERTED: + $nodes[] = $this->buildTree($tokens, $token); + break; - case Mustache_Tokenizer::T_END_SECTION: - if (!isset($parent)) { - throw new LogicException('Unexpected closing tag: /'. $token[Mustache_Tokenizer::NAME]); - } + case Mustache_Tokenizer::T_END_SECTION: + if (!isset($parent)) { + throw new LogicException('Unexpected closing tag: /'. $token[Mustache_Tokenizer::NAME]); + } - if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { - throw new LogicException('Nesting error: ' . $parent[Mustache_Tokenizer::NAME] . ' vs. ' . $token[Mustache_Tokenizer::NAME]); - } + if ($token[Mustache_Tokenizer::NAME] !== $parent[Mustache_Tokenizer::NAME]) { + throw new LogicException('Nesting error: ' . $parent[Mustache_Tokenizer::NAME] . ' vs. ' . $token[Mustache_Tokenizer::NAME]); + } - $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; - $parent[Mustache_Tokenizer::NODES] = $nodes; + $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; + $parent[Mustache_Tokenizer::NODES] = $nodes; - return $parent; - break; + return $parent; + break; - default: - $nodes[] = $token; - break; - } - } + default: + $nodes[] = $token; + break; + } + } - } while ($tokens->valid()); + } while ($tokens->valid()); - if (isset($parent)) { - throw new LogicException('Missing closing tag: ' . $parent[Mustache_Tokenizer::NAME]); - } + if (isset($parent)) { + throw new LogicException('Missing closing tag: ' . $parent[Mustache_Tokenizer::NAME]); + } - return $nodes; - } + return $nodes; + } } diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 5ec4d51..819efbf 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -14,130 +14,136 @@ * * @abstract */ -abstract class Mustache_Template { +abstract class Mustache_Template +{ - /** - * @var Mustache_Engine - */ - protected $mustache; + /** + * @var Mustache_Engine + */ + protected $mustache; - /** - * Mustache Template constructor. - * - * @param Mustache_Engine $mustache - */ - public function __construct(Mustache_Engine $mustache) { - $this->mustache = $mustache; - } + /** + * Mustache Template constructor. + * + * @param Mustache_Engine $mustache + */ + public function __construct(Mustache_Engine $mustache) + { + $this->mustache = $mustache; + } - /** - * Mustache Template instances can be treated as a function and rendered by simply calling them: - * - * $m = new Mustache_Engine; - * $tpl = $m->loadTemplate('Hello, {{ name }}!'); - * echo $tpl(array('name' => 'World')); // "Hello, World!" - * - * @see Mustache_Template::render - * - * @param mixed $context Array or object rendering context (default: array()) - * - * @return string Rendered template - */ - public function __invoke($context = array()) { - return $this->render($context); - } + /** + * Mustache Template instances can be treated as a function and rendered by simply calling them: + * + * $m = new Mustache_Engine; + * $tpl = $m->loadTemplate('Hello, {{ name }}!'); + * echo $tpl(array('name' => 'World')); // "Hello, World!" + * + * @see Mustache_Template::render + * + * @param mixed $context Array or object rendering context (default: array()) + * + * @return string Rendered template + */ + public function __invoke($context = array()) + { + return $this->render($context); + } - /** - * Render this template given the rendering context. - * - * @param mixed $context Array or object rendering context (default: array()) - * - * @return string Rendered template - */ - public function render($context = array()) { - return $this->renderInternal($this->prepareContextStack($context)); - } + /** + * Render this template given the rendering context. + * + * @param mixed $context Array or object rendering context (default: array()) + * + * @return string Rendered template + */ + public function render($context = array()) + { + return $this->renderInternal($this->prepareContextStack($context)); + } - /** - * Internal rendering method implemented by Mustache Template concrete subclasses. - * - * This is where the magic happens :) - * - * @abstract - * - * @param Mustache_Context $context - * - * @return string Rendered template - */ - abstract public function renderInternal(Mustache_Context $context, $indent = '', $escape = false); + /** + * Internal rendering method implemented by Mustache Template concrete subclasses. + * + * This is where the magic happens :) + * + * @abstract + * + * @param Mustache_Context $context + * + * @return string Rendered template + */ + abstract public function renderInternal(Mustache_Context $context, $indent = '', $escape = false); - /** - * Tests whether a value should be iterated over (e.g. in a section context). - * - * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists - * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, - * Java, Python, etc. - * - * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish - * between between a list of things (numeric, normalized array) and a set of variables to be used as section context - * (associative array). In other words, this will be iterated over: - * - * $items = array( - * array('name' => 'foo'), - * array('name' => 'bar'), - * array('name' => 'baz'), - * ); - * - * ... but this will be used as a section context block: - * - * $items = array( - * 1 => array('name' => 'foo'), - * 'banana' => array('name' => 'bar'), - * 42 => array('name' => 'baz'), - * ); - * - * @param mixed $value - * - * @return boolean True if the value is 'iterable' - */ - protected function isIterable($value) { - if (is_object($value)) { - return $value instanceof Traversable; - } elseif (is_array($value)) { - $i = 0; - foreach ($value as $k => $v) { - if ($k !== $i++) { - return false; - } - } + /** + * Tests whether a value should be iterated over (e.g. in a section context). + * + * In most languages there are two distinct array types: list and hash (or whatever you want to call them). Lists + * should be iterated, hashes should be treated as objects. Mustache follows this paradigm for Ruby, Javascript, + * Java, Python, etc. + * + * PHP, however, treats lists and hashes as one primitive type: array. So Mustache.php needs a way to distinguish + * between between a list of things (numeric, normalized array) and a set of variables to be used as section context + * (associative array). In other words, this will be iterated over: + * + * $items = array( + * array('name' => 'foo'), + * array('name' => 'bar'), + * array('name' => 'baz'), + * ); + * + * ... but this will be used as a section context block: + * + * $items = array( + * 1 => array('name' => 'foo'), + * 'banana' => array('name' => 'bar'), + * 42 => array('name' => 'baz'), + * ); + * + * @param mixed $value + * + * @return boolean True if the value is 'iterable' + */ + protected function isIterable($value) + { + if (is_object($value)) { + return $value instanceof Traversable; + } elseif (is_array($value)) { + $i = 0; + foreach ($value as $k => $v) { + if ($k !== $i++) { + return false; + } + } - return true; - } else { - return false; - } - } + return true; + } else { + return false; + } + } - /** - * Helper method to prepare the Context stack. - * - * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present. - * - * @param mixed $context Optional first context frame (default: null) - * - * @return Mustache_Context - */ - protected function prepareContextStack($context = null) { - $stack = new Mustache_Context; + /** + * Helper method to prepare the Context stack. + * + * Adds the Mustache HelperCollection to the stack's top context frame if helpers are present. + * + * @param mixed $context Optional first context frame (default: null) + * + * @return Mustache_Context + */ + protected function prepareContextStack($context = null) + { + $stack = new Mustache_Context; - $helpers = $this->mustache->getHelpers(); - if (!$helpers->isEmpty()) { - $stack->push($helpers); - } + $helpers = $this->mustache->getHelpers(); + if (!$helpers->isEmpty()) { + $stack->push($helpers); + } - if (!empty($context)) { - $stack->push($context); - } + if (!empty($context)) { + $stack->push($context); + } - return $stack; - } + return $stack; + } } diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index 2aff838..6ecbfea 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -16,263 +16,270 @@ */ class Mustache_Tokenizer { - // Finite state machine states - const IN_TEXT = 0; - const IN_TAG_TYPE = 1; - const IN_TAG = 2; + // Finite state machine states + const IN_TEXT = 0; + const IN_TAG_TYPE = 1; + const IN_TAG = 2; - // Token types - const T_SECTION = '#'; - const T_INVERTED = '^'; - const T_END_SECTION = '/'; - const T_COMMENT = '!'; - const T_PARTIAL = '>'; - const T_PARTIAL_2 = '<'; - const T_DELIM_CHANGE = '='; - const T_ESCAPED = '_v'; - const T_UNESCAPED = '{'; - const T_UNESCAPED_2 = '&'; - const T_TEXT = '_t'; + // Token types + const T_SECTION = '#'; + const T_INVERTED = '^'; + const T_END_SECTION = '/'; + const T_COMMENT = '!'; + const T_PARTIAL = '>'; + const T_PARTIAL_2 = '<'; + const T_DELIM_CHANGE = '='; + const T_ESCAPED = '_v'; + const T_UNESCAPED = '{'; + const T_UNESCAPED_2 = '&'; + const T_TEXT = '_t'; - // Valid token types - private static $tagTypes = array( - self::T_SECTION => true, - self::T_INVERTED => true, - self::T_END_SECTION => true, - self::T_COMMENT => true, - self::T_PARTIAL => true, - self::T_PARTIAL_2 => true, - self::T_DELIM_CHANGE => true, - self::T_ESCAPED => true, - self::T_UNESCAPED => true, - self::T_UNESCAPED_2 => true, - ); + // Valid token types + private static $tagTypes = array( + self::T_SECTION => true, + self::T_INVERTED => true, + self::T_END_SECTION => true, + self::T_COMMENT => true, + self::T_PARTIAL => true, + self::T_PARTIAL_2 => true, + self::T_DELIM_CHANGE => true, + self::T_ESCAPED => true, + self::T_UNESCAPED => true, + self::T_UNESCAPED_2 => true, + ); - // Interpolated tags - private static $interpolatedTags = array( - self::T_ESCAPED => true, - self::T_UNESCAPED => true, - self::T_UNESCAPED_2 => true, - ); + // Interpolated tags + private static $interpolatedTags = array( + self::T_ESCAPED => true, + self::T_UNESCAPED => true, + self::T_UNESCAPED_2 => true, + ); - // Token properties - const TYPE = 'type'; - const NAME = 'name'; - const OTAG = 'otag'; - const CTAG = 'ctag'; - const INDEX = 'index'; - const END = 'end'; - const INDENT = 'indent'; - const NODES = 'nodes'; - const VALUE = 'value'; + // Token properties + const TYPE = 'type'; + const NAME = 'name'; + const OTAG = 'otag'; + const CTAG = 'ctag'; + const INDEX = 'index'; + const END = 'end'; + const INDENT = 'indent'; + const NODES = 'nodes'; + const VALUE = 'value'; - private $state; - private $tagType; - private $tag; - private $buffer; - private $tokens; - private $seenTag; - private $lineStart; - private $otag; - private $ctag; + private $state; + private $tagType; + private $tag; + private $buffer; + private $tokens; + private $seenTag; + private $lineStart; + private $otag; + private $ctag; - /** - * Scan and tokenize template source. - * - * @param string $text Mustache template source to tokenize - * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null) - * - * @return array Set of Mustache tokens - */ - public function scan($text, $delimiters = null) { - $this->reset(); + /** + * Scan and tokenize template source. + * + * @param string $text Mustache template source to tokenize + * @param string $delimiters Optionally, pass initial opening and closing delimiters (default: null) + * + * @return array Set of Mustache tokens + */ + public function scan($text, $delimiters = null) + { + $this->reset(); - if ($delimiters = trim($delimiters)) { - list($otag, $ctag) = explode(' ', $delimiters); - $this->otag = $otag; - $this->ctag = $ctag; - } + if ($delimiters = trim($delimiters)) { + list($otag, $ctag) = explode(' ', $delimiters); + $this->otag = $otag; + $this->ctag = $ctag; + } - $len = strlen($text); - for ($i = 0; $i < $len; $i++) { - switch ($this->state) { - case self::IN_TEXT: - if ($this->tagChange($this->otag, $text, $i)) { - $i--; - $this->flushBuffer(); - $this->state = self::IN_TAG_TYPE; - } else { - if ($text[$i] == "\n") { - $this->filterLine(); - } else { - $this->buffer .= $text[$i]; - } - } - break; + $len = strlen($text); + for ($i = 0; $i < $len; $i++) { + switch ($this->state) { + case self::IN_TEXT: + if ($this->tagChange($this->otag, $text, $i)) { + $i--; + $this->flushBuffer(); + $this->state = self::IN_TAG_TYPE; + } else { + if ($text[$i] == "\n") { + $this->filterLine(); + } else { + $this->buffer .= $text[$i]; + } + } + break; - case self::IN_TAG_TYPE: + case self::IN_TAG_TYPE: - $i += strlen($this->otag) - 1; - if (isset(self::$tagTypes[$text[$i + 1]])) { - $tag = $text[$i + 1]; - $this->tagType = $tag; - } else { - $tag = null; - $this->tagType = self::T_ESCAPED; - } + $i += strlen($this->otag) - 1; + if (isset(self::$tagTypes[$text[$i + 1]])) { + $tag = $text[$i + 1]; + $this->tagType = $tag; + } else { + $tag = null; + $this->tagType = self::T_ESCAPED; + } - if ($this->tagType === self::T_DELIM_CHANGE) { - $i = $this->changeDelimiters($text, $i); - $this->state = self::IN_TEXT; - } else { - if ($tag !== null) { - $i++; - } - $this->state = self::IN_TAG; - } - $this->seenTag = $i; - break; + if ($this->tagType === self::T_DELIM_CHANGE) { + $i = $this->changeDelimiters($text, $i); + $this->state = self::IN_TEXT; + } else { + if ($tag !== null) { + $i++; + } + $this->state = self::IN_TAG; + } + $this->seenTag = $i; + break; - default: - if ($this->tagChange($this->ctag, $text, $i)) { - $this->tokens[] = array( - self::TYPE => $this->tagType, - self::NAME => trim($this->buffer), - self::OTAG => $this->otag, - self::CTAG => $this->ctag, - self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) - ); + default: + if ($this->tagChange($this->ctag, $text, $i)) { + $this->tokens[] = array( + self::TYPE => $this->tagType, + self::NAME => trim($this->buffer), + self::OTAG => $this->otag, + self::CTAG => $this->ctag, + self::INDEX => ($this->tagType == self::T_END_SECTION) ? $this->seenTag - strlen($this->otag) : $i + strlen($this->ctag) + ); - $this->buffer = ''; - $i += strlen($this->ctag) - 1; - $this->state = self::IN_TEXT; - if ($this->tagType == self::T_UNESCAPED) { - if ($this->ctag == '}}') { - $i++; - } else { - // Clean up `{{{ tripleStache }}}` style tokens. - $lastName = $this->tokens[count($this->tokens) - 1][self::NAME]; - if (substr($lastName, -1) === '}') { - $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1)); - } - } - } - } else { - $this->buffer .= $text[$i]; - } - break; - } - } + $this->buffer = ''; + $i += strlen($this->ctag) - 1; + $this->state = self::IN_TEXT; + if ($this->tagType == self::T_UNESCAPED) { + if ($this->ctag == '}}') { + $i++; + } else { + // Clean up `{{{ tripleStache }}}` style tokens. + $lastName = $this->tokens[count($this->tokens) - 1][self::NAME]; + if (substr($lastName, -1) === '}') { + $this->tokens[count($this->tokens) - 1][self::NAME] = trim(substr($lastName, 0, -1)); + } + } + } + } else { + $this->buffer .= $text[$i]; + } + break; + } + } - $this->filterLine(true); + $this->filterLine(true); - return $this->tokens; - } + return $this->tokens; + } - /** - * Helper function to reset tokenizer internal state. - */ - private function reset() { - $this->state = self::IN_TEXT; - $this->tagType = null; - $this->tag = null; - $this->buffer = ''; - $this->tokens = array(); - $this->seenTag = false; - $this->lineStart = 0; - $this->otag = '{{'; - $this->ctag = '}}'; - } + /** + * Helper function to reset tokenizer internal state. + */ + private function reset() + { + $this->state = self::IN_TEXT; + $this->tagType = null; + $this->tag = null; + $this->buffer = ''; + $this->tokens = array(); + $this->seenTag = false; + $this->lineStart = 0; + $this->otag = '{{'; + $this->ctag = '}}'; + } - /** - * Flush the current buffer to a token. - */ - private function flushBuffer() { - if (!empty($this->buffer)) { - $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => $this->buffer); - $this->buffer = ''; - } - } + /** + * Flush the current buffer to a token. + */ + private function flushBuffer() + { + if (!empty($this->buffer)) { + $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => $this->buffer); + $this->buffer = ''; + } + } - /** - * Test whether the current line is entirely made up of whitespace. - * - * @return boolean True if the current line is all whitespace - */ - private function lineIsWhitespace() { - $tokensCount = count($this->tokens); - for ($j = $this->lineStart; $j < $tokensCount; $j++) { - $token = $this->tokens[$j]; - if (isset(self::$tagTypes[$token[self::TYPE]])) { - if (isset(self::$interpolatedTags[$token[self::TYPE]])) { - return false; - } - } elseif ($token[self::TYPE] == self::T_TEXT) { - if (preg_match('/\S/', $token[self::VALUE])) { - return false; - } - } - } + /** + * Test whether the current line is entirely made up of whitespace. + * + * @return boolean True if the current line is all whitespace + */ + private function lineIsWhitespace() + { + $tokensCount = count($this->tokens); + for ($j = $this->lineStart; $j < $tokensCount; $j++) { + $token = $this->tokens[$j]; + if (isset(self::$tagTypes[$token[self::TYPE]])) { + if (isset(self::$interpolatedTags[$token[self::TYPE]])) { + return false; + } + } elseif ($token[self::TYPE] == self::T_TEXT) { + if (preg_match('/\S/', $token[self::VALUE])) { + return false; + } + } + } - return true; - } + return true; + } - /** - * Filter out whitespace-only lines and store indent levels for partials. - * - * @param bool $noNewLine Suppress the newline? (default: false) - */ - private function filterLine($noNewLine = false) { - $this->flushBuffer(); - if ($this->seenTag && $this->lineIsWhitespace()) { - $tokensCount = count($this->tokens); - for ($j = $this->lineStart; $j < $tokensCount; $j++) { - if ($this->tokens[$j][self::TYPE] == self::T_TEXT) { - if (isset($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { - $this->tokens[$j+1][self::INDENT] = $this->tokens[$j][self::VALUE]; - } + /** + * Filter out whitespace-only lines and store indent levels for partials. + * + * @param bool $noNewLine Suppress the newline? (default: false) + */ + private function filterLine($noNewLine = false) + { + $this->flushBuffer(); + if ($this->seenTag && $this->lineIsWhitespace()) { + $tokensCount = count($this->tokens); + for ($j = $this->lineStart; $j < $tokensCount; $j++) { + if ($this->tokens[$j][self::TYPE] == self::T_TEXT) { + if (isset($this->tokens[$j+1]) && $this->tokens[$j+1][self::TYPE] == self::T_PARTIAL) { + $this->tokens[$j+1][self::INDENT] = $this->tokens[$j][self::VALUE]; + } - $this->tokens[$j] = null; - } - } - } elseif (!$noNewLine) { - $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => "\n"); - } + $this->tokens[$j] = null; + } + } + } elseif (!$noNewLine) { + $this->tokens[] = array(self::TYPE => self::T_TEXT, self::VALUE => "\n"); + } - $this->seenTag = false; - $this->lineStart = count($this->tokens); - } + $this->seenTag = false; + $this->lineStart = count($this->tokens); + } - /** - * Change the current Mustache delimiters. Set new `otag` and `ctag` values. - * - * @param string $text Mustache template source - * @param int $index Current tokenizer index - * - * @return int New index value - */ - private function changeDelimiters($text, $index) { - $startIndex = strpos($text, '=', $index) + 1; - $close = '='.$this->ctag; - $closeIndex = strpos($text, $close, $index); + /** + * Change the current Mustache delimiters. Set new `otag` and `ctag` values. + * + * @param string $text Mustache template source + * @param int $index Current tokenizer index + * + * @return int New index value + */ + private function changeDelimiters($text, $index) + { + $startIndex = strpos($text, '=', $index) + 1; + $close = '='.$this->ctag; + $closeIndex = strpos($text, $close, $index); - list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex))); - $this->otag = $otag; - $this->ctag = $ctag; + list($otag, $ctag) = explode(' ', trim(substr($text, $startIndex, $closeIndex - $startIndex))); + $this->otag = $otag; + $this->ctag = $ctag; - return $closeIndex + strlen($close) - 1; - } + return $closeIndex + strlen($close) - 1; + } - /** - * Test whether it's time to change tags. - * - * @param string $tag Current tag name - * @param string $text Mustache template source - * @param int $index Current tokenizer index - * - * @return boolean True if this is a closing section tag - */ - private function tagChange($tag, $text, $index) { - return substr($text, $index, strlen($tag)) === $tag; - } + /** + * Test whether it's time to change tags. + * + * @param string $tag Current tag name + * @param string $text Mustache template source + * @param int $index Current tokenizer index + * + * @return boolean True if this is a closing section tag + */ + private function tagChange($tag, $text, $index) + { + return substr($text, $index, strlen($tag)) === $tag; + } } diff --git a/test/Mustache/Test/AutoloaderTest.php b/test/Mustache/Test/AutoloaderTest.php index 4743e01..2c35ba2 100644 --- a/test/Mustache/Test/AutoloaderTest.php +++ b/test/Mustache/Test/AutoloaderTest.php @@ -12,22 +12,25 @@ /** * @group unit */ -class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase { - public function testRegister() { - $loader = Mustache_Autoloader::register(); - $this->assertTrue(spl_autoload_unregister(array($loader, 'autoload'))); - } +class Mustache_Test_AutoloaderTest extends PHPUnit_Framework_TestCase +{ + public function testRegister() + { + $loader = Mustache_Autoloader::register(); + $this->assertTrue(spl_autoload_unregister(array($loader, 'autoload'))); + } - public function testAutoloader() { - $loader = new Mustache_Autoloader(dirname(__FILE__).'/../../fixtures/autoloader'); + public function testAutoloader() + { + $loader = new Mustache_Autoloader(dirname(__FILE__).'/../../fixtures/autoloader'); - $this->assertNull($loader->autoload('NonMustacheClass')); - $this->assertFalse(class_exists('NonMustacheClass')); + $this->assertNull($loader->autoload('NonMustacheClass')); + $this->assertFalse(class_exists('NonMustacheClass')); - $loader->autoload('Mustache_Foo'); - $this->assertTrue(class_exists('Mustache_Foo')); + $loader->autoload('Mustache_Foo'); + $this->assertTrue(class_exists('Mustache_Foo')); - $loader->autoload('\Mustache_Bar'); - $this->assertTrue(class_exists('Mustache_Bar')); - } + $loader->autoload('\Mustache_Bar'); + $this->assertTrue(class_exists('Mustache_Bar')); + } } diff --git a/test/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php index b508b02..8b6f5be 100644 --- a/test/Mustache/Test/CompilerTest.php +++ b/test/Mustache/Test/CompilerTest.php @@ -12,87 +12,92 @@ /** * @group unit */ -class Mustache_Test_CompilerTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_CompilerTest extends PHPUnit_Framework_TestCase +{ - /** - * @dataProvider getCompileValues - */ - public function testCompile($source, array $tree, $name, $customEscaper, $charset, $expected) { - $compiler = new Mustache_Compiler; + /** + * @dataProvider getCompileValues + */ + public function testCompile($source, array $tree, $name, $customEscaper, $charset, $expected) + { + $compiler = new Mustache_Compiler; - $compiled = $compiler->compile($source, $tree, $name, $customEscaper, $charset); - foreach ($expected as $contains) { - $this->assertContains($contains, $compiled); - } - } + $compiled = $compiler->compile($source, $tree, $name, $customEscaper, $charset); + foreach ($expected as $contains) { + $this->assertContains($contains, $compiled); + } + } - public function getCompileValues() { - return array( - array('', array(), 'Banana', false, 'ISO-8859-1', array( - "\nclass Banana extends Mustache_Template", - 'return htmlspecialchars($buffer, ENT_COMPAT, \'ISO-8859-1\');', - 'return $buffer;', - )), + public function getCompileValues() + { + return array( + array('', array(), 'Banana', false, 'ISO-8859-1', array( + "\nclass Banana extends Mustache_Template", + 'return htmlspecialchars($buffer, ENT_COMPAT, \'ISO-8859-1\');', + 'return $buffer;', + )), - array('', array($this->createTextToken('TEXT')), 'Monkey', false, 'UTF-8', array( - "\nclass Monkey extends Mustache_Template", - 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', - '$buffer .= $indent . \'TEXT\';', - 'return $buffer;', - )), + array('', array($this->createTextToken('TEXT')), 'Monkey', false, 'UTF-8', array( + "\nclass Monkey extends Mustache_Template", + 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', + '$buffer .= $indent . \'TEXT\';', + 'return $buffer;', + )), - array('', array($this->createTextToken('TEXT')), 'Monkey', true, 'ISO-8859-1', array( - "\nclass Monkey extends Mustache_Template", - '$buffer .= $indent . \'TEXT\';', - 'return call_user_func($this->mustache->getEscape(), $buffer);', - 'return $buffer;', - )), + array('', array($this->createTextToken('TEXT')), 'Monkey', true, 'ISO-8859-1', array( + "\nclass Monkey extends Mustache_Template", + '$buffer .= $indent . \'TEXT\';', + 'return call_user_func($this->mustache->getEscape(), $buffer);', + 'return $buffer;', + )), - array( - '', - array( - $this->createTextToken('foo'), - $this->createTextToken("\n"), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name', - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => '.', - ), - $this->createTextToken("'bar'"), - ), - 'Monkey', - false, - 'UTF-8', - array( - "\nclass Monkey extends Mustache_Template", - '$buffer .= $indent . \'foo\'', - '$buffer .= "\n"', - '$value = $context->find(\'name\');', - '$buffer .= htmlspecialchars($value, ENT_COMPAT, \'UTF-8\');', - '$value = $context->last();', - '$buffer .= \'\\\'bar\\\'\';', - 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', - 'return $buffer;', - ) - ), - ); - } + array( + '', + array( + $this->createTextToken('foo'), + $this->createTextToken("\n"), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => '.', + ), + $this->createTextToken("'bar'"), + ), + 'Monkey', + false, + 'UTF-8', + array( + "\nclass Monkey extends Mustache_Template", + '$buffer .= $indent . \'foo\'', + '$buffer .= "\n"', + '$value = $context->find(\'name\');', + '$buffer .= htmlspecialchars($value, ENT_COMPAT, \'UTF-8\');', + '$value = $context->last();', + '$buffer .= \'\\\'bar\\\'\';', + 'return htmlspecialchars($buffer, ENT_COMPAT, \'UTF-8\');', + 'return $buffer;', + ) + ), + ); + } - /** - * @expectedException InvalidArgumentException - */ - public function testCompilerThrowsUnknownNodeTypeException() { - $compiler = new Mustache_Compiler; - $compiler->compile('', array(array(Mustache_Tokenizer::TYPE => 'invalid')), 'SomeClass'); - } + /** + * @expectedException InvalidArgumentException + */ + public function testCompilerThrowsUnknownNodeTypeException() + { + $compiler = new Mustache_Compiler; + $compiler->compile('', array(array(Mustache_Tokenizer::TYPE => 'invalid')), 'SomeClass'); + } - private function createTextToken($value) { - return array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => $value, - ); - } + private function createTextToken($value) + { + return array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => $value, + ); + } } diff --git a/test/Mustache/Test/ContextTest.php b/test/Mustache/Test/ContextTest.php index c11afb8..857dc0a 100644 --- a/test/Mustache/Test/ContextTest.php +++ b/test/Mustache/Test/ContextTest.php @@ -12,100 +12,108 @@ /** * @group unit */ -class Mustache_Test_ContextTest extends PHPUnit_Framework_TestCase { - public function testConstructor() { - $one = new Mustache_Context; - $this->assertSame('', $one->find('foo')); - $this->assertSame('', $one->find('bar')); +class Mustache_Test_ContextTest extends PHPUnit_Framework_TestCase +{ + public function testConstructor() + { + $one = new Mustache_Context; + $this->assertSame('', $one->find('foo')); + $this->assertSame('', $one->find('bar')); - $two = new Mustache_Context(array( - 'foo' => 'FOO', - 'bar' => '' - )); - $this->assertEquals('FOO', $two->find('foo')); - $this->assertEquals('', $two->find('bar')); + $two = new Mustache_Context(array( + 'foo' => 'FOO', + 'bar' => '' + )); + $this->assertEquals('FOO', $two->find('foo')); + $this->assertEquals('', $two->find('bar')); - $obj = new StdClass; - $obj->name = 'NAME'; - $three = new Mustache_Context($obj); - $this->assertSame($obj, $three->last()); - $this->assertEquals('NAME', $three->find('name')); - } + $obj = new StdClass; + $obj->name = 'NAME'; + $three = new Mustache_Context($obj); + $this->assertSame($obj, $three->last()); + $this->assertEquals('NAME', $three->find('name')); + } - public function testPushPopAndLast() { - $context = new Mustache_Context; - $this->assertFalse($context->last()); + public function testPushPopAndLast() + { + $context = new Mustache_Context; + $this->assertFalse($context->last()); - $dummy = new Mustache_Test_TestDummy; - $context->push($dummy); - $this->assertSame($dummy, $context->last()); - $this->assertSame($dummy, $context->pop()); - $this->assertFalse($context->last()); + $dummy = new Mustache_Test_TestDummy; + $context->push($dummy); + $this->assertSame($dummy, $context->last()); + $this->assertSame($dummy, $context->pop()); + $this->assertFalse($context->last()); - $obj = new StdClass; - $context->push($dummy); - $this->assertSame($dummy, $context->last()); - $context->push($obj); - $this->assertSame($obj, $context->last()); - $this->assertSame($obj, $context->pop()); - $this->assertSame($dummy, $context->pop()); - $this->assertFalse($context->last()); - } + $obj = new StdClass; + $context->push($dummy); + $this->assertSame($dummy, $context->last()); + $context->push($obj); + $this->assertSame($obj, $context->last()); + $this->assertSame($obj, $context->pop()); + $this->assertSame($dummy, $context->pop()); + $this->assertFalse($context->last()); + } - public function testFind() { - $context = new Mustache_Context; + public function testFind() + { + $context = new Mustache_Context; - $dummy = new Mustache_Test_TestDummy; + $dummy = new Mustache_Test_TestDummy; - $obj = new StdClass; - $obj->name = 'obj'; + $obj = new StdClass; + $obj->name = 'obj'; - $arr = array( - 'a' => array('b' => array('c' => 'see')), - 'b' => 'bee', - ); + $arr = array( + 'a' => array('b' => array('c' => 'see')), + 'b' => 'bee', + ); - $string = 'some arbitrary string'; + $string = 'some arbitrary string'; - $context->push($dummy); - $this->assertEquals('dummy', $context->find('name')); + $context->push($dummy); + $this->assertEquals('dummy', $context->find('name')); - $context->push($obj); - $this->assertEquals('obj', $context->find('name')); + $context->push($obj); + $this->assertEquals('obj', $context->find('name')); - $context->pop(); - $this->assertEquals('dummy', $context->find('name')); + $context->pop(); + $this->assertEquals('dummy', $context->find('name')); - $dummy->name = 'dummyer'; - $this->assertEquals('dummyer', $context->find('name')); + $dummy->name = 'dummyer'; + $this->assertEquals('dummyer', $context->find('name')); - $context->push($arr); - $this->assertEquals('bee', $context->find('b')); - $this->assertEquals('see', $context->findDot('a.b.c')); + $context->push($arr); + $this->assertEquals('bee', $context->find('b')); + $this->assertEquals('see', $context->findDot('a.b.c')); - $dummy->name = 'dummy'; + $dummy->name = 'dummy'; - $context->push($string); - $this->assertSame($string, $context->last()); - $this->assertEquals('dummy', $context->find('name')); - $this->assertEquals('see', $context->findDot('a.b.c')); - $this->assertEquals('', $context->find('foo')); - $this->assertEquals('', $context->findDot('bar')); - } + $context->push($string); + $this->assertSame($string, $context->last()); + $this->assertEquals('dummy', $context->find('name')); + $this->assertEquals('see', $context->findDot('a.b.c')); + $this->assertEquals('', $context->find('foo')); + $this->assertEquals('', $context->findDot('bar')); + } } -class Mustache_Test_TestDummy { - public $name = 'dummy'; +class Mustache_Test_TestDummy +{ + public $name = 'dummy'; - public function __invoke() { - // nothing - } + public function __invoke() + { + // nothing + } - public static function foo() { - return ''; - } + public static function foo() + { + return ''; + } - public function bar() { - return ''; - } + public function bar() + { + return ''; + } } diff --git a/test/Mustache/Test/EngineTest.php b/test/Mustache/Test/EngineTest.php index 0e299fe..35390c1 100644 --- a/test/Mustache/Test/EngineTest.php +++ b/test/Mustache/Test/EngineTest.php @@ -12,229 +12,245 @@ /** * @group unit */ -class Mustache_Test_EngineTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_EngineTest extends PHPUnit_Framework_TestCase +{ - private static $tempDir; + private static $tempDir; - public static function setUpBeforeClass() { - self::$tempDir = sys_get_temp_dir() . '/mustache_test'; - if (file_exists(self::$tempDir)) { - self::rmdir(self::$tempDir); - } - } + public static function setUpBeforeClass() + { + self::$tempDir = sys_get_temp_dir() . '/mustache_test'; + if (file_exists(self::$tempDir)) { + self::rmdir(self::$tempDir); + } + } - public function testConstructor() { - $loader = new Mustache_Loader_StringLoader; - $partialsLoader = new Mustache_Loader_ArrayLoader; - $mustache = new Mustache_Engine(array( - 'template_class_prefix' => '__whot__', - 'cache' => self::$tempDir, - 'loader' => $loader, - 'partials_loader' => $partialsLoader, - 'partials' => array( - 'foo' => '{{ foo }}', - ), - 'helpers' => array( - 'foo' => array($this, 'getFoo'), - 'bar' => 'BAR', - ), - 'escape' => 'strtoupper', - 'charset' => 'ISO-8859-1', - )); + public function testConstructor() + { + $loader = new Mustache_Loader_StringLoader; + $partialsLoader = new Mustache_Loader_ArrayLoader; + $mustache = new Mustache_Engine(array( + 'template_class_prefix' => '__whot__', + 'cache' => self::$tempDir, + 'loader' => $loader, + 'partials_loader' => $partialsLoader, + 'partials' => array( + 'foo' => '{{ foo }}', + ), + 'helpers' => array( + 'foo' => array($this, 'getFoo'), + 'bar' => 'BAR', + ), + 'escape' => 'strtoupper', + 'charset' => 'ISO-8859-1', + )); - $this->assertSame($loader, $mustache->getLoader()); - $this->assertSame($partialsLoader, $mustache->getPartialsLoader()); - $this->assertEquals('{{ foo }}', $partialsLoader->load('foo')); - $this->assertContains('__whot__', $mustache->getTemplateClassName('{{ foo }}')); - $this->assertEquals('strtoupper', $mustache->getEscape()); - $this->assertEquals('ISO-8859-1', $mustache->getCharset()); - $this->assertTrue($mustache->hasHelper('foo')); - $this->assertTrue($mustache->hasHelper('bar')); - $this->assertFalse($mustache->hasHelper('baz')); - } + $this->assertSame($loader, $mustache->getLoader()); + $this->assertSame($partialsLoader, $mustache->getPartialsLoader()); + $this->assertEquals('{{ foo }}', $partialsLoader->load('foo')); + $this->assertContains('__whot__', $mustache->getTemplateClassName('{{ foo }}')); + $this->assertEquals('strtoupper', $mustache->getEscape()); + $this->assertEquals('ISO-8859-1', $mustache->getCharset()); + $this->assertTrue($mustache->hasHelper('foo')); + $this->assertTrue($mustache->hasHelper('bar')); + $this->assertFalse($mustache->hasHelper('baz')); + } - public static function getFoo() { - return 'foo'; - } + public static function getFoo() + { + return 'foo'; + } - public function testRender() { - $source = '{{ foo }}'; - $data = array('bar' => 'baz'); - $output = 'TEH OUTPUT'; + public function testRender() + { + $source = '{{ foo }}'; + $data = array('bar' => 'baz'); + $output = 'TEH OUTPUT'; - $template = $this->getMockBuilder('Mustache_Template') - ->disableOriginalConstructor() - ->getMock(); + $template = $this->getMockBuilder('Mustache_Template') + ->disableOriginalConstructor() + ->getMock(); - $mustache = new MustacheStub; - $mustache->template = $template; + $mustache = new MustacheStub; + $mustache->template = $template; - $template->expects($this->once()) - ->method('render') - ->with($data) - ->will($this->returnValue($output)); + $template->expects($this->once()) + ->method('render') + ->with($data) + ->will($this->returnValue($output)); - $this->assertEquals($output, $mustache->render($source, $data)); - $this->assertEquals($source, $mustache->source); - } + $this->assertEquals($output, $mustache->render($source, $data)); + $this->assertEquals($source, $mustache->source); + } - public function testSettingServices() { - $loader = new Mustache_Loader_StringLoader; - $tokenizer = new Mustache_Tokenizer; - $parser = new Mustache_Parser; - $compiler = new Mustache_Compiler; - $mustache = new Mustache_Engine; + public function testSettingServices() + { + $loader = new Mustache_Loader_StringLoader; + $tokenizer = new Mustache_Tokenizer; + $parser = new Mustache_Parser; + $compiler = new Mustache_Compiler; + $mustache = new Mustache_Engine; - $this->assertNotSame($loader, $mustache->getLoader()); - $mustache->setLoader($loader); - $this->assertSame($loader, $mustache->getLoader()); + $this->assertNotSame($loader, $mustache->getLoader()); + $mustache->setLoader($loader); + $this->assertSame($loader, $mustache->getLoader()); - $this->assertNotSame($loader, $mustache->getPartialsLoader()); - $mustache->setPartialsLoader($loader); - $this->assertSame($loader, $mustache->getPartialsLoader()); + $this->assertNotSame($loader, $mustache->getPartialsLoader()); + $mustache->setPartialsLoader($loader); + $this->assertSame($loader, $mustache->getPartialsLoader()); - $this->assertNotSame($tokenizer, $mustache->getTokenizer()); - $mustache->setTokenizer($tokenizer); - $this->assertSame($tokenizer, $mustache->getTokenizer()); + $this->assertNotSame($tokenizer, $mustache->getTokenizer()); + $mustache->setTokenizer($tokenizer); + $this->assertSame($tokenizer, $mustache->getTokenizer()); - $this->assertNotSame($parser, $mustache->getParser()); - $mustache->setParser($parser); - $this->assertSame($parser, $mustache->getParser()); + $this->assertNotSame($parser, $mustache->getParser()); + $mustache->setParser($parser); + $this->assertSame($parser, $mustache->getParser()); - $this->assertNotSame($compiler, $mustache->getCompiler()); - $mustache->setCompiler($compiler); - $this->assertSame($compiler, $mustache->getCompiler()); - } + $this->assertNotSame($compiler, $mustache->getCompiler()); + $mustache->setCompiler($compiler); + $this->assertSame($compiler, $mustache->getCompiler()); + } - /** - * @group functional - */ - public function testCache() { - $mustache = new Mustache_Engine(array( - 'template_class_prefix' => '__whot__', - 'cache' => self::$tempDir, - )); + /** + * @group functional + */ + public function testCache() + { + $mustache = new Mustache_Engine(array( + 'template_class_prefix' => '__whot__', + 'cache' => self::$tempDir, + )); - $source = '{{ foo }}'; - $template = $mustache->loadTemplate($source); - $className = $mustache->getTemplateClassName($source); - $fileName = self::$tempDir . '/' . $className . '.php'; - $this->assertInstanceOf($className, $template); - $this->assertFileExists($fileName); - $this->assertContains("\nclass $className extends Mustache_Template", file_get_contents($fileName)); - } + $source = '{{ foo }}'; + $template = $mustache->loadTemplate($source); + $className = $mustache->getTemplateClassName($source); + $fileName = self::$tempDir . '/' . $className . '.php'; + $this->assertInstanceOf($className, $template); + $this->assertFileExists($fileName); + $this->assertContains("\nclass $className extends Mustache_Template", file_get_contents($fileName)); + } - /** - * @expectedException InvalidArgumentException - * @dataProvider getBadEscapers - */ - public function testNonCallableEscapeThrowsException($escape) { - new Mustache_Engine(array('escape' => $escape)); - } + /** + * @expectedException InvalidArgumentException + * @dataProvider getBadEscapers + */ + public function testNonCallableEscapeThrowsException($escape) + { + new Mustache_Engine(array('escape' => $escape)); + } - public function getBadEscapers() { - return array( - array('nothing'), - array('foo', 'bar'), - ); - } + public function getBadEscapers() + { + return array( + array('nothing'), + array('foo', 'bar'), + ); + } - /** - * @expectedException RuntimeException - */ - public function testImmutablePartialsLoadersThrowException() { - $mustache = new Mustache_Engine(array( - 'partials_loader' => new Mustache_Loader_StringLoader, - )); + /** + * @expectedException RuntimeException + */ + public function testImmutablePartialsLoadersThrowException() + { + $mustache = new Mustache_Engine(array( + 'partials_loader' => new Mustache_Loader_StringLoader, + )); - $mustache->setPartials(array('foo' => '{{ foo }}')); - } + $mustache->setPartials(array('foo' => '{{ foo }}')); + } - public function testMissingPartialsTreatedAsEmptyString() { - $mustache = new Mustache_Engine(array( - 'partials_loader' => new Mustache_Loader_ArrayLoader(array( - 'foo' => 'FOO', - 'baz' => 'BAZ', - )) - )); + public function testMissingPartialsTreatedAsEmptyString() + { + $mustache = new Mustache_Engine(array( + 'partials_loader' => new Mustache_Loader_ArrayLoader(array( + 'foo' => 'FOO', + 'baz' => 'BAZ', + )) + )); - $this->assertEquals('FOOBAZ', $mustache->render('{{>foo}}{{>bar}}{{>baz}}', array())); - } + $this->assertEquals('FOOBAZ', $mustache->render('{{>foo}}{{>bar}}{{>baz}}', array())); + } - public function testHelpers() { - $foo = array($this, 'getFoo'); - $bar = 'BAR'; - $mustache = new Mustache_Engine(array('helpers' => array( - 'foo' => $foo, - 'bar' => $bar, - ))); + public function testHelpers() + { + $foo = array($this, 'getFoo'); + $bar = 'BAR'; + $mustache = new Mustache_Engine(array('helpers' => array( + 'foo' => $foo, + 'bar' => $bar, + ))); - $helpers = $mustache->getHelpers(); - $this->assertTrue($mustache->hasHelper('foo')); - $this->assertTrue($mustache->hasHelper('bar')); - $this->assertTrue($helpers->has('foo')); - $this->assertTrue($helpers->has('bar')); - $this->assertSame($foo, $mustache->getHelper('foo')); - $this->assertSame($bar, $mustache->getHelper('bar')); + $helpers = $mustache->getHelpers(); + $this->assertTrue($mustache->hasHelper('foo')); + $this->assertTrue($mustache->hasHelper('bar')); + $this->assertTrue($helpers->has('foo')); + $this->assertTrue($helpers->has('bar')); + $this->assertSame($foo, $mustache->getHelper('foo')); + $this->assertSame($bar, $mustache->getHelper('bar')); - $mustache->removeHelper('bar'); - $this->assertFalse($mustache->hasHelper('bar')); - $mustache->addHelper('bar', $bar); - $this->assertSame($bar, $mustache->getHelper('bar')); + $mustache->removeHelper('bar'); + $this->assertFalse($mustache->hasHelper('bar')); + $mustache->addHelper('bar', $bar); + $this->assertSame($bar, $mustache->getHelper('bar')); - $baz = array($this, 'wrapWithUnderscores'); - $this->assertFalse($mustache->hasHelper('baz')); - $this->assertFalse($helpers->has('baz')); + $baz = array($this, 'wrapWithUnderscores'); + $this->assertFalse($mustache->hasHelper('baz')); + $this->assertFalse($helpers->has('baz')); - $mustache->addHelper('baz', $baz); - $this->assertTrue($mustache->hasHelper('baz')); - $this->assertTrue($helpers->has('baz')); + $mustache->addHelper('baz', $baz); + $this->assertTrue($mustache->hasHelper('baz')); + $this->assertTrue($helpers->has('baz')); - // ... and a functional test - $tpl = $mustache->loadTemplate('{{foo}} - {{bar}} - {{#baz}}qux{{/baz}}'); - $this->assertEquals('foo - BAR - __qux__', $tpl->render()); - $this->assertEquals('foo - BAR - __qux__', $tpl->render(array('qux' => "won't mess things up"))); - } + // ... and a functional test + $tpl = $mustache->loadTemplate('{{foo}} - {{bar}} - {{#baz}}qux{{/baz}}'); + $this->assertEquals('foo - BAR - __qux__', $tpl->render()); + $this->assertEquals('foo - BAR - __qux__', $tpl->render(array('qux' => "won't mess things up"))); + } - public static function wrapWithUnderscores($text) { - return '__'.$text.'__'; - } + public static function wrapWithUnderscores($text) + { + return '__'.$text.'__'; + } - /** - * @expectedException InvalidArgumentException - */ - public function testSetHelpersThrowsExceptions() { - $mustache = new Mustache_Engine; - $mustache->setHelpers('monkeymonkeymonkey'); - } + /** + * @expectedException InvalidArgumentException + */ + public function testSetHelpersThrowsExceptions() + { + $mustache = new Mustache_Engine; + $mustache->setHelpers('monkeymonkeymonkey'); + } - private static function rmdir($path) { - $path = rtrim($path, '/').'/'; - $handle = opendir($path); - while (($file = readdir($handle)) !== false) { - if ($file == '.' || $file == '..') { - continue; - } + private static function rmdir($path) + { + $path = rtrim($path, '/').'/'; + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } - $fullpath = $path.$file; - if (is_dir($fullpath)) { - self::rmdir($fullpath); - } else { - unlink($fullpath); - } - } + $fullpath = $path.$file; + if (is_dir($fullpath)) { + self::rmdir($fullpath); + } else { + unlink($fullpath); + } + } - closedir($handle); - rmdir($path); - } + closedir($handle); + rmdir($path); + } } class MustacheStub extends Mustache_Engine { - public $source; - public $template; - public function loadTemplate($source) { - $this->source = $source; + public $source; + public $template; + public function loadTemplate($source) + { + $this->source = $source; - return $this->template; - } + return $this->template; + } } diff --git a/test/Mustache/Test/Functional/CallTest.php b/test/Mustache/Test/Functional/CallTest.php index 8658490..53b93b7 100644 --- a/test/Mustache/Test/Functional/CallTest.php +++ b/test/Mustache/Test/Functional/CallTest.php @@ -13,24 +13,28 @@ * @group magic_methods * @group functional */ -class Mustache_Test_Functional_CallTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_CallTest extends PHPUnit_Framework_TestCase +{ - public function testCallEatsContext() { - $m = new Mustache_Engine; - $tpl = $m->loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); + public function testCallEatsContext() + { + $m = new Mustache_Engine; + $tpl = $m->loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); - $foo = new Mustache_Test_Functional_ClassWithCall(); - $foo->name = 'Bob'; + $foo = new Mustache_Test_Functional_ClassWithCall(); + $foo->name = 'Bob'; - $data = array('label' => 'name', 'foo' => $foo); + $data = array('label' => 'name', 'foo' => $foo); - $this->assertEquals('name: Bob', $tpl->render($data)); - } + $this->assertEquals('name: Bob', $tpl->render($data)); + } } -class Mustache_Test_Functional_ClassWithCall { - public $name; - public function __call($method, $args) { - return 'unknown value'; - } +class Mustache_Test_Functional_ClassWithCall +{ + public $name; + public function __call($method, $args) + { + return 'unknown value'; + } } diff --git a/test/Mustache/Test/Functional/ExamplesTest.php b/test/Mustache/Test/Functional/ExamplesTest.php index a16e459..6c335e8 100644 --- a/test/Mustache/Test/Functional/ExamplesTest.php +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -13,125 +13,130 @@ * @group examples * @group functional */ -class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_ExamplesTest extends PHPUnit_Framework_TestCase +{ - /** - * Test everything in the `examples` directory. - * - * @dataProvider getExamples - * - * @param string $context - * @param string $source - * @param array $partials - * @param string $expected - */ - public function testExamples($context, $source, $partials, $expected) { - $mustache = new Mustache_Engine(array( - 'partials' => $partials - )); - $this->assertEquals($expected, $mustache->loadTemplate($source)->render($context)); - } + /** + * Test everything in the `examples` directory. + * + * @dataProvider getExamples + * + * @param string $context + * @param string $source + * @param array $partials + * @param string $expected + */ + public function testExamples($context, $source, $partials, $expected) + { + $mustache = new Mustache_Engine(array( + 'partials' => $partials + )); + $this->assertEquals($expected, $mustache->loadTemplate($source)->render($context)); + } - /** - * Data provider for testExamples method. - * - * Loads examples from the test fixtures directory. - * - * This examples directory should contain any number of subdirectories, each of which contains - * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file - * (.txt). Optionally, the directory may contain a folder full of partials. - * - * @return array - */ - public function getExamples() { - $path = realpath(dirname(__FILE__).'/../../../fixtures/examples'); - $examples = array(); + /** + * Data provider for testExamples method. + * + * Loads examples from the test fixtures directory. + * + * This examples directory should contain any number of subdirectories, each of which contains + * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file + * (.txt). Optionally, the directory may contain a folder full of partials. + * + * @return array + */ + public function getExamples() + { + $path = realpath(dirname(__FILE__).'/../../../fixtures/examples'); + $examples = array(); - $handle = opendir($path); - while (($file = readdir($handle)) !== false) { - if ($file == '.' || $file == '..') { - continue; - } + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } - $fullpath = $path.'/'.$file; - if (is_dir($fullpath)) { - $examples[$file] = $this->loadExample($fullpath); - } - } - closedir($handle); + $fullpath = $path.'/'.$file; + if (is_dir($fullpath)) { + $examples[$file] = $this->loadExample($fullpath); + } + } + closedir($handle); - return $examples; - } + return $examples; + } - /** - * Helper method to load an example given the full path. - * - * @param string $path - * - * @return array arguments for testExamples - */ - private function loadExample($path) { - $context = null; - $source = null; - $partials = array(); - $expected = null; + /** + * Helper method to load an example given the full path. + * + * @param string $path + * + * @return array arguments for testExamples + */ + private function loadExample($path) + { + $context = null; + $source = null; + $partials = array(); + $expected = null; - $handle = opendir($path); - while (($file = readdir($handle)) !== false) { - $fullpath = $path.'/'.$file; - $info = pathinfo($fullpath); + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + $fullpath = $path.'/'.$file; + $info = pathinfo($fullpath); - if (is_dir($fullpath) && $info['basename'] == 'partials') { - // load partials - $partials = $this->loadPartials($fullpath); - } elseif (is_file($fullpath)) { - // load other files - switch ($info['extension']) { - case 'php': - require_once($fullpath); - $context = new $info['filename']; - break; + if (is_dir($fullpath) && $info['basename'] == 'partials') { + // load partials + $partials = $this->loadPartials($fullpath); + } elseif (is_file($fullpath)) { + // load other files + switch ($info['extension']) { + case 'php': + require_once($fullpath); + $context = new $info['filename']; + break; - case 'mustache': - $source = file_get_contents($fullpath); - break; + case 'mustache': + $source = file_get_contents($fullpath); + break; - case 'txt': - $expected = file_get_contents($fullpath); - break; - } - } - } - closedir($handle); + case 'txt': + $expected = file_get_contents($fullpath); + break; + } + } + } + closedir($handle); - return array($context, $source, $partials, $expected); - } + return array($context, $source, $partials, $expected); + } - /** - * Helper method to load partials given an example directory. - * - * @param string $path - * - * @return array $partials - */ - private function loadPartials($path) { - $partials = array(); + /** + * Helper method to load partials given an example directory. + * + * @param string $path + * + * @return array $partials + */ + private function loadPartials($path) + { + $partials = array(); - $handle = opendir($path); - while (($file = readdir($handle)) !== false) { - if ($file == '.' || $file == '..') { - continue; - } + $handle = opendir($path); + while (($file = readdir($handle)) !== false) { + if ($file == '.' || $file == '..') { + continue; + } - $fullpath = $path.'/'.$file; - $info = pathinfo($fullpath); + $fullpath = $path.'/'.$file; + $info = pathinfo($fullpath); - if ($info['extension'] === 'mustache') { - $partials[$info['filename']] = file_get_contents($fullpath); - } - } - closedir($handle); + if ($info['extension'] === 'mustache') { + $partials[$info['filename']] = file_get_contents($fullpath); + } + } + closedir($handle); - return $partials; - } + return $partials; + } } diff --git a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php index 22bab17..4c3cba6 100644 --- a/test/Mustache/Test/Functional/HigherOrderSectionsTest.php +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -13,82 +13,94 @@ * @group lambdas * @group functional */ -class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_HigherOrderSectionsTest extends PHPUnit_Framework_TestCase +{ - private $mustache; + private $mustache; - public function setUp() { - $this->mustache = new Mustache_Engine; - } + public function setUp() + { + $this->mustache = new Mustache_Engine; + } - public function testRuntimeSectionCallback() { - $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); + public function testRuntimeSectionCallback() + { + $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); - $foo = new Mustache_Test_Functional_Foo; - $foo->doublewrap = array($foo, 'wrapWithBoth'); + $foo = new Mustache_Test_Functional_Foo; + $foo->doublewrap = array($foo, 'wrapWithBoth'); - $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); - } + $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); + } - public function testStaticSectionCallback() { - $tpl = $this->mustache->loadTemplate('{{#trimmer}} {{name}} {{/trimmer}}'); + public function testStaticSectionCallback() + { + $tpl = $this->mustache->loadTemplate('{{#trimmer}} {{name}} {{/trimmer}}'); - $foo = new Mustache_Test_Functional_Foo; - $foo->trimmer = array(get_class($foo), 'staticTrim'); + $foo = new Mustache_Test_Functional_Foo; + $foo->trimmer = array(get_class($foo), 'staticTrim'); - $this->assertEquals($foo->name, $tpl->render($foo)); - } + $this->assertEquals($foo->name, $tpl->render($foo)); + } - public function testViewArraySectionCallback() { - $tpl = $this->mustache->loadTemplate('{{#trim}} {{name}} {{/trim}}'); + public function testViewArraySectionCallback() + { + $tpl = $this->mustache->loadTemplate('{{#trim}} {{name}} {{/trim}}'); - $foo = new Mustache_Test_Functional_Foo; + $foo = new Mustache_Test_Functional_Foo; - $data = array( - 'name' => 'Bob', - 'trim' => array(get_class($foo), 'staticTrim'), - ); + $data = array( + 'name' => 'Bob', + 'trim' => array(get_class($foo), 'staticTrim'), + ); - $this->assertEquals($data['name'], $tpl->render($data)); - } + $this->assertEquals($data['name'], $tpl->render($data)); + } - public function testMonsters() { - $tpl = $this->mustache->loadTemplate('{{#title}}{{title}} {{/title}}{{name}}'); + public function testMonsters() + { + $tpl = $this->mustache->loadTemplate('{{#title}}{{title}} {{/title}}{{name}}'); - $frank = new Mustache_Test_Functional_Monster(); - $frank->title = 'Dr.'; - $frank->name = 'Frankenstein'; - $this->assertEquals('Dr. Frankenstein', $tpl->render($frank)); + $frank = new Mustache_Test_Functional_Monster(); + $frank->title = 'Dr.'; + $frank->name = 'Frankenstein'; + $this->assertEquals('Dr. Frankenstein', $tpl->render($frank)); - $dracula = new Mustache_Test_Functional_Monster(); - $dracula->title = 'Count'; - $dracula->name = 'Dracula'; - $this->assertEquals('Count Dracula', $tpl->render($dracula)); - } + $dracula = new Mustache_Test_Functional_Monster(); + $dracula->title = 'Count'; + $dracula->name = 'Dracula'; + $this->assertEquals('Count Dracula', $tpl->render($dracula)); + } } -class Mustache_Test_Functional_Foo { - public $name = 'Justin'; - public $lorem = 'Lorem ipsum dolor sit amet,'; +class Mustache_Test_Functional_Foo +{ + public $name = 'Justin'; + public $lorem = 'Lorem ipsum dolor sit amet,'; - public function wrapWithEm($text) { - return sprintf('%s', $text); - } + public function wrapWithEm($text) + { + return sprintf('%s', $text); + } - public function wrapWithStrong($text) { - return sprintf('%s', $text); - } + public function wrapWithStrong($text) + { + return sprintf('%s', $text); + } - public function wrapWithBoth($text) { - return self::wrapWithStrong(self::wrapWithEm($text)); - } + public function wrapWithBoth($text) + { + return self::wrapWithStrong(self::wrapWithEm($text)); + } - public static function staticTrim($text) { - return trim($text); - } + public static function staticTrim($text) + { + return trim($text); + } } -class Mustache_Test_Functional_Monster { - public $title; - public $name; +class Mustache_Test_Functional_Monster +{ + public $title; + public $name; } diff --git a/test/Mustache/Test/Functional/MustacheInjectionTest.php b/test/Mustache/Test/Functional/MustacheInjectionTest.php index 679cd47..c6d6337 100644 --- a/test/Mustache/Test/Functional/MustacheInjectionTest.php +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -13,128 +13,140 @@ * @group mustache_injection * @group functional */ -class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_MustacheInjectionTest extends PHPUnit_Framework_TestCase +{ - private $mustache; + private $mustache; - public function setUp() { - $this->mustache = new Mustache_Engine; - } + public function setUp() + { + $this->mustache = new Mustache_Engine; + } - // interpolation + // interpolation - public function testInterpolationInjection() { - $tpl = $this->mustache->loadTemplate('{{ a }}'); + public function testInterpolationInjection() + { + $tpl = $this->mustache->loadTemplate('{{ a }}'); - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); - $this->assertEquals('{{ b }}', $tpl->render($data)); - } + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - public function testUnescapedInterpolationInjection() { - $tpl = $this->mustache->loadTemplate('{{{ a }}}'); + public function testUnescapedInterpolationInjection() + { + $tpl = $this->mustache->loadTemplate('{{{ a }}}'); - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); - $this->assertEquals('{{ b }}', $tpl->render($data)); - } + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - // sections + // sections - public function testSectionInjection() { - $tpl = $this->mustache->loadTemplate('{{# a }}{{ b }}{{/ a }}'); + public function testSectionInjection() + { + $tpl = $this->mustache->loadTemplate('{{# a }}{{ b }}{{/ a }}'); - $data = array( - 'a' => true, - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); + $data = array( + 'a' => true, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); - $this->assertEquals('{{ c }}', $tpl->render($data)); - } + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - public function testUnescapedSectionInjection() { - $tpl = $this->mustache->loadTemplate('{{# a }}{{{ b }}}{{/ a }}'); + public function testUnescapedSectionInjection() + { + $tpl = $this->mustache->loadTemplate('{{# a }}{{{ b }}}{{/ a }}'); - $data = array( - 'a' => true, - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); + $data = array( + 'a' => true, + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); - $this->assertEquals('{{ c }}', $tpl->render($data)); - } + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - // partials + // partials - public function testPartialInjection() { - $tpl = $this->mustache->loadTemplate('{{> partial }}'); - $this->mustache->setPartials(array( - 'partial' => '{{ a }}', - )); + public function testPartialInjection() + { + $tpl = $this->mustache->loadTemplate('{{> partial }}'); + $this->mustache->setPartials(array( + 'partial' => '{{ a }}', + )); - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); - $this->assertEquals('{{ b }}', $tpl->render($data)); - } + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - public function testPartialUnescapedInjection() { - $tpl = $this->mustache->loadTemplate('{{> partial }}'); - $this->mustache->setPartials(array( - 'partial' => '{{{ a }}}', - )); + public function testPartialUnescapedInjection() + { + $tpl = $this->mustache->loadTemplate('{{> partial }}'); + $this->mustache->setPartials(array( + 'partial' => '{{{ a }}}', + )); - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); + $data = array( + 'a' => '{{ b }}', + 'b' => 'FAIL' + ); - $this->assertEquals('{{ b }}', $tpl->render($data)); - } + $this->assertEquals('{{ b }}', $tpl->render($data)); + } - // lambdas + // lambdas - public function testLambdaInterpolationInjection() { - $tpl = $this->mustache->loadTemplate('{{ a }}'); + public function testLambdaInterpolationInjection() + { + $tpl = $this->mustache->loadTemplate('{{ a }}'); - $data = array( - 'a' => array($this, 'lambdaInterpolationCallback'), - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); + $data = array( + 'a' => array($this, 'lambdaInterpolationCallback'), + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); - $this->assertEquals('{{ c }}', $tpl->render($data)); - } + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - public static function lambdaInterpolationCallback() { - return '{{ b }}'; - } + public static function lambdaInterpolationCallback() + { + return '{{ b }}'; + } - public function testLambdaSectionInjection() { - $tpl = $this->mustache->loadTemplate('{{# a }}b{{/ a }}'); + public function testLambdaSectionInjection() + { + $tpl = $this->mustache->loadTemplate('{{# a }}b{{/ a }}'); - $data = array( - 'a' => array($this, 'lambdaSectionCallback'), - 'b' => '{{ c }}', - 'c' => 'FAIL' - ); + $data = array( + 'a' => array($this, 'lambdaSectionCallback'), + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); - $this->assertEquals('{{ c }}', $tpl->render($data)); - } + $this->assertEquals('{{ c }}', $tpl->render($data)); + } - public static function lambdaSectionCallback($text) { - return '{{ ' . $text . ' }}'; - } + public static function lambdaSectionCallback($text) + { + return '{{ ' . $text . ' }}'; + } } diff --git a/test/Mustache/Test/Functional/MustacheSpecTest.php b/test/Mustache/Test/Functional/MustacheSpecTest.php index 67bbb73..470f7f3 100644 --- a/test/Mustache/Test/Functional/MustacheSpecTest.php +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -15,144 +15,161 @@ * @group mustache-spec * @group functional */ -class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_Functional_MustacheSpecTest extends PHPUnit_Framework_TestCase +{ - private static $mustache; + private static $mustache; - public static function setUpBeforeClass() { - self::$mustache = new Mustache_Engine; - } + public static function setUpBeforeClass() + { + self::$mustache = new Mustache_Engine; + } - /** - * For some reason data providers can't mark tests skipped, so this test exists - * simply to provide a 'skipped' test if the `spec` submodule isn't initialized. - */ - public function testSpecInitialized() { - if (!file_exists(dirname(__FILE__).'/../../../../vendor/spec/specs/')) { - $this->markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); - } - } + /** + * For some reason data providers can't mark tests skipped, so this test exists + * simply to provide a 'skipped' test if the `spec` submodule isn't initialized. + */ + public function testSpecInitialized() + { + if (!file_exists(dirname(__FILE__).'/../../../../vendor/spec/specs/')) { + $this->markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); + } + } - /** - * @group comments - * @dataProvider loadCommentSpec - */ - public function testCommentSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group comments + * @dataProvider loadCommentSpec + */ + public function testCommentSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadCommentSpec() { - return $this->loadSpec('comments'); - } + public function loadCommentSpec() + { + return $this->loadSpec('comments'); + } - /** - * @group delimiters - * @dataProvider loadDelimitersSpec - */ - public function testDelimitersSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group delimiters + * @dataProvider loadDelimitersSpec + */ + public function testDelimitersSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadDelimitersSpec() { - return $this->loadSpec('delimiters'); - } + public function loadDelimitersSpec() + { + return $this->loadSpec('delimiters'); + } - /** - * @group interpolation - * @dataProvider loadInterpolationSpec - */ - public function testInterpolationSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group interpolation + * @dataProvider loadInterpolationSpec + */ + public function testInterpolationSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadInterpolationSpec() { - return $this->loadSpec('interpolation'); - } + public function loadInterpolationSpec() + { + return $this->loadSpec('interpolation'); + } - /** - * @group inverted - * @group inverted-sections - * @dataProvider loadInvertedSpec - */ - public function testInvertedSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group inverted + * @group inverted-sections + * @dataProvider loadInvertedSpec + */ + public function testInvertedSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadInvertedSpec() { - return $this->loadSpec('inverted'); - } + public function loadInvertedSpec() + { + return $this->loadSpec('inverted'); + } - /** - * @group partials - * @dataProvider loadPartialsSpec - */ - public function testPartialsSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group partials + * @dataProvider loadPartialsSpec + */ + public function testPartialsSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadPartialsSpec() { - return $this->loadSpec('partials'); - } + public function loadPartialsSpec() + { + return $this->loadSpec('partials'); + } - /** - * @group sections - * @dataProvider loadSectionsSpec - */ - public function testSectionsSpec($desc, $source, $partials, $data, $expected) { - $template = self::loadTemplate($source, $partials); - $this->assertEquals($expected, $template->render($data), $desc); - } + /** + * @group sections + * @dataProvider loadSectionsSpec + */ + public function testSectionsSpec($desc, $source, $partials, $data, $expected) + { + $template = self::loadTemplate($source, $partials); + $this->assertEquals($expected, $template->render($data), $desc); + } - public function loadSectionsSpec() { - return $this->loadSpec('sections'); - } + public function loadSectionsSpec() + { + return $this->loadSpec('sections'); + } - /** - * Data provider for the mustache spec test. - * - * Loads YAML files from the spec and converts them to PHPisms. - * - * @access public - * @return array - */ - private function loadSpec($name) { - $filename = dirname(__FILE__) . '/../../../../vendor/spec/specs/' . $name . '.yml'; - if (!file_exists($filename)) { - return array(); - } + /** + * Data provider for the mustache spec test. + * + * Loads YAML files from the spec and converts them to PHPisms. + * + * @access public + * @return array + */ + private function loadSpec($name) + { + $filename = dirname(__FILE__) . '/../../../../vendor/spec/specs/' . $name . '.yml'; + if (!file_exists($filename)) { + return array(); + } - $data = array(); - $yaml = new sfYamlParser; - $file = file_get_contents($filename); + $data = array(); + $yaml = new sfYamlParser; + $file = file_get_contents($filename); - // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. - if ($name === '~lambdas') { - $file = str_replace(" !code\n", "\n", $file); - } + // @hack: pre-process the 'lambdas' spec so the Symfony YAML parser doesn't complain. + if ($name === '~lambdas') { + $file = str_replace(" !code\n", "\n", $file); + } - $spec = $yaml->parse($file); + $spec = $yaml->parse($file); - foreach ($spec['tests'] as $test) { - $data[] = array( - $test['name'] . ': ' . $test['desc'], - $test['template'], - isset($test['partials']) ? $test['partials'] : array(), - $test['data'], - $test['expected'], - ); - } + foreach ($spec['tests'] as $test) { + $data[] = array( + $test['name'] . ': ' . $test['desc'], + $test['template'], + isset($test['partials']) ? $test['partials'] : array(), + $test['data'], + $test['expected'], + ); + } - return $data; - } + return $data; + } - private static function loadTemplate($source, $partials) { - self::$mustache->setPartials($partials); + private static function loadTemplate($source, $partials) + { + self::$mustache->setPartials($partials); - return self::$mustache->loadTemplate($source); - } + return self::$mustache->loadTemplate($source); + } } diff --git a/test/Mustache/Test/Functional/ObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php index a8995a1..893b668 100644 --- a/test/Mustache/Test/Functional/ObjectSectionTest.php +++ b/test/Mustache/Test/Functional/ObjectSectionTest.php @@ -13,82 +13,98 @@ * @group sections * @group functional */ -class Mustache_Test_Functional_ObjectSectionTest extends PHPUnit_Framework_TestCase { - private $mustache; +class Mustache_Test_Functional_ObjectSectionTest extends PHPUnit_Framework_TestCase +{ + private $mustache; - public function setUp() { - $this->mustache = new Mustache_Engine; - } + public function setUp() + { + $this->mustache = new Mustache_Engine; + } - public function testBasicObject() { - $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Alpha)); - } + public function testBasicObject() + { + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Alpha)); + } - /** - * @group magic_methods - */ - public function testObjectWithGet() { - $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Beta)); - } + /** + * @group magic_methods + */ + public function testObjectWithGet() + { + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Beta)); + } - /** - * @group magic_methods - */ - public function testSectionObjectWithGet() { - $tpl = $this->mustache->loadTemplate('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}'); - $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Gamma)); - } + /** + * @group magic_methods + */ + public function testSectionObjectWithGet() + { + $tpl = $this->mustache->loadTemplate('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}'); + $this->assertEquals('Foo', $tpl->render(new Mustache_Test_Functional_Gamma)); + } - public function testSectionObjectWithFunction() { - $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); - $alpha = new Mustache_Test_Functional_Alpha; - $alpha->foo = new Mustache_Test_Functional_Delta; - $this->assertEquals('Foo', $tpl->render($alpha)); - } + public function testSectionObjectWithFunction() + { + $tpl = $this->mustache->loadTemplate('{{#foo}}{{name}}{{/foo}}'); + $alpha = new Mustache_Test_Functional_Alpha; + $alpha->foo = new Mustache_Test_Functional_Delta; + $this->assertEquals('Foo', $tpl->render($alpha)); + } } -class Mustache_Test_Functional_Alpha { - public $foo; +class Mustache_Test_Functional_Alpha +{ + public $foo; - public function __construct() { - $this->foo = new StdClass(); - $this->foo->name = 'Foo'; - $this->foo->number = 1; - } + public function __construct() + { + $this->foo = new StdClass(); + $this->foo->name = 'Foo'; + $this->foo->number = 1; + } } -class Mustache_Test_Functional_Beta { - protected $_data = array(); +class Mustache_Test_Functional_Beta +{ + protected $_data = array(); - public function __construct() { - $this->_data['foo'] = new StdClass(); - $this->_data['foo']->name = 'Foo'; - $this->_data['foo']->number = 1; - } + public function __construct() + { + $this->_data['foo'] = new StdClass(); + $this->_data['foo']->name = 'Foo'; + $this->_data['foo']->number = 1; + } - public function __isset($name) { - return array_key_exists($name, $this->_data); - } + public function __isset($name) + { + return array_key_exists($name, $this->_data); + } - public function __get($name) { - return $this->_data[$name]; - } + public function __get($name) + { + return $this->_data[$name]; + } } -class Mustache_Test_Functional_Gamma { - public $bar; +class Mustache_Test_Functional_Gamma +{ + public $bar; - public function __construct() { - $this->bar = new Mustache_Test_Functional_Beta; - } + public function __construct() + { + $this->bar = new Mustache_Test_Functional_Beta; + } } -class Mustache_Test_Functional_Delta { - protected $_name = 'Foo'; +class Mustache_Test_Functional_Delta +{ + protected $_name = 'Foo'; - public function name() { - return $this->_name; - } + public function name() + { + return $this->_name; + } } diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php index 5c66bd5..8bd54f9 100644 --- a/test/Mustache/Test/HelperCollectionTest.php +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -9,27 +9,31 @@ * file that was distributed with this source code. */ -class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { - public function testConstructor() { - $foo = array($this, 'getFoo'); - $bar = 'BAR'; +class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase +{ + public function testConstructor() + { + $foo = array($this, 'getFoo'); + $bar = 'BAR'; - $helpers = new Mustache_HelperCollection(array( - 'foo' => $foo, - 'bar' => $bar, - )); + $helpers = new Mustache_HelperCollection(array( + 'foo' => $foo, + 'bar' => $bar, + )); - $this->assertSame($foo, $helpers->get('foo')); - $this->assertSame($bar, $helpers->get('bar')); - } + $this->assertSame($foo, $helpers->get('foo')); + $this->assertSame($bar, $helpers->get('bar')); + } - public static function getFoo() { + public static function getFoo() + { echo 'foo'; } - public function testAccessorsAndMutators() { - $foo = array($this, 'getFoo'); - $bar = 'BAR'; + public function testAccessorsAndMutators() + { + $foo = array($this, 'getFoo'); + $bar = 'BAR'; $helpers = new Mustache_HelperCollection; $this->assertTrue($helpers->isEmpty()); @@ -52,7 +56,8 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { $this->assertTrue($helpers->has('bar')); } - public function testMagicMethods() { + public function testMagicMethods() + { $foo = array($this, 'getFoo'); $bar = 'BAR'; @@ -88,7 +93,8 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { /** * @dataProvider getInvalidHelperArguments */ - public function testHelperCollectionIsntAfraidToThrowExceptions($helpers = array(), $actions = array(), $exception = null) { + public function testHelperCollectionIsntAfraidToThrowExceptions($helpers = array(), $actions = array(), $exception = null) + { if ($exception) { $this->setExpectedException($exception); } @@ -100,7 +106,8 @@ class Mustache_Test_HelperCollectionTest extends PHPUnit_Framework_TestCase { } } - public function getInvalidHelperArguments() { + public function getInvalidHelperArguments() + { return array( array( 'not helpers', diff --git a/test/Mustache/Test/Loader/ArrayLoaderTest.php b/test/Mustache/Test/Loader/ArrayLoaderTest.php index 0f659da..63d1a96 100644 --- a/test/Mustache/Test/Loader/ArrayLoaderTest.php +++ b/test/Mustache/Test/Loader/ArrayLoaderTest.php @@ -12,37 +12,41 @@ /** * @group unit */ -class Mustache_Test_Loader_ArrayLoaderTest extends PHPUnit_Framework_TestCase { - public function testConstructor() { - $loader = new Mustache_Loader_ArrayLoader(array( - 'foo' => 'bar' - )); +class Mustache_Test_Loader_ArrayLoaderTest extends PHPUnit_Framework_TestCase +{ + public function testConstructor() + { + $loader = new Mustache_Loader_ArrayLoader(array( + 'foo' => 'bar' + )); - $this->assertEquals('bar', $loader->load('foo')); - } + $this->assertEquals('bar', $loader->load('foo')); + } - public function testSetAndLoadTemplates() { - $loader = new Mustache_Loader_ArrayLoader(array( - 'foo' => 'bar' - )); - $this->assertEquals('bar', $loader->load('foo')); + public function testSetAndLoadTemplates() + { + $loader = new Mustache_Loader_ArrayLoader(array( + 'foo' => 'bar' + )); + $this->assertEquals('bar', $loader->load('foo')); - $loader->setTemplate('baz', 'qux'); - $this->assertEquals('qux', $loader->load('baz')); + $loader->setTemplate('baz', 'qux'); + $this->assertEquals('qux', $loader->load('baz')); - $loader->setTemplates(array( - 'foo' => 'FOO', - 'baz' => 'BAZ', - )); - $this->assertEquals('FOO', $loader->load('foo')); - $this->assertEquals('BAZ', $loader->load('baz')); - } + $loader->setTemplates(array( + 'foo' => 'FOO', + 'baz' => 'BAZ', + )); + $this->assertEquals('FOO', $loader->load('foo')); + $this->assertEquals('BAZ', $loader->load('baz')); + } - /** - * @expectedException InvalidArgumentException - */ - public function testMissingTemplatesThrowExceptions() { - $loader = new Mustache_Loader_ArrayLoader; - $loader->load('not_a_real_template'); - } + /** + * @expectedException InvalidArgumentException + */ + public function testMissingTemplatesThrowExceptions() + { + $loader = new Mustache_Loader_ArrayLoader; + $loader->load('not_a_real_template'); + } } diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php index 670274f..f0f0997 100644 --- a/test/Mustache/Test/Loader/FilesystemLoaderTest.php +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -12,35 +12,40 @@ /** * @group unit */ -class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCase { - public function testConstructor() { - $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); - $loader = new Mustache_Loader_FilesystemLoader($baseDir, array('extension' => '.ms')); - $this->assertEquals('alpha contents', $loader->load('alpha')); - $this->assertEquals('beta contents', $loader->load('beta.ms')); - } +class Mustache_Test_Loader_FilesystemLoaderTest extends PHPUnit_Framework_TestCase +{ + public function testConstructor() + { + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); + $loader = new Mustache_Loader_FilesystemLoader($baseDir, array('extension' => '.ms')); + $this->assertEquals('alpha contents', $loader->load('alpha')); + $this->assertEquals('beta contents', $loader->load('beta.ms')); + } - public function testLoadTemplates() { - $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); - $loader = new Mustache_Loader_FilesystemLoader($baseDir); - $this->assertEquals('one contents', $loader->load('one')); - $this->assertEquals('two contents', $loader->load('two.mustache')); - } + public function testLoadTemplates() + { + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); + $loader = new Mustache_Loader_FilesystemLoader($baseDir); + $this->assertEquals('one contents', $loader->load('one')); + $this->assertEquals('two contents', $loader->load('two.mustache')); + } - /** - * @expectedException RuntimeException - */ - public function testMissingBaseDirThrowsException() { - $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/not_a_directory'); - } + /** + * @expectedException RuntimeException + */ + public function testMissingBaseDirThrowsException() + { + $loader = new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/not_a_directory'); + } - /** - * @expectedException InvalidArgumentException - */ - public function testMissingTemplateThrowsException() { - $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); - $loader = new Mustache_Loader_FilesystemLoader($baseDir); + /** + * @expectedException InvalidArgumentException + */ + public function testMissingTemplateThrowsException() + { + $baseDir = realpath(dirname(__FILE__).'/../../../fixtures/templates'); + $loader = new Mustache_Loader_FilesystemLoader($baseDir); - $loader->load('fake'); - } + $loader->load('fake'); + } } diff --git a/test/Mustache/Test/Loader/StringLoaderTest.php b/test/Mustache/Test/Loader/StringLoaderTest.php index 7a0d302..abda71a 100644 --- a/test/Mustache/Test/Loader/StringLoaderTest.php +++ b/test/Mustache/Test/Loader/StringLoaderTest.php @@ -12,12 +12,14 @@ /** * @group unit */ -class Mustache_Test_Loader_StringLoaderTest extends PHPUnit_Framework_TestCase { - public function testLoadTemplates() { - $loader = new Mustache_Loader_StringLoader; +class Mustache_Test_Loader_StringLoaderTest extends PHPUnit_Framework_TestCase +{ + public function testLoadTemplates() + { + $loader = new Mustache_Loader_StringLoader; - $this->assertEquals('foo', $loader->load('foo')); - $this->assertEquals('{{ bar }}', $loader->load('{{ bar }}')); - $this->assertEquals("\n{{! comment }}\n", $loader->load("\n{{! comment }}\n")); - } + $this->assertEquals('foo', $loader->load('foo')); + $this->assertEquals('{{ bar }}', $loader->load('{{ bar }}')); + $this->assertEquals("\n{{! comment }}\n", $loader->load("\n{{! comment }}\n")); + } } diff --git a/test/Mustache/Test/ParserTest.php b/test/Mustache/Test/ParserTest.php index 192b8aa..5f898d8 100644 --- a/test/Mustache/Test/ParserTest.php +++ b/test/Mustache/Test/ParserTest.php @@ -12,168 +12,171 @@ /** * @group unit */ -class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_ParserTest extends PHPUnit_Framework_TestCase +{ - /** - * @dataProvider getTokenSets - */ - public function testParse($tokens, $expected) - { - $parser = new Mustache_Parser; - $this->assertEquals($expected, $parser->parse($tokens)); - } + /** + * @dataProvider getTokenSets + */ + public function testParse($tokens, $expected) + { + $parser = new Mustache_Parser; + $this->assertEquals($expected, $parser->parse($tokens)); + } - public function getTokenSets() - { - return array( - array( - array(), - array() - ), + public function getTokenSets() + { + return array( + array( + array(), + array() + ), - array( - array(array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'text' - )), - array(array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'text' - )), - ), + array( + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text' + )), + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text' + )), + ), - array( - array(array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name' - )), - array(array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name' - )), - ), + array( + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' + )), + array(array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' + )), + ), - array( - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'foo' - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, - Mustache_Tokenizer::INDEX => 123, - Mustache_Tokenizer::NAME => 'parent' - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name' - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, - Mustache_Tokenizer::INDEX => 456, - Mustache_Tokenizer::NAME => 'parent' - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'bar' - ), - ), - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'foo' - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - Mustache_Tokenizer::END => 456, - Mustache_Tokenizer::NODES => array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name' - ), - ), - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'bar' - ), - ), - ), + array( + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'foo' + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::INDEX => 123, + Mustache_Tokenizer::NAME => 'parent' + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::INDEX => 456, + Mustache_Tokenizer::NAME => 'parent' + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'bar' + ), + ), + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'foo' + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + Mustache_Tokenizer::END => 456, + Mustache_Tokenizer::NODES => array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name' + ), + ), + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'bar' + ), + ), + ), - ); - } + ); + } - /** - * @dataProvider getBadParseTrees - * @expectedException LogicException - */ - public function testParserThrowsExceptions($tokens) { - $parser = new Mustache_Parser; - $parser->parse($tokens); - } + /** + * @dataProvider getBadParseTrees + * @expectedException LogicException + */ + public function testParserThrowsExceptions($tokens) + { + $parser = new Mustache_Parser; + $parser->parse($tokens); + } - public function getBadParseTrees() { - return array( - // no close - array( - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - ), - ), - ), + public function getBadParseTrees() + { + return array( + // no close + array( + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + ), + ), + ), - // no close inverted - array( - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - ), - ), - ), + // no close inverted + array( + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_INVERTED, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + ), + ), + ), - // no opening inverted - array( - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - ), - ), - ), + // no opening inverted + array( + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + ), + ), + ), - // weird nesting - array( - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, - Mustache_Tokenizer::NAME => 'child', - Mustache_Tokenizer::INDEX => 123, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, - Mustache_Tokenizer::NAME => 'parent', - Mustache_Tokenizer::INDEX => 123, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, - Mustache_Tokenizer::NAME => 'child', - Mustache_Tokenizer::INDEX => 123, - ), - ), - ), - ); - } + // weird nesting + array( + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'child', + Mustache_Tokenizer::INDEX => 123, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'parent', + Mustache_Tokenizer::INDEX => 123, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'child', + Mustache_Tokenizer::INDEX => 123, + ), + ), + ), + ); + } } diff --git a/test/Mustache/Test/TemplateTest.php b/test/Mustache/Test/TemplateTest.php index 69ce3f6..a3b14a1 100644 --- a/test/Mustache/Test/TemplateTest.php +++ b/test/Mustache/Test/TemplateTest.php @@ -12,38 +12,44 @@ /** * @group unit */ -class Mustache_Test_TemplateTest extends PHPUnit_Framework_TestCase { - public function testConstructor() { - $mustache = new Mustache_Engine; - $template = new Mustache_Test_TemplateStub($mustache); - $this->assertSame($mustache, $template->getMustache()); - } +class Mustache_Test_TemplateTest extends PHPUnit_Framework_TestCase +{ + public function testConstructor() + { + $mustache = new Mustache_Engine; + $template = new Mustache_Test_TemplateStub($mustache); + $this->assertSame($mustache, $template->getMustache()); + } - public function testRendering() { - $rendered = '<< wheee >>'; - $mustache = new Mustache_Engine; - $template = new Mustache_Test_TemplateStub($mustache); - $template->rendered = $rendered; - $context = new Mustache_Context; + public function testRendering() + { + $rendered = '<< wheee >>'; + $mustache = new Mustache_Engine; + $template = new Mustache_Test_TemplateStub($mustache); + $template->rendered = $rendered; + $context = new Mustache_Context; - if (version_compare(PHP_VERSION, '5.3.0', '>=')) { - $this->assertEquals($rendered, $template()); - } + if (version_compare(PHP_VERSION, '5.3.0', '>=')) { + $this->assertEquals($rendered, $template()); + } - $this->assertEquals($rendered, $template->render()); - $this->assertEquals($rendered, $template->renderInternal($context)); - $this->assertEquals($rendered, $template->render(array('foo' => 'bar'))); - } + $this->assertEquals($rendered, $template->render()); + $this->assertEquals($rendered, $template->renderInternal($context)); + $this->assertEquals($rendered, $template->render(array('foo' => 'bar'))); + } } -class Mustache_Test_TemplateStub extends Mustache_Template { - public $rendered; +class Mustache_Test_TemplateStub extends Mustache_Template +{ + public $rendered; - public function getMustache() { - return $this->mustache; - } + public function getMustache() + { + return $this->mustache; + } - public function renderInternal(Mustache_Context $context, $indent = '', $escape = false) { - return $this->rendered; - } + public function renderInternal(Mustache_Context $context, $indent = '', $escape = false) + { + return $this->rendered; + } } diff --git a/test/Mustache/Test/TokenizerTest.php b/test/Mustache/Test/TokenizerTest.php index 522668c..3f6d76b 100644 --- a/test/Mustache/Test/TokenizerTest.php +++ b/test/Mustache/Test/TokenizerTest.php @@ -12,130 +12,133 @@ /** * @group unit */ -class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase { +class Mustache_Test_TokenizerTest extends PHPUnit_Framework_TestCase +{ - /** - * @dataProvider getTokens - */ - public function testScan($text, $delimiters, $expected) { - $tokenizer = new Mustache_Tokenizer; - $this->assertSame($expected, $tokenizer->scan($text, $delimiters)); - } + /** + * @dataProvider getTokens + */ + public function testScan($text, $delimiters, $expected) + { + $tokenizer = new Mustache_Tokenizer; + $this->assertSame($expected, $tokenizer->scan($text, $delimiters)); + } - public function getTokens() { - return array( - array( - 'text', - null, - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'text', - ), - ), - ), + public function getTokens() + { + return array( + array( + 'text', + null, + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text', + ), + ), + ), - array( - 'text', - '<<< >>>', - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => 'text', - ), - ), - ), + array( + 'text', + '<<< >>>', + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => 'text', + ), + ), + ), - array( - '{{ name }}', - null, - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name', - Mustache_Tokenizer::OTAG => '{{', - Mustache_Tokenizer::CTAG => '}}', - Mustache_Tokenizer::INDEX => 10, - ) - ) - ), + array( + '{{ name }}', + null, + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 10, + ) + ) + ), - array( - '{{ name }}', - '<<< >>>', - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => '{{ name }}', - ), - ), - ), + array( + '{{ name }}', + '<<< >>>', + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => '{{ name }}', + ), + ), + ), - array( - '<<< name >>>', - '<<< >>>', - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'name', - Mustache_Tokenizer::OTAG => '<<<', - Mustache_Tokenizer::CTAG => '>>>', - Mustache_Tokenizer::INDEX => 12, - ) - ) - ), + array( + '<<< name >>>', + '<<< >>>', + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'name', + Mustache_Tokenizer::OTAG => '<<<', + Mustache_Tokenizer::CTAG => '>>>', + Mustache_Tokenizer::INDEX => 12, + ) + ) + ), - array( - "{{{ a }}}\n{{# b }} \n{{= | | =}}| c ||/ b |\n|{ d }|", - null, - array( - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, - Mustache_Tokenizer::NAME => 'a', - Mustache_Tokenizer::OTAG => '{{', - Mustache_Tokenizer::CTAG => '}}', - Mustache_Tokenizer::INDEX => 8, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => "\n", - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, - Mustache_Tokenizer::NAME => 'b', - Mustache_Tokenizer::OTAG => '{{', - Mustache_Tokenizer::CTAG => '}}', - Mustache_Tokenizer::INDEX => 18, - ), - null, - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, - Mustache_Tokenizer::NAME => 'c', - Mustache_Tokenizer::OTAG => '|', - Mustache_Tokenizer::CTAG => '|', - Mustache_Tokenizer::INDEX => 37, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, - Mustache_Tokenizer::NAME => 'b', - Mustache_Tokenizer::OTAG => '|', - Mustache_Tokenizer::CTAG => '|', - Mustache_Tokenizer::INDEX => 37, - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, - Mustache_Tokenizer::VALUE => "\n", - ), - array( - Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, - Mustache_Tokenizer::NAME => 'd', - Mustache_Tokenizer::OTAG => '|', - Mustache_Tokenizer::CTAG => '|', - Mustache_Tokenizer::INDEX => 51, - ), + array( + "{{{ a }}}\n{{# b }} \n{{= | | =}}| c ||/ b |\n|{ d }|", + null, + array( + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, + Mustache_Tokenizer::NAME => 'a', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 8, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => "\n", + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_SECTION, + Mustache_Tokenizer::NAME => 'b', + Mustache_Tokenizer::OTAG => '{{', + Mustache_Tokenizer::CTAG => '}}', + Mustache_Tokenizer::INDEX => 18, + ), + null, + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_ESCAPED, + Mustache_Tokenizer::NAME => 'c', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 37, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_END_SECTION, + Mustache_Tokenizer::NAME => 'b', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 37, + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_TEXT, + Mustache_Tokenizer::VALUE => "\n", + ), + array( + Mustache_Tokenizer::TYPE => Mustache_Tokenizer::T_UNESCAPED, + Mustache_Tokenizer::NAME => 'd', + Mustache_Tokenizer::OTAG => '|', + Mustache_Tokenizer::CTAG => '|', + Mustache_Tokenizer::INDEX => 51, + ), - ) - ), - ); - } + ) + ), + ); + } } diff --git a/test/fixtures/autoloader/Mustache/Bar.php b/test/fixtures/autoloader/Mustache/Bar.php index 1df3265..4cad3d9 100644 --- a/test/fixtures/autoloader/Mustache/Bar.php +++ b/test/fixtures/autoloader/Mustache/Bar.php @@ -9,6 +9,7 @@ * file that was distributed with this source code. */ -class Mustache_Bar { - // nada +class Mustache_Bar +{ + // nada } diff --git a/test/fixtures/autoloader/Mustache/Foo.php b/test/fixtures/autoloader/Mustache/Foo.php index 9cf31a2..e7c0713 100644 --- a/test/fixtures/autoloader/Mustache/Foo.php +++ b/test/fixtures/autoloader/Mustache/Foo.php @@ -9,6 +9,7 @@ * file that was distributed with this source code. */ -class Mustache_Foo { - // nada +class Mustache_Foo +{ + // nada } diff --git a/test/fixtures/autoloader/NonMustacheClass.php b/test/fixtures/autoloader/NonMustacheClass.php index 1d30016..cd216a2 100644 --- a/test/fixtures/autoloader/NonMustacheClass.php +++ b/test/fixtures/autoloader/NonMustacheClass.php @@ -9,6 +9,7 @@ * file that was distributed with this source code. */ -class NonMustacheClass { - // noop +class NonMustacheClass +{ + // noop } diff --git a/test/fixtures/examples/child_context/ChildContext.php b/test/fixtures/examples/child_context/ChildContext.php index 95eb5a6..bae81c6 100644 --- a/test/fixtures/examples/child_context/ChildContext.php +++ b/test/fixtures/examples/child_context/ChildContext.php @@ -1,13 +1,14 @@ 'child works', - ); +class ChildContext +{ + public $parent = array( + 'child' => 'child works', + ); - public $grandparent = array( - 'parent' => array( - 'child' => 'grandchild works', - ), - ); + public $grandparent = array( + 'parent' => array( + 'child' => 'grandchild works', + ), + ); } diff --git a/test/fixtures/examples/comments/Comments.php b/test/fixtures/examples/comments/Comments.php index 6eb7da1..afabd22 100644 --- a/test/fixtures/examples/comments/Comments.php +++ b/test/fixtures/examples/comments/Comments.php @@ -1,7 +1,9 @@ 'red', 'current' => true, 'url' => '#Red'), - array('name' => 'green', 'current' => false, 'url' => '#Green'), - array('name' => 'blue', 'current' => false, 'url' => '#Blue'), - ); + public $item = array( + array('name' => 'red', 'current' => true, 'url' => '#Red'), + array('name' => 'green', 'current' => false, 'url' => '#Green'), + array('name' => 'blue', 'current' => false, 'url' => '#Blue'), + ); - public function notEmpty() { - return !($this->isEmpty()); - } + public function notEmpty() + { + return !($this->isEmpty()); + } - public function isEmpty() { - return count($this->item) === 0; - } + public function isEmpty() + { + return count($this->item) === 0; + } } diff --git a/test/fixtures/examples/delimiters/Delimiters.php b/test/fixtures/examples/delimiters/Delimiters.php index 4dac04d..6f03557 100644 --- a/test/fixtures/examples/delimiters/Delimiters.php +++ b/test/fixtures/examples/delimiters/Delimiters.php @@ -1,14 +1,16 @@ "And it worked the second time."), - array('item' => "As well as the third."), - ); - } + public function middle() + { + return array( + array('item' => "And it worked the second time."), + array('item' => "As well as the third."), + ); + } - public $final = "Then, surprisingly, it worked the final time."; + public $final = "Then, surprisingly, it worked the final time."; } diff --git a/test/fixtures/examples/dot_notation/DotNotation.php b/test/fixtures/examples/dot_notation/DotNotation.php index 13d52f7..d2939f1 100644 --- a/test/fixtures/examples/dot_notation/DotNotation.php +++ b/test/fixtures/examples/dot_notation/DotNotation.php @@ -1,14 +1,15 @@ array('first' => 'Chris', 'last' => 'Firescythe'), - 'age' => 24, - 'hometown' => array( - 'city' => 'Cincinnati', - 'state' => 'OH', - ) - ); +class DotNotation +{ + public $person = array( + 'name' => array('first' => 'Chris', 'last' => 'Firescythe'), + 'age' => 24, + 'hometown' => array( + 'city' => 'Cincinnati', + 'state' => 'OH', + ) + ); - public $normal = 'Normal'; + public $normal = 'Normal'; } diff --git a/test/fixtures/examples/double_section/DoubleSection.php b/test/fixtures/examples/double_section/DoubleSection.php index 31fdfc5..8860181 100644 --- a/test/fixtures/examples/double_section/DoubleSection.php +++ b/test/fixtures/examples/double_section/DoubleSection.php @@ -1,9 +1,11 @@ "Shark"'; +class Escaped +{ + public $title = '"Bear" > "Shark"'; } diff --git a/test/fixtures/examples/grand_parent_context/GrandParentContext.php b/test/fixtures/examples/grand_parent_context/GrandParentContext.php index 6829372..ce218fb 100644 --- a/test/fixtures/examples/grand_parent_context/GrandParentContext.php +++ b/test/fixtures/examples/grand_parent_context/GrandParentContext.php @@ -1,22 +1,24 @@ parent_contexts[] = array('parent_id' => 'parent1', 'child_contexts' => array( - array('child_id' => 'parent1-child1'), - array('child_id' => 'parent1-child2') - )); + public function __construct() + { + $this->parent_contexts[] = array('parent_id' => 'parent1', 'child_contexts' => array( + array('child_id' => 'parent1-child1'), + array('child_id' => 'parent1-child2') + )); - $parent2 = new stdClass(); - $parent2->parent_id = 'parent2'; - $parent2->child_contexts = array( - array('child_id' => 'parent2-child1'), - array('child_id' => 'parent2-child2') - ); + $parent2 = new stdClass(); + $parent2->parent_id = 'parent2'; + $parent2->child_contexts = array( + array('child_id' => 'parent2-child1'), + array('child_id' => 'parent2-child2') + ); - $this->parent_contexts[] = $parent2; - } + $this->parent_contexts[] = $parent2; + } } diff --git a/test/fixtures/examples/i18n/I18n.php b/test/fixtures/examples/i18n/I18n.php index ea62c5d..7b7cd9f 100644 --- a/test/fixtures/examples/i18n/I18n.php +++ b/test/fixtures/examples/i18n/I18n.php @@ -1,6 +1,7 @@ 'Me llamo {{ name }}.', ); - public static function __trans($text) { + public static function __trans($text) + { return isset(self::$dictionary[$text]) ? self::$dictionary[$text] : $text; } } diff --git a/test/fixtures/examples/implicit_iterator/ImplicitIterator.php b/test/fixtures/examples/implicit_iterator/ImplicitIterator.php index d52ac58..6cb7644 100644 --- a/test/fixtures/examples/implicit_iterator/ImplicitIterator.php +++ b/test/fixtures/examples/implicit_iterator/ImplicitIterator.php @@ -1,5 +1,6 @@ 'Dan', - 'child' => array( - 'name' => 'Justin', - 'child' => false, - ) - ); +class RecursivePartials +{ + public $name = 'George'; + public $child = array( + 'name' => 'Dan', + 'child' => array( + 'name' => 'Justin', + 'child' => false, + ) + ); } diff --git a/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php b/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php index 9a14418..3415ed5 100644 --- a/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php +++ b/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php @@ -1,16 +1,18 @@ 'And it worked the second time.'), - array('item' => 'As well as the third.'), - ); + protected $_data = array( + array('item' => 'And it worked the second time.'), + array('item' => 'As well as the third.'), + ); - public function middle() { - return new ArrayIterator($this->_data); - } + public function middle() + { + return new ArrayIterator($this->_data); + } - public $final = "Then, surprisingly, it worked the final time."; + public $final = "Then, surprisingly, it worked the final time."; } diff --git a/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php b/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php index eaf84c1..c03e228 100644 --- a/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php +++ b/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php @@ -1,26 +1,31 @@ 'And it worked the second time.', - 'bar' => 'As well as the third.' - ); +class MagicObject +{ + protected $_data = array( + 'foo' => 'And it worked the second time.', + 'bar' => 'As well as the third.' + ); - public function __get($key) { - return isset($this->_data[$key]) ? $this->_data[$key] : NULL; - } + public function __get($key) + { + return isset($this->_data[$key]) ? $this->_data[$key] : NULL; + } - public function __isset($key) { - return isset($this->_data[$key]); - } + public function __isset($key) + { + return isset($this->_data[$key]); + } } diff --git a/test/fixtures/examples/section_objects/SectionObjects.php b/test/fixtures/examples/section_objects/SectionObjects.php index 8d9f101..e6a6b16 100644 --- a/test/fixtures/examples/section_objects/SectionObjects.php +++ b/test/fixtures/examples/section_objects/SectionObjects.php @@ -1,16 +1,19 @@ "And it worked the second time."), - array('item' => "As well as the third."), - ); - } + public function middle() + { + return array( + array('item' => "And it worked the second time."), + array('item' => "As well as the third."), + ); + } - public $final = "Then, surprisingly, it worked the final time."; + public $final = "Then, surprisingly, it worked the final time."; } diff --git a/test/fixtures/examples/sections_nested/SectionsNested.php b/test/fixtures/examples/sections_nested/SectionsNested.php index ba37ab0..9360505 100644 --- a/test/fixtures/examples/sections_nested/SectionsNested.php +++ b/test/fixtures/examples/sections_nested/SectionsNested.php @@ -1,33 +1,35 @@ 'Von Kaiser', - 'enemies' => array( - array('name' => 'Super Macho Man'), - array('name' => 'Piston Honda'), - array('name' => 'Mr. Sandman'), - ) - ), - array( - 'name' => 'Mike Tyson', - 'enemies' => array( - array('name' => 'Soda Popinski'), - array('name' => 'King Hippo'), - array('name' => 'Great Tiger'), - array('name' => 'Glass Joe'), - ) - ), - array( - 'name' => 'Don Flamenco', - 'enemies' => array( - array('name' => 'Bald Bull'), - ) - ), - ); - } + public function enemies() + { + return array( + array( + 'name' => 'Von Kaiser', + 'enemies' => array( + array('name' => 'Super Macho Man'), + array('name' => 'Piston Honda'), + array('name' => 'Mr. Sandman'), + ) + ), + array( + 'name' => 'Mike Tyson', + 'enemies' => array( + array('name' => 'Soda Popinski'), + array('name' => 'King Hippo'), + array('name' => 'Great Tiger'), + array('name' => 'Glass Joe'), + ) + ), + array( + 'name' => 'Don Flamenco', + 'enemies' => array( + array('name' => 'Bald Bull'), + ) + ), + ); + } } diff --git a/test/fixtures/examples/simple/Simple.php b/test/fixtures/examples/simple/Simple.php index 45f1f34..f097ff2 100644 --- a/test/fixtures/examples/simple/Simple.php +++ b/test/fixtures/examples/simple/Simple.php @@ -1,12 +1,14 @@ value - ($this->value * 0.4); - } + public function taxed_value() + { + return $this->value - ($this->value * 0.4); + } - public $in_ca = true; + public $in_ca = true; }; diff --git a/test/fixtures/examples/unescaped/Unescaped.php b/test/fixtures/examples/unescaped/Unescaped.php index 99dcdab..282ba21 100644 --- a/test/fixtures/examples/unescaped/Unescaped.php +++ b/test/fixtures/examples/unescaped/Unescaped.php @@ -1,5 +1,6 @@ Shark"; +class Unescaped +{ + public $title = "Bear > Shark"; } diff --git a/test/fixtures/examples/utf8/UTF8.php b/test/fixtures/examples/utf8/UTF8.php index 258fa70..e5a7877 100644 --- a/test/fixtures/examples/utf8/UTF8.php +++ b/test/fixtures/examples/utf8/UTF8.php @@ -1,5 +1,6 @@ tag }}` and `{{> tag}}` and `{{>tag}}` should all be equivalent. */ -class Whitespace { - public $foo = 'alpha'; +class Whitespace +{ + public $foo = 'alpha'; - public $bar = 'beta'; + public $bar = 'beta'; - public function baz() { - return 'gamma'; - } + public function baz() + { + return 'gamma'; + } - public function qux() { - return array( - array('key with space' => 'A'), - array('key with space' => 'B'), - array('key with space' => 'C'), - array('key with space' => 'D'), - array('key with space' => 'E'), - array('key with space' => 'F'), - array('key with space' => 'G'), - ); - } + public function qux() + { + return array( + array('key with space' => 'A'), + array('key with space' => 'B'), + array('key with space' => 'C'), + array('key with space' => 'D'), + array('key with space' => 'E'), + array('key with space' => 'F'), + array('key with space' => 'G'), + ); + } } From 4dd4db606503c27e7eafad362bd0acdf9a921f21 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 3 May 2012 08:03:54 -0700 Subject: [PATCH 49/58] Code style cleanup. --- src/Mustache/Compiler.php | 4 ++++ src/Mustache/Parser.php | 6 +++--- src/Mustache/Template.php | 4 ++-- src/Mustache/Tokenizer.php | 3 ++- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index db152e4..845fee0 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -29,6 +29,8 @@ class Mustache_Compiler * @param string $source Mustache Template source code * @param string $tree Parse tree of Mustache tokens * @param string $name Mustache Template class name + * @param bool $customEscape (default: false) + * @param string $charset (default: 'UTF-8') * * @return string Generated PHP source code */ @@ -328,6 +330,8 @@ class Mustache_Compiler /** * Get the current escaper. * + * @param string $value (default: '$value') + * * @return string Either a custom callback, or an inline call to `htmlspecialchars` */ private function getEscape($value = '$value') diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php index 5b31823..5766dde 100644 --- a/src/Mustache/Parser.php +++ b/src/Mustache/Parser.php @@ -32,12 +32,12 @@ class Mustache_Parser /** * Helper method for recursively building a parse tree. * - * @throws LogicException when nesting errors or mismatched section tags are encountered. - * * @param ArrayIterator $tokens Stream of Mustache tokens - * @param array $parent Parent token (default: null) + * @param array $parent Parent token (default: null) * * @return array Mustache Token parse tree + * + * @throws LogicException when nesting errors or mismatched section tags are encountered. */ private function buildTree(ArrayIterator $tokens, array $parent = null) { diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 819efbf..249e4c2 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -67,9 +67,9 @@ abstract class Mustache_Template * * This is where the magic happens :) * - * @abstract - * * @param Mustache_Context $context + * @param string $indent (default: '') + * @param bool $escape (default: false) * * @return string Rendered template */ diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php index 6ecbfea..1dd3ef8 100644 --- a/src/Mustache/Tokenizer.php +++ b/src/Mustache/Tokenizer.php @@ -14,7 +14,8 @@ * * This class is responsible for turning raw template source into a set of Mustache tokens. */ -class Mustache_Tokenizer { +class Mustache_Tokenizer +{ // Finite state machine states const IN_TEXT = 0; From 5486537b10710f20f92bfac8f7bec658b4de0c26 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 17 May 2012 14:58:28 -0700 Subject: [PATCH 50/58] Composer updates --- .gitignore | 1 + .travis.yml | 1 + composer.json | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 2659611..987e2a2 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ composer.lock +vendor diff --git a/.travis.yml b/.travis.yml index 1284d21..d549e06 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,6 @@ language: php php: + - 5.2.4 - 5.2 - 5.3 - 5.4 diff --git a/composer.json b/composer.json index 4e42da3..61b6552 100644 --- a/composer.json +++ b/composer.json @@ -1,5 +1,5 @@ { - "name": "bobthecow/mustache", + "name": "mustache/mustache", "description": "A Mustache implementation in PHP.", "keywords": ["templating", "mustache"], "homepage": "https://github.com/bobthecow/mustache.php", From 49e47de61216a3e4df55be7f9fa443125e41bf43 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 17 May 2012 15:02:28 -0700 Subject: [PATCH 51/58] Use versions Travis actually supports --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index d549e06..292e287 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,6 @@ language: php php: - - 5.2.4 - 5.2 + - 5.3.2 - 5.3 - 5.4 From d8bc0b870feffc59587687da27839bb288d19407 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 17 May 2012 16:21:04 -0700 Subject: [PATCH 52/58] 'Improve' code coverage :) --- src/Mustache/Engine.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Mustache/Engine.php b/src/Mustache/Engine.php index 94ea124..6f4afd6 100644 --- a/src/Mustache/Engine.php +++ b/src/Mustache/Engine.php @@ -566,6 +566,8 @@ class Mustache_Engine * * @param string $fileName * @param string $source + * + * @codeCoverageIgnore */ private function writeCacheFile($fileName, $source) { From 7750a4136918a9094dee8ed413cbf8394d6dccc4 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Thu, 17 May 2012 16:21:14 -0700 Subject: [PATCH 53/58] Minor code style cleanup. --- composer.json | 2 +- src/Mustache/Compiler.php | 10 +++++----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/composer.json b/composer.json index 61b6552..ebf9541 100644 --- a/composer.json +++ b/composer.json @@ -9,7 +9,7 @@ { "name": "Justin Hileman", "email": "justin@justinhileman.info", - "homepage": "http://justinhileman.com/" + "homepage": "http://justinhileman.com" } ], "require": { diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 845fee0..329a8c6 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -26,11 +26,11 @@ class Mustache_Compiler /** * Compile a Mustache token parse tree into PHP source code. * - * @param string $source Mustache Template source code - * @param string $tree Parse tree of Mustache tokens - * @param string $name Mustache Template class name + * @param string $source Mustache Template source code + * @param string $tree Parse tree of Mustache tokens + * @param string $name Mustache Template class name * @param bool $customEscape (default: false) - * @param string $charset (default: 'UTF-8') + * @param string $charset (default: 'UTF-8') * * @return string Generated PHP source code */ @@ -53,7 +53,7 @@ class Mustache_Compiler * @param array $tree Parse tree of Mustache tokens * @param int $level (default: 0) * - * @return string Generated PHP source code; + * @return string Generated PHP source code */ private function walk(array $tree, $level = 0) { From 83b6f935f7623bc7b8a2d1998606d67f2edcafc4 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 13 Jun 2012 12:50:18 -0700 Subject: [PATCH 54/58] Fixes for PSR-1/2 --- src/Mustache/Autoloader.php | 2 +- src/Mustache/Compiler.php | 1 - src/Mustache/Template.php | 4 ++-- 3 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php index 5d70a8e..df48536 100644 --- a/src/Mustache/Autoloader.php +++ b/src/Mustache/Autoloader.php @@ -38,7 +38,7 @@ class Mustache_Autoloader * * @return Mustache_Autoloader Registered Autoloader instance */ - static public function register($baseDir = null) + public static function register($baseDir = null) { $loader = new self($baseDir); spl_autoload_register(array($loader, 'autoload')); diff --git a/src/Mustache/Compiler.php b/src/Mustache/Compiler.php index 329a8c6..e7f34e7 100644 --- a/src/Mustache/Compiler.php +++ b/src/Mustache/Compiler.php @@ -102,7 +102,6 @@ class Mustache_Compiler $code .= $this->variable($node[Mustache_Tokenizer::NAME], true, $level); break; - case Mustache_Tokenizer::T_TEXT: $code .= $this->text($node[Mustache_Tokenizer::VALUE], $level); break; diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php index 249e4c2..b9c81fd 100644 --- a/src/Mustache/Template.php +++ b/src/Mustache/Template.php @@ -68,8 +68,8 @@ abstract class Mustache_Template * This is where the magic happens :) * * @param Mustache_Context $context - * @param string $indent (default: '') - * @param bool $escape (default: false) + * @param string $indent (default: '') + * @param bool $escape (default: false) * * @return string Rendered template */ From 0c22b75ec1341fc51c8610f23a5538dd57a2ea6d Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 13 Jun 2012 12:51:37 -0700 Subject: [PATCH 55/58] Version bump to 2.0.2-rc.1 --- src/Mustache/Engine.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Mustache/Engine.php b/src/Mustache/Engine.php index 6f4afd6..762bd47 100644 --- a/src/Mustache/Engine.php +++ b/src/Mustache/Engine.php @@ -23,7 +23,7 @@ */ class Mustache_Engine { - const VERSION = '2.0.0-dev'; + const VERSION = '2.0.0-rc.1'; const SPEC_VERSION = '1.1.2'; // Template cache From 27c7719a33c1149b70bd926c76a4642df8a7620d Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Wed, 13 Jun 2012 17:40:51 -0700 Subject: [PATCH 56/58] Travis changes available point releases too often. --- .travis.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 292e287..1284d21 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,6 +1,5 @@ language: php php: - 5.2 - - 5.3.2 - 5.3 - 5.4 From be5390b2d7904b0af1690c37661bc59974a8852c Mon Sep 17 00:00:00 2001 From: Roy Date: Fri, 6 Jul 2012 12:14:53 -0300 Subject: [PATCH 57/58] Update Readme.markdown to point at the updated mustache.github.com url. Conflicts: vendor/spec --- README.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.markdown b/README.markdown index 86cebfa..d7ef259 100644 --- a/README.markdown +++ b/README.markdown @@ -1,7 +1,7 @@ Mustache.php ============ -A [Mustache](http://defunkt.github.com/mustache/) implementation in PHP. +A [Mustache](http://mustache.github.com/) implementation in PHP. [![Build Status](https://secure.travis-ci.org/bobthecow/mustache.php.png?branch=dev)](http://travis-ci.org/bobthecow/mustache.php) From 0673292ac8a9988ee42eab3d14cf164c263918c4 Mon Sep 17 00:00:00 2001 From: Justin Hileman Date: Mon, 9 Jul 2012 14:53:10 -0700 Subject: [PATCH 58/58] Bump version to 2.0.0 --- src/Mustache/Engine.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Mustache/Engine.php b/src/Mustache/Engine.php index 762bd47..751a3e8 100644 --- a/src/Mustache/Engine.php +++ b/src/Mustache/Engine.php @@ -23,7 +23,7 @@ */ class Mustache_Engine { - const VERSION = '2.0.0-rc.1'; + const VERSION = '2.0.0'; const SPEC_VERSION = '1.1.2'; // Template cache