diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..987e2a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +composer.lock +vendor diff --git a/.gitmodules b/.gitmodules index 1aaa50a..54f3a7b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -1,3 +1,6 @@ -[submodule "test/spec"] - path = test/spec +[submodule "vendor/spec"] + path = vendor/spec url = git://github.com/mustache/spec.git +[submodule "vendor/yaml"] + path = vendor/yaml + url = git://github.com/fabpot/yaml.git diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..1284d21 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,5 @@ +language: php +php: + - 5.2 + - 5.3 + - 5.4 diff --git a/Mustache.php b/Mustache.php deleted file mode 100644 index 18236aa..0000000 --- a/Mustache.php +++ /dev/null @@ -1,931 +0,0 @@ - false, - MustacheException::UNCLOSED_SECTION => true, - MustacheException::UNEXPECTED_CLOSE_SECTION => true, - MustacheException::UNKNOWN_PARTIAL => false, - MustacheException::UNKNOWN_PRAGMA => true, - ); - - // Override the escaper function. Defaults to `htmlspecialchars`. - protected $_escape; - - // 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(); - - /** - * 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( - * // `escape` -- custom escaper callback; must be callable. - * 'escape' => function($text) { - * return htmlspecialchars($text, ENT_COMPAT, 'UTF-8'); - * }, - * - * // `charset` -- must be supported by `htmlspecialentities()`. 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); - } - - /** - * Helper function for setting options from constructor args. - * - * @access protected - * @param array $options - * @return void - */ - protected function _setOptions(array $options) { - 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']; - } - - 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; - } - } - } - - /** - * Mustache class clone method. - * - * 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(); - } - } - - /** - * Internal render function, used for recursive calls. - * - * @access protected - * @param string $template - * @return string Rendered Mustache template. - */ - protected function _renderTemplate($template) { - if ($section = $this->_findSection($template)) { - list($before, $type, $tag_name, $content, $after) = $section; - - $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); - } - - return $this->_renderTags($template); - } - - /** - * Prepare a section RegEx string for the given opening/closing tags. - * - * @access protected - * @param string $otag - * @param string $ctag - * @return string - */ - 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, '/') - ); - } - - /** - * Extract the first section from $template. - * - * @access protected - * @param string $template - * @return array $before, $type, $tag_name, $content and $after - */ - protected function _findSection($template) { - $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag); - - $section_start = null; - $section_type = null; - $content_start = null; - - $search_offset = 0; - - $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; - } - - $match = $matches[0][0]; - $offset = $matches[0][1]; - $type = $matches['type'][0]; - $tag_name = trim($matches['tag_name'][0]); - - $search_offset = $offset + strlen($match); - - 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); - } - } - - 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); - } else { - return $this->_renderUnescaped($tag_name, $leading, $trailing); - } - 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; - } - } - return false; - } - - /** - * Escape and return the requested tag. - * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string - */ - protected function _renderEscaped($tag_name, $leading, $trailing) { - $value = $this->_renderUnescaped($tag_name, '', ''); - if (isset($this->_escape)) { - $rendered = call_user_func($this->_escape, $value); - } else { - $rendered = htmlentities($value, ENT_COMPAT, $this->_charset); - } - - return $leading . $rendered . $trailing; - } - - /** - * Render a comment (i.e. return an empty string). - * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string - */ - 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; - } - - /** - * Return the requested tag unescaped. - * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string - */ - 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; - } - - /** - * Render the requested partial. - * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string - */ - 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; - } - } - - /** - * Change the Mustache tag delimiter. This method also replaces this object's current - * tag RegEx with one using the new delimiters. - * - * @access protected - * @param string $tag_name - * @param string $leading Whitespace - * @param string $trailing Whitespace - * @return string - */ - 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"; - } - 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; - } - - /** - * 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]; - } - } - - 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); - } -} - - -/** - * 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/MustacheLoader.php b/MustacheLoader.php deleted file mode 100644 index 9c4b386..0000000 --- a/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/README.markdown b/README.markdown index 989ff97..d7ef259 100644 --- a/README.markdown +++ b/README.markdown @@ -1,8 +1,9 @@ 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) Usage ----- @@ -11,16 +12,14 @@ A quick example: ```php render('Hello {{planet}}', array('planet' => 'World!')); -// "Hello World!" +$m = new Mustache_Engine; +echo $m->render('Hello {{planet}}', 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: -``` +```html+jinja Hello {{name}} You have just won ${{value}}! {{#in_ca}} @@ -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); ``` -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 -------- + * [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. diff --git a/bin/create_example.php b/bin/create_example.php index 1f0b894..05e52b3 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')); /** @@ -39,10 +38,10 @@ define('EXAMPLE_PATH', realpath(dirname(__FILE__) . DS . ".." . DS . "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)); } /** @@ -58,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)); } @@ -73,8 +72,8 @@ function getUpperCaseName($name) { * @return mixed */ function out($value) { - echo $value . "\n"; - return $value; + echo $value . "\n"; + return $value; } /** @@ -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 : "")); } /** @@ -103,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"); + } } /** @@ -120,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"); + } } @@ -144,29 +143,29 @@ 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/composer.json b/composer.json new file mode 100644 index 0000000..ebf9541 --- /dev/null +++ b/composer.json @@ -0,0 +1,21 @@ +{ + "name": "mustache/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.2.4" + }, + "autoload": { + "psr-0": { "Mustache": "src/" } + } +} diff --git a/examples/child_context/ChildContext.php b/examples/child_context/ChildContext.php deleted file mode 100644 index b652356..0000000 --- a/examples/child_context/ChildContext.php +++ /dev/null @@ -1,13 +0,0 @@ - '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 deleted file mode 100644 index 7f028ba..0000000 --- a/examples/comments/Comments.php +++ /dev/null @@ -1,7 +0,0 @@ - '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 isEmpty() { - return count($this->item) === 0; - } -} \ No newline at end of file diff --git a/examples/delimiters/Delimiters.php b/examples/delimiters/Delimiters.php deleted file mode 100644 index be372fa..0000000 --- a/examples/delimiters/Delimiters.php +++ /dev/null @@ -1,14 +0,0 @@ - "And it worked the second time."), - array('item' => "As well as the third."), - ); - } - - public $final = "Then, surprisingly, it worked the final time."; -} \ No newline at end of file diff --git a/examples/dot_notation/DotNotation.php b/examples/dot_notation/DotNotation.php deleted file mode 100644 index 7dd0a4e..0000000 --- a/examples/dot_notation/DotNotation.php +++ /dev/null @@ -1,20 +0,0 @@ - array('first' => 'Chris', 'last' => 'Firescythe'), - 'age' => 24, - 'hobbies' => array('Cycling', 'Fishing'), - 'hometown' => array( - 'city' => 'Cincinnati', - 'state' => 'OH', - ), - ); - - public $normal = 'Normal'; -} diff --git a/examples/double_section/DoubleSection.php b/examples/double_section/DoubleSection.php deleted file mode 100644 index f9d3dbb..0000000 --- a/examples/double_section/DoubleSection.php +++ /dev/null @@ -1,9 +0,0 @@ - "Shark"'; -} \ No newline at end of file diff --git a/examples/grand_parent_context/GrandParentContext.php b/examples/grand_parent_context/GrandParentContext.php deleted file mode 100644 index 5a59ed9..0000000 --- a/examples/grand_parent_context/GrandParentContext.php +++ /dev/null @@ -1,24 +0,0 @@ -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/implicit_iterator/ImplicitIterator.php b/examples/implicit_iterator/ImplicitIterator.php deleted file mode 100644 index c01fef0..0000000 --- a/examples/implicit_iterator/ImplicitIterator.php +++ /dev/null @@ -1,5 +0,0 @@ -{{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 deleted file mode 100644 index 2b9ed3f..0000000 --- a/examples/inverted_section/inverted_section.txt +++ /dev/null @@ -1 +0,0 @@ -No repos :( \ No newline at end of file diff --git a/examples/partials/Partials.php b/examples/partials/Partials.php deleted file mode 100644 index 093257b..0000000 --- a/examples/partials/Partials.php +++ /dev/null @@ -1,13 +0,0 @@ - '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.mustache b/examples/partials/partials.mustache deleted file mode 100644 index 037e1b3..0000000 --- a/examples/partials/partials.mustache +++ /dev/null @@ -1,2 +0,0 @@ -Children of {{name}}: -{{>children}} \ No newline at end of file diff --git a/examples/partials/partials.txt b/examples/partials/partials.txt deleted file mode 100644 index d967e15..0000000 --- a/examples/partials/partials.txt +++ /dev/null @@ -1,3 +0,0 @@ -Children of ilmich: -federica - 27 - female -marco - 32 - male 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 deleted file mode 100644 index 04e8af8..0000000 --- a/examples/recursive_partials/RecursivePartials.php +++ /dev/null @@ -1,16 +0,0 @@ - " > {{ name }}{{#child}}{{>child}}{{/child}}", - ); - - public $name = 'George'; - public $child = array( - 'name' => 'Dan', - 'child' => array( - 'name' => 'Justin', - 'child' => false, - ) - ); -} \ No newline at end of file diff --git a/examples/section_iterator_objects/SectionIteratorObjects.php b/examples/section_iterator_objects/SectionIteratorObjects.php deleted file mode 100644 index 7b65597..0000000 --- a/examples/section_iterator_objects/SectionIteratorObjects.php +++ /dev/null @@ -1,16 +0,0 @@ - 'And it worked the second time.'), - array('item' => 'As well as the third.'), - ); - - public function middle() { - return new ArrayIterator($this->_data); - } - - public $final = "Then, surprisingly, it worked the final time."; -} \ No newline at end of file diff --git a/examples/section_magic_objects/SectionMagicObjects.php b/examples/section_magic_objects/SectionMagicObjects.php deleted file mode 100644 index ebb0031..0000000 --- a/examples/section_magic_objects/SectionMagicObjects.php +++ /dev/null @@ -1,26 +0,0 @@ - '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 __isset($key) { - return isset($this->_data[$key]); - } -} \ No newline at end of file diff --git a/examples/section_objects/SectionObjects.php b/examples/section_objects/SectionObjects.php deleted file mode 100644 index 41b7d84..0000000 --- a/examples/section_objects/SectionObjects.php +++ /dev/null @@ -1,16 +0,0 @@ - "And it worked the second time."), - array('item' => "As well as the third."), - ); - } - - public $final = "Then, surprisingly, it worked the final time."; -} \ No newline at end of file diff --git a/examples/sections_nested/SectionsNested.php b/examples/sections_nested/SectionsNested.php deleted file mode 100644 index ec01b75..0000000 --- a/examples/sections_nested/SectionsNested.php +++ /dev/null @@ -1,33 +0,0 @@ - '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'), - ) - ), - ); - } -} \ No newline at end of file diff --git a/examples/simple/Simple.php b/examples/simple/Simple.php deleted file mode 100644 index 6d07dac..0000000 --- a/examples/simple/Simple.php +++ /dev/null @@ -1,12 +0,0 @@ -value - ($this->value * 0.4); - } - - public $in_ca = true; -}; \ No newline at end of file diff --git a/examples/unescaped/Unescaped.php b/examples/unescaped/Unescaped.php deleted file mode 100644 index 41b10cb..0000000 --- a/examples/unescaped/Unescaped.php +++ /dev/null @@ -1,5 +0,0 @@ - Shark"; -} \ No newline at end of file diff --git a/examples/utf8/UTF8.php b/examples/utf8/UTF8.php deleted file mode 100644 index 7843f53..0000000 --- a/examples/utf8/UTF8.php +++ /dev/null @@ -1,5 +0,0 @@ - tag }}` and `{{> tag}}` and `{{>tag}}` should all be equivalent. - * - * @extends Mustache - */ -class Whitespace extends Mustache { - public $foo = 'alpha'; - - public $bar = 'beta'; - - 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'), - ); - } - - protected $_partials = array( - 'alphabet' => " * {{.}}\n", - ); -} \ No newline at end of file diff --git a/phpunit.xml.dist b/phpunit.xml.dist new file mode 100644 index 0000000..3c620b6 --- /dev/null +++ b/phpunit.xml.dist @@ -0,0 +1,17 @@ + + + + ./test + ./test/Mustache/Test/FiveThree + + + + ./test/Mustache/Test/FiveThree + + + + + ./src/Mustache + + + \ No newline at end of file diff --git a/src/Mustache/Autoloader.php b/src/Mustache/Autoloader.php new file mode 100644 index 0000000..df48536 --- /dev/null +++ b/src/Mustache/Autoloader.php @@ -0,0 +1,69 @@ +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 + */ + public static 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/src/Mustache/Compiler.php b/src/Mustache/Compiler.php new file mode 100644 index 0000000..e7f34e7 --- /dev/null +++ b/src/Mustache/Compiler.php @@ -0,0 +1,386 @@ +sections = array(); + $this->source = $source; + $this->indentNextLine = true; + $this->customEscape = $customEscape; + $this->charset = $charset; + + 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; + + 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_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_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; + + default: + throw new InvalidArgumentException('Unknown node type: '.json_encode($node)); + } + } + + return $code; + } + + const KLASS = 'walk($tree); + $sections = implode("\n", $this->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 = ' + 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; + }'; + + /** + * 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 = ''; + } + + $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 = ' + // %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); + + 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); + } + '; + + /** + * 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; + '; + + /** + * 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); + } + + 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; + + 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++; + } + + 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)'; + + /** + * 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') + { + 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'; + } + } + + 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/src/Mustache/Context.php b/src/Mustache/Context.php new file mode 100644 index 0000000..6a2d57c --- /dev/null +++ b/src/Mustache/Context.php @@ -0,0 +1,149 @@ +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); + } + + /** + * 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/Engine.php b/src/Mustache/Engine.php new file mode 100644 index 0000000..751a3e8 --- /dev/null +++ b/src/Mustache/Engine.php @@ -0,0 +1,589 @@ + '__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['loader'])) { + $this->setLoader($options['loader']); + } + + if (isset($options['partials_loader'])) { + $this->setPartialsLoader($options['partials_loader']); + } + + if (isset($options['partials'])) { + $this->setPartials($options['partials']); + } + + 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'); + } + + $this->escape = $options['escape']; + } + + 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); + } + + /** + * 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; + } + + /** + * 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; + } + + return $this->loader; + } + + /** + * 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; + } + + 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'); + } + + $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_Engine::setHelpers + * + * @return Mustache_HelperCollection + */ + public function getHelpers() + { + if (!isset($this->helpers)) { + $this->helpers = new Mustache_HelperCollection; + } + + 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); + } + + /** + * 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); + } + + /** + * 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; + } + + /** + * 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; + } + + /** + * 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; + } + + return $this->parser; + } + + /** + * 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; + } + + 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 + )); + } + + /** + * 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 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_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)); + } + + require_once $fileName; + } else { + eval('?>'.$this->compile($source)); + } + } + + $this->templates[$className] = new $className($this); + } + + 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 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); + + 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 dump a generated Mustache Template subclass to the file cache. + * + * @throws RuntimeException if unable to write to $fileName. + * + * @param string $fileName + * @param string $source + * + * @codeCoverageIgnore + */ + 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); + + return; + } + } + + throw new RuntimeException(sprintf('Failed to write cache file "%s".', $fileName)); + } +} diff --git a/src/Mustache/HelperCollection.php b/src/Mustache/HelperCollection.php new file mode 100644 index 0000000..f6354e6 --- /dev/null +++ b/src/Mustache/HelperCollection.php @@ -0,0 +1,168 @@ + $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/Loader.php b/src/Mustache/Loader.php new file mode 100644 index 0000000..21229d1 --- /dev/null +++ b/src/Mustache/Loader.php @@ -0,0 +1,26 @@ + '{{ bar }}', + * 'baz' => 'Hey {{ qux }}!' + * ); + * + * $tpl = $loader->load('foo'); // '{{ bar }}' + * + * 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 + * @implements 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; + } + + /** + * 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..dc488f2 --- /dev/null +++ b/src/Mustache/Loader/FilesystemLoader.php @@ -0,0 +1,118 @@ +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(dirname(__FILE__).'/views'), + * 'partials_loader' => new FilesystemLoader(dirname(__FILE__).'/views/partials'), + * )); + * + * @implements Loader + */ +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), '/'); + + 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(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]; + } + + /** + * 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..02bb207 --- /dev/null +++ b/src/Mustache/Loader/MutableLoader.php @@ -0,0 +1,32 @@ +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 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; + } +} diff --git a/src/Mustache/Parser.php b/src/Mustache/Parser.php new file mode 100644 index 0000000..5766dde --- /dev/null +++ b/src/Mustache/Parser.php @@ -0,0 +1,88 @@ +buildTree(new ArrayIterator($tokens)); + } + + /** + * Helper method for recursively building a parse tree. + * + * @param ArrayIterator $tokens Stream of Mustache tokens + * @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) + { + $nodes = array(); + + 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; + + 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]); + } + + $parent[Mustache_Tokenizer::END] = $token[Mustache_Tokenizer::INDEX]; + $parent[Mustache_Tokenizer::NODES] = $nodes; + + return $parent; + break; + + default: + $nodes[] = $token; + break; + } + } + + } while ($tokens->valid()); + + if (isset($parent)) { + throw new LogicException('Missing closing tag: ' . $parent[Mustache_Tokenizer::NAME]); + } + + return $nodes; + } +} diff --git a/src/Mustache/Template.php b/src/Mustache/Template.php new file mode 100644 index 0000000..b9c81fd --- /dev/null +++ b/src/Mustache/Template.php @@ -0,0 +1,149 @@ +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); + } + + /** + * 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 :) + * + * @param Mustache_Context $context + * @param string $indent (default: '') + * @param bool $escape (default: false) + * + * @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; + } + } + + 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; + + $helpers = $this->mustache->getHelpers(); + if (!$helpers->isEmpty()) { + $stack->push($helpers); + } + + if (!empty($context)) { + $stack->push($context); + } + + return $stack; + } +} diff --git a/src/Mustache/Tokenizer.php b/src/Mustache/Tokenizer.php new file mode 100644 index 0000000..1dd3ef8 --- /dev/null +++ b/src/Mustache/Tokenizer.php @@ -0,0 +1,286 @@ +'; + 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, + ); + + // 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'; + + 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(); + + 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; + 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; + + 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->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[] = 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; + } + } + } + + 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]; + } + + $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); + } + + /** + * 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; + } + + /** + * 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 new file mode 100644 index 0000000..2c35ba2 --- /dev/null +++ b/test/Mustache/Test/AutoloaderTest.php @@ -0,0 +1,36 @@ +assertTrue(spl_autoload_unregister(array($loader, 'autoload'))); + } + + public function testAutoloader() + { + $loader = new Mustache_Autoloader(dirname(__FILE__).'/../../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/Mustache/Test/CompilerTest.php b/test/Mustache/Test/CompilerTest.php new file mode 100644 index 0000000..8b6f5be --- /dev/null +++ b/test/Mustache/Test/CompilerTest.php @@ -0,0 +1,103 @@ +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;', + )), + + 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('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'); + } + + 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 new file mode 100644 index 0000000..857dc0a --- /dev/null +++ b/test/Mustache/Test/ContextTest.php @@ -0,0 +1,119 @@ +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')); + + $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()); + + $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()); + } + + public function testFind() + { + $context = new Mustache_Context; + + $dummy = new Mustache_Test_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 Mustache_Test_TestDummy +{ + public $name = 'dummy'; + + public function __invoke() + { + // nothing + } + + public static function foo() + { + return ''; + } + + public function bar() + { + return ''; + } +} diff --git a/test/Mustache/Test/EngineTest.php b/test/Mustache/Test/EngineTest.php new file mode 100644 index 0000000..35390c1 --- /dev/null +++ b/test/Mustache/Test/EngineTest.php @@ -0,0 +1,256 @@ + '__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')); + } + + public static function getFoo() + { + return 'foo'; + } + + 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 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->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 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)); + } + + /** + * @expectedException InvalidArgumentException + * @dataProvider getBadEscapers + */ + public function testNonCallableEscapeThrowsException($escape) + { + new Mustache_Engine(array('escape' => $escape)); + } + + 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, + )); + + $mustache->setPartials(array('foo' => '{{ foo }}')); + } + + 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())); + } + + 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')); + + $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')); + + $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"))); + } + + public static function wrapWithUnderscores($text) + { + return '__'.$text.'__'; + } + + /** + * @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; + } + + $fullpath = $path.$file; + if (is_dir($fullpath)) { + self::rmdir($fullpath); + } else { + unlink($fullpath); + } + } + + closedir($handle); + rmdir($path); + } +} + +class MustacheStub extends Mustache_Engine { + public $source; + public $template; + public function loadTemplate($source) + { + $this->source = $source; + + return $this->template; + } +} diff --git a/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php new file mode 100644 index 0000000..8453c93 --- /dev/null +++ b/test/Mustache/Test/FiveThree/Functional/HigherOrderSectionsTest.php @@ -0,0 +1,71 @@ +mustache = new Mustache_Engine; + } + + 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..cf26ae1 --- /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/CallTest.php b/test/Mustache/Test/Functional/CallTest.php new file mode 100644 index 0000000..53b93b7 --- /dev/null +++ b/test/Mustache/Test/Functional/CallTest.php @@ -0,0 +1,40 @@ +loadTemplate('{{# foo }}{{ label }}: {{ name }}{{/ foo }}'); + + $foo = new Mustache_Test_Functional_ClassWithCall(); + $foo->name = 'Bob'; + + $data = array('label' => 'name', 'foo' => $foo); + + $this->assertEquals('name: Bob', $tpl->render($data)); + } +} + +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 new file mode 100644 index 0000000..6c335e8 --- /dev/null +++ b/test/Mustache/Test/Functional/ExamplesTest.php @@ -0,0 +1,142 @@ + $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(); + + $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/Functional/HigherOrderSectionsTest.php b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php new file mode 100644 index 0000000..4c3cba6 --- /dev/null +++ b/test/Mustache/Test/Functional/HigherOrderSectionsTest.php @@ -0,0 +1,106 @@ +mustache = new Mustache_Engine; + } + + public function testRuntimeSectionCallback() + { + $tpl = $this->mustache->loadTemplate('{{#doublewrap}}{{name}}{{/doublewrap}}'); + + $foo = new Mustache_Test_Functional_Foo; + $foo->doublewrap = array($foo, 'wrapWithBoth'); + + $this->assertEquals(sprintf('%s', $foo->name), $tpl->render($foo)); + } + + public function testStaticSectionCallback() + { + $tpl = $this->mustache->loadTemplate('{{#trimmer}} {{name}} {{/trimmer}}'); + + $foo = new Mustache_Test_Functional_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 Mustache_Test_Functional_Foo; + + $data = array( + 'name' => 'Bob', + 'trim' => array(get_class($foo), 'staticTrim'), + ); + + $this->assertEquals($data['name'], $tpl->render($data)); + } + + 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)); + + $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,'; + + public function wrapWithEm($text) + { + return sprintf('%s', $text); + } + + public function wrapWithStrong($text) + { + return sprintf('%s', $text); + } + + public function wrapWithBoth($text) + { + return self::wrapWithStrong(self::wrapWithEm($text)); + } + + public static function staticTrim($text) + { + return trim($text); + } +} + +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 new file mode 100644 index 0000000..c6d6337 --- /dev/null +++ b/test/Mustache/Test/Functional/MustacheInjectionTest.php @@ -0,0 +1,152 @@ +mustache = new Mustache_Engine; + } + + // 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 + + public function testSectionInjection() + { + $tpl = $this->mustache->loadTemplate('{{# a }}{{ b }}{{/ a }}'); + + $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 + + public function testPartialInjection() + { + $tpl = $this->mustache->loadTemplate('{{> partial }}'); + $this->mustache->setPartials(array( + 'partial' => '{{ a }}', + )); + + $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 + + public function testLambdaInterpolationInjection() + { + $tpl = $this->mustache->loadTemplate('{{ a }}'); + + $data = array( + 'a' => array($this, 'lambdaInterpolationCallback'), + 'b' => '{{ c }}', + 'c' => 'FAIL' + ); + + $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' => 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 new file mode 100644 index 0000000..470f7f3 --- /dev/null +++ b/test/Mustache/Test/Functional/MustacheSpecTest.php @@ -0,0 +1,175 @@ +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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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); + } + + 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 = 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/ObjectSectionTest.php b/test/Mustache/Test/Functional/ObjectSectionTest.php new file mode 100644 index 0000000..893b668 --- /dev/null +++ b/test/Mustache/Test/Functional/ObjectSectionTest.php @@ -0,0 +1,110 @@ +mustache = new Mustache_Engine; + } + + 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 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)); + } +} + +class Mustache_Test_Functional_Alpha +{ + public $foo; + + public function __construct() + { + $this->foo = new StdClass(); + $this->foo->name = 'Foo'; + $this->foo->number = 1; + } +} + +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 __isset($name) + { + return array_key_exists($name, $this->_data); + } + + public function __get($name) + { + return $this->_data[$name]; + } +} + +class Mustache_Test_Functional_Gamma +{ + public $bar; + + public function __construct() + { + $this->bar = new Mustache_Test_Functional_Beta; + } +} + +class Mustache_Test_Functional_Delta +{ + protected $_name = 'Foo'; + + public function name() + { + return $this->_name; + } +} diff --git a/test/Mustache/Test/HelperCollectionTest.php b/test/Mustache/Test/HelperCollectionTest.php new file mode 100644 index 0000000..8bd54f9 --- /dev/null +++ b/test/Mustache/Test/HelperCollectionTest.php @@ -0,0 +1,163 @@ + $foo, + 'bar' => $bar, + )); + + $this->assertSame($foo, $helpers->get('foo')); + $this->assertSame($bar, $helpers->get('bar')); + } + + public static function getFoo() + { + echo 'foo'; + } + + public function testAccessorsAndMutators() + { + $foo = array($this, 'getFoo'); + $bar = 'BAR'; + + $helpers = new Mustache_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 = array($this, 'getFoo'); + $bar = 'BAR'; + + $helpers = new Mustache_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 Mustache_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/Loader/ArrayLoaderTest.php b/test/Mustache/Test/Loader/ArrayLoaderTest.php new file mode 100644 index 0000000..63d1a96 --- /dev/null +++ b/test/Mustache/Test/Loader/ArrayLoaderTest.php @@ -0,0 +1,52 @@ + '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->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'); + } +} diff --git a/test/Mustache/Test/Loader/FilesystemLoaderTest.php b/test/Mustache/Test/Loader/FilesystemLoaderTest.php new file mode 100644 index 0000000..f0f0997 --- /dev/null +++ b/test/Mustache/Test/Loader/FilesystemLoaderTest.php @@ -0,0 +1,51 @@ + '.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')); + } + + /** + * @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); + + $loader->load('fake'); + } +} diff --git a/test/Mustache/Test/Loader/StringLoaderTest.php b/test/Mustache/Test/Loader/StringLoaderTest.php new file mode 100644 index 0000000..abda71a --- /dev/null +++ b/test/Mustache/Test/Loader/StringLoaderTest.php @@ -0,0 +1,25 @@ +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 new file mode 100644 index 0000000..5f898d8 --- /dev/null +++ b/test/Mustache/Test/ParserTest.php @@ -0,0 +1,182 @@ +assertEquals($expected, $parser->parse($tokens)); + } + + 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_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' + ), + ), + ), + + ); + } + + /** + * @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, + ), + ), + ), + + // 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, + ), + ), + ), + + // 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 new file mode 100644 index 0000000..a3b14a1 --- /dev/null +++ b/test/Mustache/Test/TemplateTest.php @@ -0,0 +1,55 @@ +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; + + 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'))); + } +} + +class Mustache_Test_TemplateStub extends Mustache_Template +{ + public $rendered; + + public function getMustache() + { + return $this->mustache; + } + + 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 new file mode 100644 index 0000000..3f6d76b --- /dev/null +++ b/test/Mustache/Test/TokenizerTest.php @@ -0,0 +1,144 @@ +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', + ), + ), + ), + + 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 }}', + '<<< >>>', + 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( + "{{{ 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/MustacheCallTest.php b/test/MustacheCallTest.php deleted file mode 100644 index 366d2c4..0000000 --- a/test/MustacheCallTest.php +++ /dev/null @@ -1,24 +0,0 @@ -name = 'Bob'; - - $template = '{{# foo }}{{ label }}: {{ name }}{{/ foo }}'; - $data = array('label' => 'name', 'foo' => $foo); - $m = new Mustache($template, $data); - - $this->assertEquals('name: Bob', $m->render()); - } -} - -class ClassWithCall { - public $name; - public function __call($method, $args) { - return 'unknown value'; - } -} diff --git a/test/MustacheExceptionTest.php b/test/MustacheExceptionTest.php deleted file mode 100644 index 2a40223..0000000 --- a/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/MustacheHigherOrderSectionsTest.php b/test/MustacheHigherOrderSectionsTest.php deleted file mode 100644 index 87e4142..0000000 --- a/test/MustacheHigherOrderSectionsTest.php +++ /dev/null @@ -1,114 +0,0 @@ -foo = new Foo(); - } - - 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; - } - - $this->foo->wrapper = function($text) { - return sprintf('
%s
', $text); - }; - - $this->assertEquals( - sprintf('
%s
', $this->foo->name), - $this->foo->render('{{#wrapper}}{{name}}{{/wrapper}}') - ); - } - - 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}}')); - } - - 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}}') - ); - } - - public function testStaticSectionCallback() { - $this->foo->trimmer = array(get_class($this->foo), 'staticTrim'); - $this->assertEquals($this->foo->name, $this->foo->render('{{#trimmer}} {{name}} {{/trimmer}}')); - } - - public function testViewArraySectionCallback() { - $data = array( - 'name' => 'Bob', - 'trim' => array(get_class($this->foo), 'staticTrim'), - ); - $this->assertEquals($data['name'], $this->foo->render('{{#trim}} {{name}} {{/trim}}', $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; - } - $data = array( - 'name' => 'Bob', - 'wrap' => function($text) { - return sprintf('[[%s]]', $text); - } - ); - $this->assertEquals( - sprintf('[[%s]]', $data['name']), - $this->foo->render('{{#wrap}}{{name}}{{/wrap}}', $data) - ); - } - - public function testMonsters() { - $frank = new Monster(); - $frank->title = 'Dr.'; - $frank->name = 'Frankenstein'; - $this->assertEquals('Dr. Frankenstein', $frank->render()); - - $dracula = new Monster(); - $dracula->title = 'Count'; - $dracula->name = 'Dracula'; - $this->assertEquals('Count Dracula', $dracula->render()); - } -} - -class Foo extends Mustache { - 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 wrapWithEm($text) { - return sprintf('%s', $text); - } - - public function wrapWithStrong($text) { - return sprintf('%s', $text); - } - - public function wrapWithBoth($text) { - return self::wrapWithStrong(self::wrapWithEm($text)); - } - - public static function staticTrim($text) { - return trim($text); - } -} - -class Monster extends Mustache { - public $_template = '{{#title}}{{title}} {{/title}}{{name}}'; - public $title; - public $name; -} \ No newline at end of file diff --git a/test/MustacheInjectionTest.php b/test/MustacheInjectionTest.php deleted file mode 100644 index de74943..0000000 --- a/test/MustacheInjectionTest.php +++ /dev/null @@ -1,127 +0,0 @@ - '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{ a }}'; - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } - - public function testUnescapedInterpolationInjection() { - $data = array( - 'a' => '{{ b }}', - 'b' => 'FAIL' - ); - $template = '{{{ a }}}'; - $output = '{{ b }}'; - $m = new Mustache(); - $this->assertEquals($output, $m->render($template, $data)); - } - - - // 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 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)); - } - - - // 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 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)); - } - - - // 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 interpolationLambda() { - return '{{ b }}'; - } - - 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)); - } - - public function sectionLambda($content) { - return '{{ ' . $content . ' }}'; - } - -} \ No newline at end of file diff --git a/test/MustacheLoaderTest.php b/test/MustacheLoaderTest.php deleted file mode 100644 index 2674a0f..0000000 --- a/test/MustacheLoaderTest.php +++ /dev/null @@ -1,60 +0,0 @@ -assertEquals(file_get_contents(dirname(__FILE__).'/fixtures/foo.mustache'), $loader['foo']); - $this->assertEquals(file_get_contents(dirname(__FILE__).'/fixtures/bar.mustache'), $loader['bar']); - } - - 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 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)); - } -} - -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/MustacheObjectSectionTest.php b/test/MustacheObjectSectionTest.php deleted file mode 100644 index 82405d6..0000000 --- a/test/MustacheObjectSectionTest.php +++ /dev/null @@ -1,73 +0,0 @@ -assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); - } - - public function testObjectWithGet() { - $beta = new Beta(); - $this->assertEquals('Foo', $beta->render('{{#foo}}{{name}}{{/foo}}')); - } - - public function testSectionObjectWithGet() { - $gamma = new Gamma(); - $this->assertEquals('Foo', $gamma->render('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}')); - } - - public function testSectionObjectWithFunction() { - $alpha = new Alpha(); - $alpha->foo = new Delta(); - $this->assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); - } -} - -class Alpha extends Mustache { - public $foo; - - public function __construct() { - $this->foo = new StdClass(); - $this->foo->name = 'Foo'; - $this->foo->number = 1; - } -} - -class Beta extends Mustache { - protected $_data = array(); - - 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 __get($name) { - return $this->_data[$name]; - } -} - -class Gamma extends Mustache { - public $bar; - - public function __construct() { - $this->bar = new Beta(); - } -} - -class Delta extends Mustache { - protected $_name = 'Foo'; - - public function name() { - return $this->_name; - } -} \ No newline at end of file diff --git a/test/MustachePragmaTest.php b/test/MustachePragmaTest.php deleted file mode 100644 index c00441c..0000000 --- a/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/MustachePragmaUnescapedTest.php b/test/MustachePragmaUnescapedTest.php deleted file mode 100644 index df6d94c..0000000 --- a/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/MustacheSpecTest.php b/test/MustacheSpecTest.php deleted file mode 100644 index d3a3413..0000000 --- a/test/MustacheSpecTest.php +++ /dev/null @@ -1,174 +0,0 @@ -markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); - } - } - - /** - * @group comments - * @dataProvider loadCommentSpec - */ - public function testCommentSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - /** - * @group delimiters - * @dataProvider loadDelimitersSpec - */ - public function testDelimitersSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - /** - * @group interpolation - * @dataProvider loadInterpolationSpec - */ - public function testInterpolationSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - /** - * @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); - } - - /** - * @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.'); - } - - $data = $this->prepareLambdasSpec($data); - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - /** - * Extract and lambdafy any 'lambda' values found in the $data array. - */ - protected 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 - */ - public function testPartialsSpec($desc, $template, $data, $partials, $expected) { - $m = new Mustache($template, $data, $partials); - $this->assertEquals($expected, $m->render(), $desc); - } - - /** - * @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 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 - */ - protected function loadSpec($name) { - $filename = dirname(__FILE__) . '/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'], - $test['data'], - isset($test['partials']) ? $test['partials'] : array(), - $test['expected'], - ); - } - return $data; - } -} \ No newline at end of file diff --git a/test/MustacheTest.php b/test/MustacheTest.php deleted file mode 100644 index 0c0bb13..0000000 --- a/test/MustacheTest.php +++ /dev/null @@ -1,464 +0,0 @@ - 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'); - } - } - - /** - * 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); - } - } - - $files->next(); - } - return $ret; - } - - /** - * @group delimiters - */ - 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 \\\\')); - } - - /** - * @group delimiters - */ - 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 %>')); - } - - /** - * @group delimiters - */ - 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}}')); - } - - /** - * @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()); - } -} - -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); - } -} diff --git a/test/bootstrap.php b/test/bootstrap.php new file mode 100644 index 0000000..91f654a --- /dev/null +++ b/test/bootstrap.php @@ -0,0 +1,15 @@ + 'child works', + ); + + public $grandparent = array( + 'parent' => array( + 'child' => 'grandchild works', + ), + ); +} 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/test/fixtures/examples/comments/Comments.php b/test/fixtures/examples/comments/Comments.php new file mode 100644 index 0000000..afabd22 --- /dev/null +++ b/test/fixtures/examples/comments/Comments.php @@ -0,0 +1,9 @@ + '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 isEmpty() + { + return count($this->item) === 0; + } +} 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/test/fixtures/examples/delimiters/Delimiters.php b/test/fixtures/examples/delimiters/Delimiters.php new file mode 100644 index 0000000..6f03557 --- /dev/null +++ b/test/fixtures/examples/delimiters/Delimiters.php @@ -0,0 +1,16 @@ + "And it worked the second time."), + array('item' => "As well as the third."), + ); + } + + public $final = "Then, surprisingly, it worked the final time."; +} 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/test/fixtures/examples/dot_notation/DotNotation.php b/test/fixtures/examples/dot_notation/DotNotation.php new file mode 100644 index 0000000..d2939f1 --- /dev/null +++ b/test/fixtures/examples/dot_notation/DotNotation.php @@ -0,0 +1,15 @@ + array('first' => 'Chris', 'last' => 'Firescythe'), + 'age' => 24, + 'hometown' => array( + 'city' => 'Cincinnati', + 'state' => 'OH', + ) + ); + + public $normal = 'Normal'; +} diff --git a/examples/dot_notation/dot_notation.mustache b/test/fixtures/examples/dot_notation/dot_notation.mustache similarity index 66% rename from examples/dot_notation/dot_notation.mustache rename to test/fixtures/examples/dot_notation/dot_notation.mustache index 0135a2a..0566867 100644 --- a/examples/dot_notation/dot_notation.mustache +++ b/test/fixtures/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/test/fixtures/examples/dot_notation/dot_notation.txt similarity index 59% rename from examples/dot_notation/dot_notation.txt rename to test/fixtures/examples/dot_notation/dot_notation.txt index e5c1ed9..f8cf1fa 100644 --- a/examples/dot_notation/dot_notation.txt +++ b/test/fixtures/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/test/fixtures/examples/double_section/DoubleSection.php b/test/fixtures/examples/double_section/DoubleSection.php new file mode 100644 index 0000000..8860181 --- /dev/null +++ b/test/fixtures/examples/double_section/DoubleSection.php @@ -0,0 +1,11 @@ + "Shark"'; +} 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/test/fixtures/examples/grand_parent_context/GrandParentContext.php b/test/fixtures/examples/grand_parent_context/GrandParentContext.php new file mode 100644 index 0000000..ce218fb --- /dev/null +++ b/test/fixtures/examples/grand_parent_context/GrandParentContext.php @@ -0,0 +1,24 @@ +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; + } +} 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 85% rename from examples/i18n/I18n.php rename to test/fixtures/examples/i18n/I18n.php index 7e0fcce..7b7cd9f 100644 --- a/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/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/test/fixtures/examples/implicit_iterator/ImplicitIterator.php b/test/fixtures/examples/implicit_iterator/ImplicitIterator.php new file mode 100644 index 0000000..6cb7644 --- /dev/null +++ b/test/fixtures/examples/implicit_iterator/ImplicitIterator.php @@ -0,0 +1,6 @@ +{{name}} +{{/repo}} +{{^repo}} + No repos :( +{{/repo}} \ No newline at end of file diff --git a/test/fixtures/examples/inverted_section/inverted_section.txt b/test/fixtures/examples/inverted_section/inverted_section.txt new file mode 100644 index 0000000..6ba5a99 --- /dev/null +++ b/test/fixtures/examples/inverted_section/inverted_section.txt @@ -0,0 +1 @@ + No repos :( diff --git a/test/fixtures/examples/partials/Partials.php b/test/fixtures/examples/partials/Partials.php new file mode 100644 index 0000000..f15d6b2 --- /dev/null +++ b/test/fixtures/examples/partials/Partials.php @@ -0,0 +1,9 @@ + 'Page Title', + 'subtitle' => 'Page Subtitle', + 'content' => 'Lorem ipsum dolor sit amet.', + ); +} diff --git a/test/fixtures/examples/partials/partials.mustache b/test/fixtures/examples/partials/partials.mustache new file mode 100644 index 0000000..54cf1c5 --- /dev/null +++ b/test/fixtures/examples/partials/partials.mustache @@ -0,0 +1,7 @@ +
+ {{> header }} + +
+ {{ page.content }} +
+
\ No newline at end of file diff --git a/test/fixtures/examples/partials/partials.txt b/test/fixtures/examples/partials/partials.txt new file mode 100644 index 0000000..f8e45ce --- /dev/null +++ b/test/fixtures/examples/partials/partials.txt @@ -0,0 +1,8 @@ +
+

Page Title

+

Page Subtitle

+ +
+ Lorem ipsum dolor sit amet. +
+
\ No newline at end of file diff --git a/test/fixtures/examples/partials/partials/header.mustache b/test/fixtures/examples/partials/partials/header.mustache new file mode 100644 index 0000000..88d567b --- /dev/null +++ b/test/fixtures/examples/partials/partials/header.mustache @@ -0,0 +1,4 @@ +{{# page }} +

{{ title }}

+

{{ subtitle }}

+{{/ page }} \ No newline at end of file diff --git a/test/fixtures/examples/recursive_partials/RecursivePartials.php b/test/fixtures/examples/recursive_partials/RecursivePartials.php new file mode 100644 index 0000000..092a53d --- /dev/null +++ b/test/fixtures/examples/recursive_partials/RecursivePartials.php @@ -0,0 +1,13 @@ + 'Dan', + 'child' => array( + 'name' => 'Justin', + 'child' => false, + ) + ); +} diff --git a/test/fixtures/examples/recursive_partials/partials/child.mustache b/test/fixtures/examples/recursive_partials/partials/child.mustache new file mode 100644 index 0000000..1282941 --- /dev/null +++ b/test/fixtures/examples/recursive_partials/partials/child.mustache @@ -0,0 +1 @@ + > {{ name }}{{#child}}{{>child}}{{/child}} \ No newline at end of file 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/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php b/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php new file mode 100644 index 0000000..3415ed5 --- /dev/null +++ b/test/fixtures/examples/section_iterator_objects/SectionIteratorObjects.php @@ -0,0 +1,18 @@ + 'And it worked the second time.'), + array('item' => 'As well as the third.'), + ); + + public function middle() + { + return new ArrayIterator($this->_data); + } + + public $final = "Then, surprisingly, it worked the final time."; +} 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/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php b/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php new file mode 100644 index 0000000..c03e228 --- /dev/null +++ b/test/fixtures/examples/section_magic_objects/SectionMagicObjects.php @@ -0,0 +1,31 @@ + '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 __isset($key) + { + return isset($this->_data[$key]); + } +} 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/test/fixtures/examples/section_objects/SectionObjects.php b/test/fixtures/examples/section_objects/SectionObjects.php new file mode 100644 index 0000000..e6a6b16 --- /dev/null +++ b/test/fixtures/examples/section_objects/SectionObjects.php @@ -0,0 +1,19 @@ + "And it worked the second time."), + array('item' => "As well as the third."), + ); + } + + public $final = "Then, surprisingly, it worked the final time."; +} 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/test/fixtures/examples/sections_nested/SectionsNested.php b/test/fixtures/examples/sections_nested/SectionsNested.php new file mode 100644 index 0000000..9360505 --- /dev/null +++ b/test/fixtures/examples/sections_nested/SectionsNested.php @@ -0,0 +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'), + ) + ), + ); + } +} 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/test/fixtures/examples/simple/Simple.php b/test/fixtures/examples/simple/Simple.php new file mode 100644 index 0000000..f097ff2 --- /dev/null +++ b/test/fixtures/examples/simple/Simple.php @@ -0,0 +1,14 @@ +value - ($this->value * 0.4); + } + + public $in_ca = true; +}; 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/test/fixtures/examples/unescaped/Unescaped.php b/test/fixtures/examples/unescaped/Unescaped.php new file mode 100644 index 0000000..282ba21 --- /dev/null +++ b/test/fixtures/examples/unescaped/Unescaped.php @@ -0,0 +1,6 @@ + Shark"; +} 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/test/fixtures/examples/utf8/UTF8.php b/test/fixtures/examples/utf8/UTF8.php new file mode 100644 index 0000000..e5a7877 --- /dev/null +++ b/test/fixtures/examples/utf8/UTF8.php @@ -0,0 +1,6 @@ + tag }}` and `{{> tag}}` and `{{>tag}}` should all be equivalent. + */ +class Whitespace +{ + public $foo = 'alpha'; + + public $bar = 'beta'; + + 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'), + ); + } +} diff --git a/test/fixtures/examples/whitespace/partials/alphabet.mustache b/test/fixtures/examples/whitespace/partials/alphabet.mustache new file mode 100644 index 0000000..d281c41 --- /dev/null +++ b/test/fixtures/examples/whitespace/partials/alphabet.mustache @@ -0,0 +1 @@ + * {{.}} \ No newline at end of file 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 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 diff --git a/test/fixtures/templates/alpha.ms b/test/fixtures/templates/alpha.ms new file mode 100644 index 0000000..3845830 --- /dev/null +++ b/test/fixtures/templates/alpha.ms @@ -0,0 +1 @@ +alpha contents \ No newline at end of file diff --git a/test/fixtures/templates/beta.ms b/test/fixtures/templates/beta.ms new file mode 100644 index 0000000..a083dfe --- /dev/null +++ b/test/fixtures/templates/beta.ms @@ -0,0 +1 @@ +beta contents \ No newline at end of file diff --git a/test/fixtures/templates/one.mustache b/test/fixtures/templates/one.mustache new file mode 100644 index 0000000..f83ad09 --- /dev/null +++ b/test/fixtures/templates/one.mustache @@ -0,0 +1 @@ +one contents \ No newline at end of file diff --git a/test/fixtures/templates/two.mustache b/test/fixtures/templates/two.mustache new file mode 100644 index 0000000..dacc40e --- /dev/null +++ b/test/fixtures/templates/two.mustache @@ -0,0 +1 @@ +two contents \ No newline at end of file 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/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 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