├── examples ├── utf8 │ ├── utf8.txt │ ├── utf8.mustache │ └── UTF8.php ├── escaped │ ├── escaped.mustache │ ├── escaped.txt │ └── Escaped.php ├── unescaped │ ├── unescaped.txt │ ├── unescaped.mustache │ └── Unescaped.php ├── comments │ ├── comments.txt │ ├── comments.mustache │ └── Comments.php ├── inverted_section │ ├── inverted_section.txt │ ├── inverted_section.mustache │ └── InvertedSection.php ├── utf8_unescaped │ ├── utf8_unescaped.txt │ ├── utf8_unescaped.mustache │ └── UTF8Unescaped.php ├── recursive_partials │ ├── recursive_partials.txt │ ├── recursive_partials.mustache │ └── RecursivePartials.php ├── partials │ ├── partials.mustache │ ├── partials.txt │ └── Partials.php ├── pragma_unescaped │ ├── pragma_unescaped.txt │ ├── pragma_unescaped.mustache │ └── PragmaUnescaped.php ├── double_section │ ├── double_section.txt │ ├── double_section.mustache │ └── DoubleSection.php ├── pragmas_in_partials │ ├── pragmas_in_partials.txt │ ├── pragmas_in_partials.mustache │ └── PragmasInPartials.php ├── implicit_iterator │ ├── implicit_iterator.mustache │ ├── implicit_iterator.txt │ └── ImplicitIterator.php ├── child_context │ ├── child_context.txt │ ├── child_context.mustache │ └── ChildContext.php ├── inverted_double_section │ ├── inverted_double_section.txt │ ├── inverted_double_section.mustache │ └── InvertedDoubleSection.php ├── dot_notation │ ├── dot_notation.txt │ ├── dot_notation.mustache │ └── DotNotation.php ├── simple │ ├── simple.txt │ ├── simple.mustache │ └── Simple.php ├── partials_with_view_class │ ├── partials_with_view_class.mustache │ ├── partials_with_view_class.txt │ └── PartialsWithViewClass.php ├── sections │ ├── sections.mustache │ ├── sections.txt │ └── Sections.php ├── section_objects │ ├── section_objects.mustache │ ├── section_objects.txt │ └── SectionObjects.php ├── section_iterator_objects │ ├── section_iterator_objects.mustache │ ├── section_iterator_objects.txt │ └── SectionIteratorObjects.php ├── delimiters │ ├── delimiters.mustache │ ├── delimiters.txt │ └── Delimiters.php ├── section_magic_objects │ ├── section_magic_objects.mustache │ ├── section_magic_objects.txt │ └── SectionMagicObjects.php ├── whitespace │ ├── whitespace.txt │ ├── whitespace.mustache │ └── Whitespace.php ├── complex │ ├── complex.txt │ ├── complex.mustache │ └── complex.php ├── sections_nested │ ├── sections_nested.mustache │ ├── sections_nested.txt │ └── SectionsNested.php └── grand_parent_context │ ├── grand_parent_context.mustache │ ├── grand_parent_context.txt │ └── GrandParentContext.php ├── .gitmodules ├── test ├── phpunit.xml ├── MustachePragmaUnescapedTest.php ├── lib │ └── yaml │ │ ├── README.markdown │ │ ├── LICENSE │ │ ├── lib │ │ ├── sfYamlDumper.php │ │ ├── sfYaml.php │ │ ├── sfYamlInline.php │ │ └── sfYamlParser.php │ │ ├── doc │ │ ├── 01-Usage.markdown │ │ ├── 00-Introduction.markdown │ │ ├── 02-YAML.markdown │ │ └── A-License.markdown │ │ └── package.xml ├── MustacheObjectSectionTest.php ├── MustachePragmaTest.php ├── MustacheExceptionTest.php ├── MustacheSpecTest.php └── MustacheTest.php ├── LICENSE ├── README.markdown └── Mustache.php /examples/utf8/utf8.txt: -------------------------------------------------------------------------------- 1 |

中文 中文又来啦

-------------------------------------------------------------------------------- /examples/utf8/utf8.mustache: -------------------------------------------------------------------------------- 1 |

中文 {{test}}

-------------------------------------------------------------------------------- /examples/escaped/escaped.mustache: -------------------------------------------------------------------------------- 1 |

{{title}}

-------------------------------------------------------------------------------- /examples/unescaped/unescaped.txt: -------------------------------------------------------------------------------- 1 |

Bear > Shark

-------------------------------------------------------------------------------- /examples/comments/comments.txt: -------------------------------------------------------------------------------- 1 |

A Comedy of Errors

-------------------------------------------------------------------------------- /examples/inverted_section/inverted_section.txt: -------------------------------------------------------------------------------- 1 | No repos :( -------------------------------------------------------------------------------- /examples/unescaped/unescaped.mustache: -------------------------------------------------------------------------------- 1 |

{{{title}}}

-------------------------------------------------------------------------------- /examples/utf8_unescaped/utf8_unescaped.txt: -------------------------------------------------------------------------------- 1 |

中文 中文又来啦

-------------------------------------------------------------------------------- /examples/recursive_partials/recursive_partials.txt: -------------------------------------------------------------------------------- 1 | George > Dan > Justin -------------------------------------------------------------------------------- /examples/utf8_unescaped/utf8_unescaped.mustache: -------------------------------------------------------------------------------- 1 |

中文 {{{test}}}

-------------------------------------------------------------------------------- /examples/escaped/escaped.txt: -------------------------------------------------------------------------------- 1 |

"Bear" > "Shark"

-------------------------------------------------------------------------------- /examples/partials/partials.mustache: -------------------------------------------------------------------------------- 1 | Children of {{name}}: 2 | {{>children}} -------------------------------------------------------------------------------- /examples/pragma_unescaped/pragma_unescaped.txt: -------------------------------------------------------------------------------- 1 | Bear > Shark 2 | Bear > Shark -------------------------------------------------------------------------------- /examples/double_section/double_section.txt: -------------------------------------------------------------------------------- 1 | * first 2 | * second 3 | * third 4 | -------------------------------------------------------------------------------- /examples/pragmas_in_partials/pragmas_in_partials.txt: -------------------------------------------------------------------------------- 1 | < RAWR!! > 2 | < RAWR!! > -------------------------------------------------------------------------------- /examples/implicit_iterator/implicit_iterator.mustache: -------------------------------------------------------------------------------- 1 | {{#data}} 2 | * {{.}} 3 | {{/data}} -------------------------------------------------------------------------------- /examples/child_context/child_context.txt: -------------------------------------------------------------------------------- 1 |

child works

2 |

grandchild works

-------------------------------------------------------------------------------- /examples/pragma_unescaped/pragma_unescaped.mustache: -------------------------------------------------------------------------------- 1 | {{%UNESCAPED}} 2 | {{vs}} 3 | {{{vs}}} -------------------------------------------------------------------------------- /examples/recursive_partials/recursive_partials.mustache: -------------------------------------------------------------------------------- 1 | {{name}}{{#child}}{{>child}}{{/child}} -------------------------------------------------------------------------------- /examples/inverted_double_section/inverted_double_section.txt: -------------------------------------------------------------------------------- 1 | * first 2 | * second 3 | * third 4 | -------------------------------------------------------------------------------- /examples/comments/comments.mustache: -------------------------------------------------------------------------------- 1 |

{{title}}{{! just something interesting... #or ^not... }}

-------------------------------------------------------------------------------- /examples/dot_notation/dot_notation.txt: -------------------------------------------------------------------------------- 1 | * Chris Firescythe 2 | * 24 3 | * Cincinnati, OH 4 | * Normal -------------------------------------------------------------------------------- /examples/partials/partials.txt: -------------------------------------------------------------------------------- 1 | Children of ilmich: 2 | federica - 27 - female 3 | marco - 32 - male 4 | -------------------------------------------------------------------------------- /examples/pragmas_in_partials/pragmas_in_partials.mustache: -------------------------------------------------------------------------------- 1 | {{%UNESCAPED}} 2 | {{say}} 3 | {{>dinosaur}} -------------------------------------------------------------------------------- /examples/simple/simple.txt: -------------------------------------------------------------------------------- 1 | Hello Chris 2 | You have just won $10000! 3 | Well, $6000, after taxes. 4 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "test/spec"] 2 | path = test/spec 3 | url = http://github.com/mustache/spec.git 4 | -------------------------------------------------------------------------------- /examples/partials_with_view_class/partials_with_view_class.mustache: -------------------------------------------------------------------------------- 1 | Children of {{name}}: 2 | {{>children}} -------------------------------------------------------------------------------- /examples/utf8/UTF8.php: -------------------------------------------------------------------------------- 1 | {{name}}{{/repo}} 2 | {{^repo}}No repos :({{/repo}} -------------------------------------------------------------------------------- /examples/escaped/Escaped.php: -------------------------------------------------------------------------------- 1 | "Shark"'; 5 | } -------------------------------------------------------------------------------- /examples/sections/sections.mustache: -------------------------------------------------------------------------------- 1 | * {{ start }} 2 | {{# middle }} 3 | * {{ item }} 4 | {{/ middle }} 5 | * {{ final }} -------------------------------------------------------------------------------- /examples/utf8_unescaped/UTF8Unescaped.php: -------------------------------------------------------------------------------- 1 | Shark"; 5 | } -------------------------------------------------------------------------------- /examples/inverted_section/InvertedSection.php: -------------------------------------------------------------------------------- 1 | Shark'; 5 | } -------------------------------------------------------------------------------- /examples/section_objects/section_objects.mustache: -------------------------------------------------------------------------------- 1 | * {{ start }} 2 | {{# middle }} 3 | * {{ foo }} 4 | * {{ bar }} 5 | {{/ middle }} 6 | * {{ final }} -------------------------------------------------------------------------------- /examples/section_iterator_objects/section_iterator_objects.mustache: -------------------------------------------------------------------------------- 1 | * {{ start }} 2 | {{# middle }} 3 | * {{ item }} 4 | {{/ middle }} 5 | * {{ final }} -------------------------------------------------------------------------------- /examples/simple/simple.mustache: -------------------------------------------------------------------------------- 1 | Hello {{name}} 2 | You have just won ${{value}}! 3 | {{#in_ca}} 4 | Well, ${{ taxed_value }}, after taxes. 5 | {{/in_ca}} -------------------------------------------------------------------------------- /examples/comments/Comments.php: -------------------------------------------------------------------------------- 1 | {{#parent}}{{child}}{{/parent}} 2 |

{{#grandparent}}{{#parent}}{{child}}{{/parent}}{{/grandparent}}

-------------------------------------------------------------------------------- /examples/delimiters/delimiters.mustache: -------------------------------------------------------------------------------- 1 | {{=<% %>=}} 2 | * <% start %> 3 | <%=| |=%> 4 | |# middle | 5 | * | item | 6 | |/ middle | 7 | |={{ }}=| 8 | * {{ final }} -------------------------------------------------------------------------------- /examples/section_magic_objects/section_magic_objects.mustache: -------------------------------------------------------------------------------- 1 | * {{ start }} 2 | {{# middle }} 3 | * {{ foo }} 4 | * {{ bar }} 5 | {{/ middle }} 6 | * {{ final }} -------------------------------------------------------------------------------- /examples/whitespace/whitespace.txt: -------------------------------------------------------------------------------- 1 | These are some things: 2 | * alpha 3 | * beta 4 | * gamma 5 | * A 6 | * B 7 | * C 8 | * D 9 | * E 10 | * F 11 | * G 12 | ....... -------------------------------------------------------------------------------- /examples/delimiters/delimiters.txt: -------------------------------------------------------------------------------- 1 | * It worked the first time. 2 | * And it worked the second time. 3 | * As well as the third. 4 | * Then, surprisingly, it worked the final time. -------------------------------------------------------------------------------- /examples/inverted_double_section/InvertedDoubleSection.php: -------------------------------------------------------------------------------- 1 | Colors 2 | 7 | -------------------------------------------------------------------------------- /examples/implicit_iterator/ImplicitIterator.php: -------------------------------------------------------------------------------- 1 | {{ name }} 6 | {{/ enemies }} 7 | {{/ enemies }} -------------------------------------------------------------------------------- /examples/pragmas_in_partials/PragmasInPartials.php: -------------------------------------------------------------------------------- 1 | '; 5 | protected $_partials = array( 6 | 'dinosaur' => '{{say}}' 7 | ); 8 | } -------------------------------------------------------------------------------- /examples/whitespace/whitespace.mustache: -------------------------------------------------------------------------------- 1 | {{^ inverted section test }} 2 | These are some things: 3 | {{/inverted section test }} 4 | * {{ foo }} 5 | * {{ bar}} 6 | * {{ baz }} 7 | {{# qux }} 8 | * {{ key with space }} 9 | {{/ qux }} 10 | {{#qux}}.{{/qux}} -------------------------------------------------------------------------------- /examples/simple/Simple.php: -------------------------------------------------------------------------------- 1 | value - ($this->value * 0.4); 9 | } 10 | 11 | public $in_ca = true; 12 | }; -------------------------------------------------------------------------------- /examples/grand_parent_context/grand_parent_context.mustache: -------------------------------------------------------------------------------- 1 | {{grand_parent_id}} 2 | {{#parent_contexts}} 3 | {{parent_id}} ({{grand_parent_id}}) 4 | {{#child_contexts}} 5 | {{child_id}} ({{parent_id}} << {{grand_parent_id}}) 6 | {{/child_contexts}} 7 | {{/parent_contexts}} 8 | -------------------------------------------------------------------------------- /examples/child_context/ChildContext.php: -------------------------------------------------------------------------------- 1 | 'child works', 6 | ); 7 | 8 | public $grandparent = array( 9 | 'parent' => array( 10 | 'child' => 'grandchild works', 11 | ), 12 | ); 13 | } -------------------------------------------------------------------------------- /test/phpunit.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | ./ 5 | 6 | 7 | ../examples 8 | ./ 9 | 10 | -------------------------------------------------------------------------------- /examples/grand_parent_context/grand_parent_context.txt: -------------------------------------------------------------------------------- 1 | grand_parent1 2 | parent1 (grand_parent1) 3 | parent1-child1 (parent1 << grand_parent1) 4 | parent1-child2 (parent1 << grand_parent1) 5 | parent2 (grand_parent1) 6 | parent2-child1 (parent2 << grand_parent1) 7 | parent2-child2 (parent2 << grand_parent1) 8 | -------------------------------------------------------------------------------- /examples/sections_nested/sections_nested.txt: -------------------------------------------------------------------------------- 1 | Enemies of Little Mac: 2 | Von Kaiser ... who also has enemies: 3 | --> Super Macho Man 4 | --> Piston Honda 5 | --> Mr. Sandman 6 | Mike Tyson ... who also has enemies: 7 | --> Soda Popinski 8 | --> King Hippo 9 | --> Great Tiger 10 | --> Glass Joe 11 | Don Flamenco ... who also has enemies: 12 | --> Bald Bull 13 | -------------------------------------------------------------------------------- /examples/complex/complex.mustache: -------------------------------------------------------------------------------- 1 |

{{header}}

2 | {{#notEmpty}} 3 | 13 | {{/notEmpty}} 14 | {{#isEmpty}} 15 |

The list is empty.

16 | {{/isEmpty}} -------------------------------------------------------------------------------- /examples/sections/Sections.php: -------------------------------------------------------------------------------- 1 | "And it worked the second time."), 9 | array('item' => "As well as the third."), 10 | ); 11 | } 12 | 13 | public $final = "Then, surprisingly, it worked the final time."; 14 | } -------------------------------------------------------------------------------- /examples/delimiters/Delimiters.php: -------------------------------------------------------------------------------- 1 | "And it worked the second time."), 9 | array('item' => "As well as the third."), 10 | ); 11 | } 12 | 13 | public $final = "Then, surprisingly, it worked the final time."; 14 | } -------------------------------------------------------------------------------- /examples/recursive_partials/RecursivePartials.php: -------------------------------------------------------------------------------- 1 | " > {{ name }}{{#child}}{{>child}}{{/child}}", 6 | ); 7 | 8 | public $name = 'George'; 9 | public $child = array( 10 | 'name' => 'Dan', 11 | 'child' => array( 12 | 'name' => 'Justin', 13 | 'child' => false, 14 | ) 15 | ); 16 | } -------------------------------------------------------------------------------- /examples/partials/Partials.php: -------------------------------------------------------------------------------- 1 | 'federica', 'age' => 27, 'gender' => 'female'), 7 | array('name' => 'marco', 'age' => 32, 'gender' => 'male'), 8 | ); 9 | 10 | protected $_partials = array( 11 | 'children' => "{{#data}}{{name}} - {{age}} - {{gender}}\n{{/data}}", 12 | ); 13 | } -------------------------------------------------------------------------------- /examples/section_objects/SectionObjects.php: -------------------------------------------------------------------------------- 1 | array('first' => 'Chris', 'last' => 'Firescythe'), 11 | 'age' => 24, 12 | 'hometown' => array( 13 | 'city' => 'Cincinnati', 14 | 'state' => 'OH', 15 | ) 16 | ); 17 | 18 | public $normal = 'Normal'; 19 | } 20 | -------------------------------------------------------------------------------- /examples/section_iterator_objects/SectionIteratorObjects.php: -------------------------------------------------------------------------------- 1 | 'And it worked the second time.'), 8 | array('item' => 'As well as the third.'), 9 | ); 10 | 11 | public function middle() { 12 | return new ArrayIterator($this->_data); 13 | } 14 | 15 | public $final = "Then, surprisingly, it worked the final time."; 16 | } -------------------------------------------------------------------------------- /examples/complex/complex.php: -------------------------------------------------------------------------------- 1 | 'red', 'current' => true, 'url' => '#Red'), 8 | array('name' => 'green', 'current' => false, 'url' => '#Green'), 9 | array('name' => 'blue', 'current' => false, 'url' => '#Blue'), 10 | ); 11 | 12 | public function notEmpty() { 13 | return !($this->isEmpty()); 14 | } 15 | 16 | public function isEmpty() { 17 | return count($this->item) === 0; 18 | } 19 | } -------------------------------------------------------------------------------- /test/MustachePragmaUnescapedTest.php: -------------------------------------------------------------------------------- 1 | 'Bear > Shark')); 12 | 13 | $this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{title}}')); 14 | $this->assertEquals('Bear > Shark', $m->render('{{title}}')); 15 | $this->assertEquals('Bear > Shark', $m->render('{{%UNESCAPED}}{{{title}}}')); 16 | $this->assertEquals('Bear > Shark', $m->render('{{{title}}}')); 17 | } 18 | 19 | } -------------------------------------------------------------------------------- /examples/section_magic_objects/SectionMagicObjects.php: -------------------------------------------------------------------------------- 1 | 'And it worked the second time.', 16 | 'bar' => 'As well as the third.' 17 | ); 18 | 19 | public function __get($key) { 20 | return isset($this->_data[$key]) ? $this->_data[$key] : NULL; 21 | } 22 | 23 | public function __isset($key) { 24 | return isset($this->_data[$key]); 25 | } 26 | } -------------------------------------------------------------------------------- /examples/partials_with_view_class/PartialsWithViewClass.php: -------------------------------------------------------------------------------- 1 | name = 'ilmich'; 8 | $view->data = array( 9 | array('name' => 'federica', 'age' => 27, 'gender' => 'female'), 10 | array('name' => 'marco', 'age' => 32, 'gender' => 'male'), 11 | ); 12 | 13 | $partials = array( 14 | 'children' => "{{#data}}{{name}} - {{age}} - {{gender}}\n{{/data}}", 15 | ); 16 | 17 | parent::__construct($template, $view, $partials); 18 | } 19 | } -------------------------------------------------------------------------------- /examples/grand_parent_context/GrandParentContext.php: -------------------------------------------------------------------------------- 1 | parent_contexts[] = array('parent_id' => 'parent1', 'child_contexts' => array( 11 | array('child_id' => 'parent1-child1'), 12 | array('child_id' => 'parent1-child2') 13 | )); 14 | 15 | $parent2 = new stdClass(); 16 | $parent2->parent_id = 'parent2'; 17 | $parent2->child_contexts = array( 18 | array('child_id' => 'parent2-child1'), 19 | array('child_id' => 'parent2-child2') 20 | ); 21 | 22 | $this->parent_contexts[] = $parent2; 23 | } 24 | } -------------------------------------------------------------------------------- /test/lib/yaml/README.markdown: -------------------------------------------------------------------------------- 1 | Symfony YAML: A PHP library that speaks YAML 2 | ============================================ 3 | 4 | Symfony YAML is a PHP library that parses YAML strings and converts them to 5 | PHP arrays. It can also converts PHP arrays to YAML strings. Its official 6 | website is at http://components.symfony-project.org/yaml/. 7 | 8 | The documentation is to be found in the `doc/` directory. 9 | 10 | Symfony YAML is licensed under the MIT license (see LICENSE file). 11 | 12 | The Symfony YAML library is developed and maintained by the 13 | [symfony](http://www.symfony-project.org/) project team. It has been extracted 14 | from symfony to be used as a standalone library. Symfony YAML is part of the 15 | [symfony components project](http://components.symfony-project.org/). 16 | -------------------------------------------------------------------------------- /examples/sections_nested/SectionsNested.php: -------------------------------------------------------------------------------- 1 | 'Von Kaiser', 10 | 'enemies' => array( 11 | array('name' => 'Super Macho Man'), 12 | array('name' => 'Piston Honda'), 13 | array('name' => 'Mr. Sandman'), 14 | ) 15 | ), 16 | array( 17 | 'name' => 'Mike Tyson', 18 | 'enemies' => array( 19 | array('name' => 'Soda Popinski'), 20 | array('name' => 'King Hippo'), 21 | array('name' => 'Great Tiger'), 22 | array('name' => 'Glass Joe'), 23 | ) 24 | ), 25 | array( 26 | 'name' => 'Don Flamenco', 27 | 'enemies' => array( 28 | array('name' => 'Bald Bull'), 29 | ) 30 | ), 31 | ); 32 | } 33 | } -------------------------------------------------------------------------------- /examples/whitespace/Whitespace.php: -------------------------------------------------------------------------------- 1 | tag }}` and `{{> tag}}` and `{{>tag}}` should all be equivalent. 10 | * 11 | * @extends Mustache 12 | */ 13 | class Whitespace extends Mustache { 14 | public $foo = 'alpha'; 15 | 16 | public $bar = 'beta'; 17 | 18 | public function baz() { 19 | return 'gamma'; 20 | } 21 | 22 | public function qux() { 23 | return array( 24 | array('key with space' => 'A'), 25 | array('key with space' => 'B'), 26 | array('key with space' => 'C'), 27 | array('key with space' => 'D'), 28 | array('key with space' => 'E'), 29 | array('key with space' => 'F'), 30 | array('key with space' => 'G'), 31 | ); 32 | } 33 | 34 | protected $_partials = array( 35 | 'alphabet' => " * {{.}}\n", 36 | ); 37 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2010 Justin Hileman 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /test/lib/yaml/LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2008-2009 Fabien Potencier 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy 4 | of this software and associated documentation files (the "Software"), to deal 5 | in the Software without restriction, including without limitation the rights 6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 7 | copies of the Software, and to permit persons to whom the Software is furnished 8 | to do so, subject to the following conditions: 9 | 10 | The above copyright notice and this permission notice shall be included in all 11 | copies or substantial portions of the Software. 12 | 13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 | THE SOFTWARE. 20 | -------------------------------------------------------------------------------- /test/MustacheObjectSectionTest.php: -------------------------------------------------------------------------------- 1 | assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); 12 | } 13 | 14 | public function testObjectWithGet() { 15 | $beta = new Beta(); 16 | $this->assertEquals('Foo', $beta->render('{{#foo}}{{name}}{{/foo}}')); 17 | } 18 | 19 | public function testSectionObjectWithGet() { 20 | $gamma = new Gamma(); 21 | $this->assertEquals('Foo', $gamma->render('{{#bar}}{{#foo}}{{name}}{{/foo}}{{/bar}}')); 22 | } 23 | 24 | public function testSectionObjectWithFunction() { 25 | $alpha = new Alpha(); 26 | $alpha->foo = new Delta(); 27 | $this->assertEquals('Foo', $alpha->render('{{#foo}}{{name}}{{/foo}}')); 28 | } 29 | } 30 | 31 | class Alpha extends Mustache { 32 | public $foo; 33 | 34 | public function __construct() { 35 | $this->foo = new StdClass(); 36 | $this->foo->name = 'Foo'; 37 | $this->foo->number = 1; 38 | } 39 | } 40 | 41 | class Beta extends Mustache { 42 | protected $_data = array(); 43 | 44 | public function __construct() { 45 | $this->_data['foo'] = new StdClass(); 46 | $this->_data['foo']->name = 'Foo'; 47 | $this->_data['foo']->number = 1; 48 | } 49 | 50 | public function __isset($name) { 51 | return array_key_exists($name, $this->_data); 52 | } 53 | 54 | public function __get($name) { 55 | return $this->_data[$name]; 56 | } 57 | } 58 | 59 | class Gamma extends Mustache { 60 | public $bar; 61 | 62 | public function __construct() { 63 | $this->bar = new Beta(); 64 | } 65 | } 66 | 67 | class Delta extends Mustache { 68 | protected $_name = 'Foo'; 69 | 70 | public function name() { 71 | return $this->_name; 72 | } 73 | } -------------------------------------------------------------------------------- /test/lib/yaml/lib/sfYamlDumper.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | require_once(dirname(__FILE__).'/sfYamlInline.php'); 12 | 13 | /** 14 | * sfYamlDumper dumps PHP variables to YAML strings. 15 | * 16 | * @package symfony 17 | * @subpackage yaml 18 | * @author Fabien Potencier 19 | * @version SVN: $Id: sfYamlDumper.class.php 10575 2008-08-01 13:08:42Z nicolas $ 20 | */ 21 | class sfYamlDumper 22 | { 23 | /** 24 | * Dumps a PHP value to YAML. 25 | * 26 | * @param mixed $input The PHP value 27 | * @param integer $inline The level where you switch to inline YAML 28 | * @param integer $indent The level o indentation indentation (used internally) 29 | * 30 | * @return string The YAML representation of the PHP value 31 | */ 32 | public function dump($input, $inline = 0, $indent = 0) 33 | { 34 | $output = ''; 35 | $prefix = $indent ? str_repeat(' ', $indent) : ''; 36 | 37 | if ($inline <= 0 || !is_array($input) || empty($input)) 38 | { 39 | $output .= $prefix.sfYamlInline::dump($input); 40 | } 41 | else 42 | { 43 | $isAHash = array_keys($input) !== range(0, count($input) - 1); 44 | 45 | foreach ($input as $key => $value) 46 | { 47 | $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); 48 | 49 | $output .= sprintf('%s%s%s%s', 50 | $prefix, 51 | $isAHash ? sfYamlInline::dump($key).':' : '-', 52 | $willBeInlined ? ' ' : "\n", 53 | $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + 2) 54 | ).($willBeInlined ? "\n" : ''); 55 | } 56 | } 57 | 58 | return $output; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /test/MustachePragmaTest.php: -------------------------------------------------------------------------------- 1 | render('{{%I-HAVE-THE-GREATEST-MUSTACHE}}'); 15 | } catch (MustacheException $e) { 16 | $this->assertEquals(MustacheException::UNKNOWN_PRAGMA, $e->getCode(), 'Caught exception code was not MustacheException::UNKNOWN_PRAGMA'); 17 | return; 18 | } 19 | 20 | $this->fail('Mustache should have thrown an unknown pragma exception'); 21 | } 22 | 23 | public function testPragmaReplace() { 24 | $m = new Mustache(); 25 | $this->assertEquals('', $m->render('{{%UNESCAPED}}'), 'Pragma tag not removed'); 26 | } 27 | 28 | public function testPragmaReplaceMultiple() { 29 | $m = new Mustache(); 30 | 31 | $this->assertEquals('', $m->render('{{% UNESCAPED }}'), 'Pragmas should allow whitespace'); 32 | $this->assertEquals('', $m->render('{{% UNESCAPED foo=bar }}'), 'Pragmas should allow whitespace'); 33 | $this->assertEquals('', $m->render("{{%UNESCAPED}}\n{{%UNESCAPED}}"), 'Multiple pragma tags not removed'); 34 | $this->assertEquals(' ', $m->render('{{%UNESCAPED}} {{%UNESCAPED}}'), 'Multiple pragma tags not removed'); 35 | } 36 | 37 | public function testPragmaReplaceNewline() { 38 | $m = new Mustache(); 39 | $this->assertEquals('', $m->render("{{%UNESCAPED}}\n"), 'Trailing newline after pragma tag not removed'); 40 | $this->assertEquals("\n", $m->render("\n{{%UNESCAPED}}\n"), 'Too many newlines removed with pragma tag'); 41 | $this->assertEquals("1\n23", $m->render("1\n2{{%UNESCAPED}}\n3"), 'Wrong newline removed with pragma tag'); 42 | } 43 | 44 | public function testPragmaReset() { 45 | $m = new Mustache('', array('symbol' => '>>>')); 46 | $this->assertEquals('>>>', $m->render('{{{symbol}}}')); 47 | $this->assertEquals('>>>', $m->render('{{%UNESCAPED}}{{symbol}}')); 48 | $this->assertEquals('>>>', $m->render('{{{symbol}}}')); 49 | } 50 | } -------------------------------------------------------------------------------- /README.markdown: -------------------------------------------------------------------------------- 1 | Mustache.php 2 | ============ 3 | 4 | A [Mustache](http://defunkt.github.com/mustache/) implementation in PHP. 5 | 6 | 7 | Usage 8 | ----- 9 | 10 | A quick example: 11 | 12 | render('Hello {{planet}}', array('planet' => 'World!')); 16 | // "Hello World!" 17 | ?> 18 | 19 | 20 | And a more in-depth example--this is the canonical Mustache template: 21 | 22 | Hello {{name}} 23 | You have just won ${{value}}! 24 | {{#in_ca}} 25 | Well, ${{taxed_value}}, after taxes. 26 | {{/in_ca}} 27 | 28 | 29 | Along with the associated Mustache class: 30 | 31 | value - ($this->value * 0.4); 38 | } 39 | 40 | public $in_ca = true; 41 | } 42 | 43 | 44 | Render it like so: 45 | 46 | render($template); 49 | ?> 50 | 51 | 52 | Here's the same thing, a different way: 53 | 54 | Create a view object--which could also be an associative array, but those don't do functions quite as well: 55 | 56 | value - ($this->value * 0.4); 63 | } 64 | 65 | public $in_ca = true; 66 | } 67 | ?> 68 | 69 | 70 | And render it: 71 | 72 | render($template, $chris); 76 | ?> 77 | 78 | 79 | 80 | 81 | Known Issues 82 | ------------ 83 | 84 | * As of Mustache spec v1.1.2, there are a couple of whitespace bugs around section tags... Despite these failing tests, this 85 | version is actually *closer* to correct than previous releases. 86 | 87 | 88 | See Also 89 | -------- 90 | 91 | * [Readme for the Ruby Mustache implementation](http://github.com/defunkt/mustache/blob/master/README.md). 92 | * [mustache(1)](http://mustache.github.com/mustache.1.html) and [mustache(5)](http://mustache.github.com/mustache.5.html) man pages. 93 | -------------------------------------------------------------------------------- /test/lib/yaml/doc/01-Usage.markdown: -------------------------------------------------------------------------------- 1 | Using Symfony YAML 2 | ================== 3 | 4 | The Symfony YAML library is very simple and consists of two main classes: one 5 | to parse YAML strings (`sfYamlParser`), and the other to dump a PHP array to 6 | a YAML string (`sfYamlDumper`). 7 | 8 | On top of these two core classes, the main `sfYaml` class acts as a thin 9 | wrapper and simplifies common uses. 10 | 11 | Reading YAML Files 12 | ------------------ 13 | 14 | The `sfYamlParser::parse()` method parses a YAML string and converts it to a 15 | PHP array: 16 | 17 | [php] 18 | $yaml = new sfYamlParser(); 19 | $value = $yaml->parse(file_get_contents('/path/to/file.yaml')); 20 | 21 | If an error occurs during parsing, the parser throws an exception indicating 22 | the error type and the line in the original YAML string where the error 23 | occurred: 24 | 25 | [php] 26 | try 27 | { 28 | $value = $yaml->parse(file_get_contents('/path/to/file.yaml')); 29 | } 30 | catch (InvalidArgumentException $e) 31 | { 32 | // an error occurred during parsing 33 | echo "Unable to parse the YAML string: ".$e->getMessage(); 34 | } 35 | 36 | >**TIP** 37 | >As the parser is reentrant, you can use the same parser object to load 38 | >different YAML strings. 39 | 40 | When loading a YAML file, it is sometimes better to use the `sfYaml::load()` 41 | wrapper method: 42 | 43 | [php] 44 | $loader = sfYaml::load('/path/to/file.yml'); 45 | 46 | The `sfYaml::load()` static method takes a YAML string or a file containing 47 | YAML. Internally, it calls the `sfYamlParser::parse()` method, but with some 48 | added bonuses: 49 | 50 | * It executes the YAML file as if it was a PHP file, so that you can embed 51 | PHP commands in YAML files; 52 | 53 | * When a file cannot be parsed, it automatically adds the file name to the 54 | error message, simplifying debugging when your application is loading 55 | several YAML files. 56 | 57 | Writing YAML Files 58 | ------------------ 59 | 60 | The `sfYamlDumper` dumps any PHP array to its YAML representation: 61 | 62 | [php] 63 | $array = array('foo' => 'bar', 'bar' => array('foo' => 'bar', 'bar' => 'baz')); 64 | 65 | $dumper = new sfYamlDumper(); 66 | $yaml = $dumper->dump($array); 67 | file_put_contents('/path/to/file.yaml', $yaml); 68 | 69 | >**NOTE** 70 | >Of course, the Symfony YAML dumper is not able to dump resources. Also, 71 | >even if the dumper is able to dump PHP objects, it is to be considered 72 | >an alpha feature. 73 | 74 | If you only need to dump one array, you can use the `sfYaml::dump()` static 75 | method shortcut: 76 | 77 | [php] 78 | $yaml = sfYaml::dump($array, $inline); 79 | 80 | The YAML format supports two kind of representation for arrays, the expanded 81 | one, and the inline one. By default, the dumper uses the inline 82 | representation: 83 | 84 | [yml] 85 | { foo: bar, bar: { foo: bar, bar: baz } } 86 | 87 | The second argument of the `dump()` method customizes the level at which the 88 | output switches from the expanded representation to the inline one: 89 | 90 | [php] 91 | echo $dumper->dump($array, 1); 92 | 93 | - 94 | 95 | [yml] 96 | foo: bar 97 | bar: { foo: bar, bar: baz } 98 | 99 | - 100 | 101 | [php] 102 | echo $dumper->dump($array, 2); 103 | 104 | - 105 | 106 | [yml] 107 | foo: bar 108 | bar: 109 | foo: bar 110 | bar: baz 111 | -------------------------------------------------------------------------------- /test/lib/yaml/package.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | YAML 4 | pear.symfony-project.com 5 | The Symfony YAML Component. 6 | The Symfony YAML Component. 7 | 8 | Fabien Potencier 9 | fabpot 10 | fabien.potencier@symfony-project.org 11 | yes 12 | 13 | 2009-12-01 14 | 15 | 1.0.2 16 | 1.0.0 17 | 18 | 19 | stable 20 | stable 21 | 22 | MIT license 23 | - 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 5.2.4 42 | 43 | 44 | 1.4.1 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 1.0.2 56 | 1.0.0 57 | 58 | 59 | stable 60 | stable 61 | 62 | MIT license 63 | 2009-12-01 64 | MIT 65 | 66 | * fabien: fixed \ usage in quoted string 67 | 68 | 69 | 70 | 71 | 1.0.1 72 | 1.0.0 73 | 74 | 75 | stable 76 | stable 77 | 78 | MIT license 79 | 2009-12-01 80 | MIT 81 | 82 | * fabien: fixed a possible loop in parsing a non-valid quoted string 83 | 84 | 85 | 86 | 87 | 1.0.0 88 | 1.0.0 89 | 90 | 91 | stable 92 | stable 93 | 94 | MIT license 95 | 2009-11-30 96 | MIT 97 | 98 | * fabien: first stable release as a Symfony Component 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /test/MustacheExceptionTest.php: -------------------------------------------------------------------------------- 1 | pickyMustache = new PickyMustache(); 14 | $this->slackerMustache = new SlackerMustache(); 15 | } 16 | 17 | /** 18 | * @group interpolation 19 | * @expectedException MustacheException 20 | */ 21 | public function testThrowsUnknownVariableException() { 22 | $this->pickyMustache->render('{{not_a_variable}}'); 23 | } 24 | 25 | /** 26 | * @group sections 27 | * @expectedException MustacheException 28 | */ 29 | public function testThrowsUnclosedSectionException() { 30 | $this->pickyMustache->render('{{#unclosed}}'); 31 | } 32 | 33 | /** 34 | * @group sections 35 | * @expectedException MustacheException 36 | */ 37 | public function testThrowsUnclosedInvertedSectionException() { 38 | $this->pickyMustache->render('{{^unclosed}}'); 39 | } 40 | 41 | /** 42 | * @group sections 43 | * @expectedException MustacheException 44 | */ 45 | public function testThrowsUnexpectedCloseSectionException() { 46 | $this->pickyMustache->render('{{/unopened}}'); 47 | } 48 | 49 | /** 50 | * @group partials 51 | * @expectedException MustacheException 52 | */ 53 | public function testThrowsUnknownPartialException() { 54 | $this->pickyMustache->render('{{>impartial}}'); 55 | } 56 | 57 | /** 58 | * @group pragmas 59 | * @expectedException MustacheException 60 | */ 61 | public function testThrowsUnknownPragmaException() { 62 | $this->pickyMustache->render('{{%SWEET-MUSTACHE-BRO}}'); 63 | } 64 | 65 | /** 66 | * @group sections 67 | */ 68 | public function testDoesntThrowUnclosedSectionException() { 69 | $this->assertEquals('', $this->slackerMustache->render('{{#unclosed}}')); 70 | } 71 | 72 | /** 73 | * @group sections 74 | */ 75 | public function testDoesntThrowUnexpectedCloseSectionException() { 76 | $this->assertEquals('', $this->slackerMustache->render('{{/unopened}}')); 77 | } 78 | 79 | /** 80 | * @group partials 81 | */ 82 | public function testDoesntThrowUnknownPartialException() { 83 | $this->assertEquals('', $this->slackerMustache->render('{{>impartial}}')); 84 | } 85 | 86 | /** 87 | * @group pragmas 88 | * @expectedException MustacheException 89 | */ 90 | public function testGetPragmaOptionsThrowsExceptionsIfItThinksYouHaveAPragmaButItTurnsOutYouDont() { 91 | $mustache = new TestableMustache(); 92 | $mustache->testableGetPragmaOptions('PRAGMATIC'); 93 | } 94 | } 95 | 96 | class PickyMustache extends Mustache { 97 | protected $_throwsExceptions = array( 98 | MustacheException::UNKNOWN_VARIABLE => true, 99 | MustacheException::UNCLOSED_SECTION => true, 100 | MustacheException::UNEXPECTED_CLOSE_SECTION => true, 101 | MustacheException::UNKNOWN_PARTIAL => true, 102 | MustacheException::UNKNOWN_PRAGMA => true, 103 | ); 104 | } 105 | 106 | class SlackerMustache extends Mustache { 107 | protected $_throwsExceptions = array( 108 | MustacheException::UNKNOWN_VARIABLE => false, 109 | MustacheException::UNCLOSED_SECTION => false, 110 | MustacheException::UNEXPECTED_CLOSE_SECTION => false, 111 | MustacheException::UNKNOWN_PARTIAL => false, 112 | MustacheException::UNKNOWN_PRAGMA => false, 113 | ); 114 | } 115 | 116 | class TestableMustache extends Mustache { 117 | public function testableGetPragmaOptions($pragma_name) { 118 | return $this->_getPragmaOptions($pragma_name); 119 | } 120 | } -------------------------------------------------------------------------------- /test/lib/yaml/lib/sfYaml.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | /** 12 | * sfYaml offers convenience methods to load and dump YAML. 13 | * 14 | * @package symfony 15 | * @subpackage yaml 16 | * @author Fabien Potencier 17 | * @version SVN: $Id: sfYaml.class.php 8988 2008-05-15 20:24:26Z fabien $ 18 | */ 19 | class sfYaml 20 | { 21 | static protected 22 | $spec = '1.2'; 23 | 24 | /** 25 | * Sets the YAML specification version to use. 26 | * 27 | * @param string $version The YAML specification version 28 | */ 29 | static public function setSpecVersion($version) 30 | { 31 | if (!in_array($version, array('1.1', '1.2'))) 32 | { 33 | throw new InvalidArgumentException(sprintf('Version %s of the YAML specifications is not supported', $version)); 34 | } 35 | 36 | self::$spec = $version; 37 | } 38 | 39 | /** 40 | * Gets the YAML specification version to use. 41 | * 42 | * @return string The YAML specification version 43 | */ 44 | static public function getSpecVersion() 45 | { 46 | return self::$spec; 47 | } 48 | 49 | /** 50 | * Loads YAML into a PHP array. 51 | * 52 | * The load method, when supplied with a YAML stream (string or file), 53 | * will do its best to convert YAML in a file into a PHP array. 54 | * 55 | * Usage: 56 | * 57 | * $array = sfYaml::load('config.yml'); 58 | * print_r($array); 59 | * 60 | * 61 | * @param string $input Path of YAML file or string containing YAML 62 | * 63 | * @return array The YAML converted to a PHP array 64 | * 65 | * @throws InvalidArgumentException If the YAML is not valid 66 | */ 67 | public static function load($input) 68 | { 69 | $file = ''; 70 | 71 | // if input is a file, process it 72 | if (strpos($input, "\n") === false && is_file($input)) 73 | { 74 | $file = $input; 75 | 76 | ob_start(); 77 | $retval = include($input); 78 | $content = ob_get_clean(); 79 | 80 | // if an array is returned by the config file assume it's in plain php form else in YAML 81 | $input = is_array($retval) ? $retval : $content; 82 | } 83 | 84 | // if an array is returned by the config file assume it's in plain php form else in YAML 85 | if (is_array($input)) 86 | { 87 | return $input; 88 | } 89 | 90 | require_once dirname(__FILE__).'/sfYamlParser.php'; 91 | 92 | $yaml = new sfYamlParser(); 93 | 94 | try 95 | { 96 | $ret = $yaml->parse($input); 97 | } 98 | catch (Exception $e) 99 | { 100 | throw new InvalidArgumentException(sprintf('Unable to parse %s: %s', $file ? sprintf('file "%s"', $file) : 'string', $e->getMessage())); 101 | } 102 | 103 | return $ret; 104 | } 105 | 106 | /** 107 | * Dumps a PHP array to a YAML string. 108 | * 109 | * The dump method, when supplied with an array, will do its best 110 | * to convert the array into friendly YAML. 111 | * 112 | * @param array $array PHP array 113 | * @param integer $inline The level where you switch to inline YAML 114 | * 115 | * @return string A YAML string representing the original PHP array 116 | */ 117 | public static function dump($array, $inline = 2) 118 | { 119 | require_once dirname(__FILE__).'/sfYamlDumper.php'; 120 | 121 | $yaml = new sfYamlDumper(); 122 | 123 | return $yaml->dump($array, $inline); 124 | } 125 | } 126 | 127 | /** 128 | * Wraps echo to automatically provide a newline. 129 | * 130 | * @param string $string The string to echo with new line 131 | */ 132 | function echoln($string) 133 | { 134 | echo $string."\n"; 135 | } 136 | -------------------------------------------------------------------------------- /test/MustacheSpecTest.php: -------------------------------------------------------------------------------- 1 | markTestSkipped('Mustache spec submodule not initialized: run "git submodule update --init"'); 21 | } 22 | } 23 | 24 | /** 25 | * @group comments 26 | * @dataProvider loadCommentSpec 27 | */ 28 | public function testCommentSpec($desc, $template, $data, $partials, $expected) { 29 | $m = new Mustache($template, $data, $partials); 30 | $this->assertEquals($expected, $m->render(), $desc); 31 | } 32 | 33 | /** 34 | * @group delimiters 35 | * @dataProvider loadDelimitersSpec 36 | */ 37 | public function testDelimitersSpec($desc, $template, $data, $partials, $expected) { 38 | $m = new Mustache($template, $data, $partials); 39 | $this->assertEquals($expected, $m->render(), $desc); 40 | } 41 | 42 | /** 43 | * @group interpolation 44 | * @dataProvider loadInterpolationSpec 45 | */ 46 | public function testInterpolationSpec($desc, $template, $data, $partials, $expected) { 47 | $m = new Mustache($template, $data, $partials); 48 | $this->assertEquals($expected, $m->render(), $desc); 49 | } 50 | 51 | /** 52 | * @group inverted-sections 53 | * @dataProvider loadInvertedSpec 54 | */ 55 | public function testInvertedSpec($desc, $template, $data, $partials, $expected) { 56 | $m = new Mustache($template, $data, $partials); 57 | $this->assertEquals($expected, $m->render(), $desc); 58 | } 59 | 60 | // /** 61 | // * @group lambdas 62 | // * @dataProvider loadLambdasSpec 63 | // */ 64 | // public function testLambdasSpec($desc, $template, $data, $partials, $expected) { 65 | // $this->markTestSkipped("Lambdas for PHP haven't made it into the spec yet, so we'll skip them to avoid a bajillion failed tests."); 66 | // 67 | // if (!version_compare(PHP_VERSION, '5.3.0', '>=')) { 68 | // $this->markTestSkipped('Unable to test Lambdas spec with PHP < 5.3.'); 69 | // } 70 | // 71 | // $m = new Mustache($template, $data, $partials); 72 | // $this->assertEquals($expected, $m->render(), $desc); 73 | // } 74 | 75 | /** 76 | * @group partials 77 | * @dataProvider loadPartialsSpec 78 | */ 79 | public function testPartialsSpec($desc, $template, $data, $partials, $expected) { 80 | $m = new Mustache($template, $data, $partials); 81 | $this->assertEquals($expected, $m->render(), $desc); 82 | } 83 | 84 | /** 85 | * @group sections 86 | * @dataProvider loadSectionsSpec 87 | */ 88 | public function testSectionsSpec($desc, $template, $data, $partials, $expected) { 89 | $m = new Mustache($template, $data, $partials); 90 | $this->assertEquals($expected, $m->render(), $desc); 91 | } 92 | 93 | public function loadCommentSpec() { 94 | return $this->loadSpec('comments'); 95 | } 96 | 97 | public function loadDelimitersSpec() { 98 | return $this->loadSpec('delimiters'); 99 | } 100 | 101 | public function loadInterpolationSpec() { 102 | return $this->loadSpec('interpolation'); 103 | } 104 | 105 | public function loadInvertedSpec() { 106 | return $this->loadSpec('inverted'); 107 | } 108 | 109 | // public function loadLambdasSpec() { 110 | // return $this->loadSpec('lambdas'); 111 | // } 112 | 113 | public function loadPartialsSpec() { 114 | return $this->loadSpec('partials'); 115 | } 116 | 117 | public function loadSectionsSpec() { 118 | return $this->loadSpec('sections'); 119 | } 120 | 121 | /** 122 | * Data provider for the mustache spec test. 123 | * 124 | * Loads YAML files from the spec and converts them to PHPisms. 125 | * 126 | * @access public 127 | * @return array 128 | */ 129 | protected function loadSpec($name) { 130 | $filename = dirname(__FILE__) . '/spec/specs/' . $name . '.yml'; 131 | if (!file_exists($filename)) { 132 | return array(); 133 | } 134 | 135 | $data = array(); 136 | 137 | $yaml = new sfYamlParser(); 138 | 139 | $spec = $yaml->parse(file_get_contents($filename)); 140 | foreach ($spec['tests'] as $test) { 141 | $data[] = array($test['name'] . ': ' . $test['desc'], $test['template'], $test['data'], isset($test['partials']) ? $test['partials'] : array(), $test['expected']); 142 | } 143 | return $data; 144 | } 145 | } -------------------------------------------------------------------------------- /test/lib/yaml/doc/00-Introduction.markdown: -------------------------------------------------------------------------------- 1 | Introduction 2 | ============ 3 | 4 | This book is about *Symfony YAML*, a PHP library part of the Symfony 5 | Components project. Its official website is at 6 | http://components.symfony-project.org/yaml/. 7 | 8 | >**SIDEBAR** 9 | >About the Symfony Components 10 | > 11 | >[Symfony Components](http://components.symfony-project.org/) are 12 | >standalone PHP classes that can be easily used in any 13 | >PHP project. Most of the time, they have been developed as part of the 14 | >[Symfony framework](http://www.symfony-project.org/), and decoupled from the 15 | >main framework later on. You don't need to use the Symfony MVC framework to use 16 | >the components. 17 | 18 | What is it? 19 | ----------- 20 | 21 | Symfony YAML is a PHP library that parses YAML strings and converts them to 22 | PHP arrays. It can also converts PHP arrays to YAML strings. 23 | 24 | [YAML](http://www.yaml.org/), YAML Ain't Markup Language, is a human friendly 25 | data serialization standard for all programming languages. YAML is a great 26 | format for your configuration files. YAML files are as expressive as XML files 27 | and as readable as INI files. 28 | 29 | ### Easy to use 30 | 31 | There is only one archive to download, and you are ready to go. No 32 | configuration, No installation. Drop the files in a directory and start using 33 | it today in your projects. 34 | 35 | ### Open-Source 36 | 37 | Released under the MIT license, you are free to do whatever you want, even in 38 | a commercial environment. You are also encouraged to contribute. 39 | 40 | 41 | ### Used by popular Projects 42 | 43 | Symfony YAML was initially released as part of the symfony framework, one of 44 | the most popular PHP web framework. It is also embedded in other popular 45 | projects like PHPUnit or Doctrine. 46 | 47 | ### Documented 48 | 49 | Symfony YAML is fully documented, with a dedicated online book, and of course 50 | a full API documentation. 51 | 52 | ### Fast 53 | 54 | One of the goal of Symfony YAML is to find the right balance between speed and 55 | features. It supports just the needed feature to handle configuration files. 56 | 57 | ### Unit tested 58 | 59 | The library is fully unit-tested. With more than 400 unit tests, the library 60 | is stable and is already used in large projects. 61 | 62 | ### Real Parser 63 | 64 | It sports a real parser and is able to parse a large subset of the YAML 65 | specification, for all your configuration needs. It also means that the parser 66 | is pretty robust, easy to understand, and simple enough to extend. 67 | 68 | ### Clear error messages 69 | 70 | Whenever you have a syntax problem with your YAML files, the library outputs a 71 | helpful message with the filename and the line number where the problem 72 | occurred. It eases the debugging a lot. 73 | 74 | ### Dump support 75 | 76 | It is also able to dump PHP arrays to YAML with object support, and inline 77 | level configuration for pretty outputs. 78 | 79 | ### Types Support 80 | 81 | It supports most of the YAML built-in types like dates, integers, octals, 82 | booleans, and much more... 83 | 84 | 85 | ### Full merge key support 86 | 87 | Full support for references, aliases, and full merge key. Don't repeat 88 | yourself by referencing common configuration bits. 89 | 90 | ### PHP Embedding 91 | 92 | YAML files are dynamic. By embedding PHP code inside a YAML file, you have 93 | even more power for your configuration files. 94 | 95 | Installation 96 | ------------ 97 | 98 | Symfony YAML can be installed by downloading the source code as a 99 | [tar](http://github.com/fabpot/yaml/tarball/master) archive or a 100 | [zip](http://github.com/fabpot/yaml/zipball/master) one. 101 | 102 | To stay up-to-date, you can also use the official Subversion 103 | [repository](http://svn.symfony-project.com/components/yaml/). 104 | 105 | If you are a Git user, there is an official 106 | [mirror](http://github.com/fabpot/yaml), which is updated every 10 minutes. 107 | 108 | If you prefer to install the component globally on your machine, you can use 109 | the symfony [PEAR](http://pear.symfony-project.com/) channel server. 110 | 111 | Support 112 | ------- 113 | 114 | Support questions and enhancements can be discussed on the 115 | [mailing-list](http://groups.google.com/group/symfony-components). 116 | 117 | If you find a bug, you can create a ticket at the symfony 118 | [trac](http://trac.symfony-project.org/newticket) under the *YAML* component. 119 | 120 | License 121 | ------- 122 | 123 | The Symfony YAML component is licensed under the *MIT license*: 124 | 125 | >Copyright (c) 2008-2009 Fabien Potencier 126 | > 127 | >Permission is hereby granted, free of charge, to any person obtaining a copy 128 | >of this software and associated documentation files (the "Software"), to deal 129 | >in the Software without restriction, including without limitation the rights 130 | >to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 131 | >copies of the Software, and to permit persons to whom the Software is furnished 132 | >to do so, subject to the following conditions: 133 | > 134 | >The above copyright notice and this permission notice shall be included in all 135 | >copies or substantial portions of the Software. 136 | > 137 | >THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 138 | >IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 139 | >FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 140 | >AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 141 | >LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 142 | >OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 143 | >THE SOFTWARE. 144 | -------------------------------------------------------------------------------- /test/lib/yaml/doc/02-YAML.markdown: -------------------------------------------------------------------------------- 1 | The YAML Format 2 | =============== 3 | 4 | According to the official [YAML](http://yaml.org/) website, YAML is "a human 5 | friendly data serialization standard for all programming languages". 6 | 7 | Even if the YAML format can describe complex nested data structure, this 8 | chapter only describes the minimum set of features needed to use YAML as a 9 | configuration file format. 10 | 11 | YAML is a simple language that describes data. As PHP, it has a syntax for 12 | simple types like strings, booleans, floats, or integers. But unlike PHP, it 13 | makes a difference between arrays (sequences) and hashes (mappings). 14 | 15 | Scalars 16 | ------- 17 | 18 | The syntax for scalars is similar to the PHP syntax. 19 | 20 | ### Strings 21 | 22 | [yml] 23 | A string in YAML 24 | 25 | - 26 | 27 | [yml] 28 | 'A singled-quoted string in YAML' 29 | 30 | >**TIP** 31 | >In a single quoted string, a single quote `'` must be doubled: 32 | > 33 | > [yml] 34 | > 'A single quote '' in a single-quoted string' 35 | 36 | [yml] 37 | "A double-quoted string in YAML\n" 38 | 39 | Quoted styles are useful when a string starts or ends with one or more 40 | relevant spaces. 41 | 42 | >**TIP** 43 | >The double-quoted style provides a way to express arbitrary strings, by 44 | >using `\` escape sequences. It is very useful when you need to embed a 45 | >`\n` or a unicode character in a string. 46 | 47 | When a string contains line breaks, you can use the literal style, indicated 48 | by the pipe (`|`), to indicate that the string will span several lines. In 49 | literals, newlines are preserved: 50 | 51 | [yml] 52 | | 53 | \/ /| |\/| | 54 | / / | | | |__ 55 | 56 | Alternatively, strings can be written with the folded style, denoted by `>`, 57 | where each line break is replaced by a space: 58 | 59 | [yml] 60 | > 61 | This is a very long sentence 62 | that spans several lines in the YAML 63 | but which will be rendered as a string 64 | without carriage returns. 65 | 66 | >**NOTE** 67 | >Notice the two spaces before each line in the previous examples. They 68 | >won't appear in the resulting PHP strings. 69 | 70 | ### Numbers 71 | 72 | [yml] 73 | # an integer 74 | 12 75 | 76 | - 77 | 78 | [yml] 79 | # an octal 80 | 014 81 | 82 | - 83 | 84 | [yml] 85 | # an hexadecimal 86 | 0xC 87 | 88 | - 89 | 90 | [yml] 91 | # a float 92 | 13.4 93 | 94 | - 95 | 96 | [yml] 97 | # an exponential number 98 | 1.2e+34 99 | 100 | - 101 | 102 | [yml] 103 | # infinity 104 | .inf 105 | 106 | ### Nulls 107 | 108 | Nulls in YAML can be expressed with `null` or `~`. 109 | 110 | ### Booleans 111 | 112 | Booleans in YAML are expressed with `true` and `false`. 113 | 114 | >**NOTE** 115 | >The symfony YAML parser also recognize `on`, `off`, `yes`, and `no` but 116 | >it is strongly discouraged to use them as it has been removed from the 117 | >1.2 YAML specifications. 118 | 119 | ### Dates 120 | 121 | YAML uses the ISO-8601 standard to express dates: 122 | 123 | [yml] 124 | 2001-12-14t21:59:43.10-05:00 125 | 126 | - 127 | 128 | [yml] 129 | # simple date 130 | 2002-12-14 131 | 132 | Collections 133 | ----------- 134 | 135 | A YAML file is rarely used to describe a simple scalar. Most of the time, it 136 | describes a collection. A collection can be a sequence or a mapping of 137 | elements. Both sequences and mappings are converted to PHP arrays. 138 | 139 | Sequences use a dash followed by a space (`- `): 140 | 141 | [yml] 142 | - PHP 143 | - Perl 144 | - Python 145 | 146 | The previous YAML file is equivalent to the following PHP code: 147 | 148 | [php] 149 | array('PHP', 'Perl', 'Python'); 150 | 151 | Mappings use a colon followed by a space (`: `) to mark each key/value pair: 152 | 153 | [yml] 154 | PHP: 5.2 155 | MySQL: 5.1 156 | Apache: 2.2.20 157 | 158 | which is equivalent to this PHP code: 159 | 160 | [php] 161 | array('PHP' => 5.2, 'MySQL' => 5.1, 'Apache' => '2.2.20'); 162 | 163 | >**NOTE** 164 | >In a mapping, a key can be any valid scalar. 165 | 166 | The number of spaces between the colon and the value does not matter: 167 | 168 | [yml] 169 | PHP: 5.2 170 | MySQL: 5.1 171 | Apache: 2.2.20 172 | 173 | YAML uses indentation with one or more spaces to describe nested collections: 174 | 175 | [yml] 176 | "symfony 1.0": 177 | PHP: 5.0 178 | Propel: 1.2 179 | "symfony 1.2": 180 | PHP: 5.2 181 | Propel: 1.3 182 | 183 | The following YAML is equivalent to the following PHP code: 184 | 185 | [php] 186 | array( 187 | 'symfony 1.0' => array( 188 | 'PHP' => 5.0, 189 | 'Propel' => 1.2, 190 | ), 191 | 'symfony 1.2' => array( 192 | 'PHP' => 5.2, 193 | 'Propel' => 1.3, 194 | ), 195 | ); 196 | 197 | There is one important thing you need to remember when using indentation in a 198 | YAML file: *Indentation must be done with one or more spaces, but never with 199 | tabulations*. 200 | 201 | You can nest sequences and mappings as you like: 202 | 203 | [yml] 204 | 'Chapter 1': 205 | - Introduction 206 | - Event Types 207 | 'Chapter 2': 208 | - Introduction 209 | - Helpers 210 | 211 | YAML can also use flow styles for collections, using explicit indicators 212 | rather than indentation to denote scope. 213 | 214 | A sequence can be written as a comma separated list within square brackets 215 | (`[]`): 216 | 217 | [yml] 218 | [PHP, Perl, Python] 219 | 220 | A mapping can be written as a comma separated list of key/values within curly 221 | braces (`{}`): 222 | 223 | [yml] 224 | { PHP: 5.2, MySQL: 5.1, Apache: 2.2.20 } 225 | 226 | You can mix and match styles to achieve a better readability: 227 | 228 | [yml] 229 | 'Chapter 1': [Introduction, Event Types] 230 | 'Chapter 2': [Introduction, Helpers] 231 | 232 | - 233 | 234 | [yml] 235 | "symfony 1.0": { PHP: 5.0, Propel: 1.2 } 236 | "symfony 1.2": { PHP: 5.2, Propel: 1.3 } 237 | 238 | Comments 239 | -------- 240 | 241 | Comments can be added in YAML by prefixing them with a hash mark (`#`): 242 | 243 | [yml] 244 | # Comment on a line 245 | "symfony 1.0": { PHP: 5.0, Propel: 1.2 } # Comment at the end of a line 246 | "symfony 1.2": { PHP: 5.2, Propel: 1.3 } 247 | 248 | >**NOTE** 249 | >Comments are simply ignored by the YAML parser and do not need to be 250 | >indented according to the current level of nesting in a collection. 251 | 252 | Dynamic YAML files 253 | ------------------ 254 | 255 | In symfony, a YAML file can contain PHP code that is evaluated just before the 256 | parsing occurs: 257 | 258 | [php] 259 | 1.0: 260 | version: 261 | 1.1: 262 | version: "" 263 | 264 | Be careful to not mess up with the indentation. Keep in mind the following 265 | simple tips when adding PHP code to a YAML file: 266 | 267 | * The `` statements must always start the line or be embedded in a 268 | value. 269 | 270 | * If a `` statement ends a line, you need to explicitly output a new 271 | line ("\n"). 272 | 273 |
274 | 275 | A Full Length Example 276 | --------------------- 277 | 278 | The following example illustrates most YAML notations explained in this 279 | document: 280 | 281 | [yml] 282 | "symfony 1.0": 283 | end_of_maintainance: 2010-01-01 284 | is_stable: true 285 | release_manager: "Grégoire Hubert" 286 | description: > 287 | This stable version is the right choice for projects 288 | that need to be maintained for a long period of time. 289 | latest_beta: ~ 290 | latest_minor: 1.0.20 291 | supported_orms: [Propel] 292 | archives: { source: [zip, tgz], sandbox: [zip, tgz] } 293 | 294 | "symfony 1.2": 295 | end_of_maintainance: 2008-11-01 296 | is_stable: true 297 | release_manager: 'Fabian Lange' 298 | description: > 299 | This stable version is the right choice 300 | if you start a new project today. 301 | latest_beta: null 302 | latest_minor: 1.2.5 303 | supported_orms: 304 | - Propel 305 | - Doctrine 306 | archives: 307 | source: 308 | - zip 309 | - tgz 310 | sandbox: 311 | - zip 312 | - tgz 313 | -------------------------------------------------------------------------------- /test/lib/yaml/lib/sfYamlInline.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | require_once dirname(__FILE__).'/sfYaml.php'; 12 | 13 | /** 14 | * sfYamlInline implements a YAML parser/dumper for the YAML inline syntax. 15 | * 16 | * @package symfony 17 | * @subpackage yaml 18 | * @author Fabien Potencier 19 | * @version SVN: $Id: sfYamlInline.class.php 16177 2009-03-11 08:32:48Z fabien $ 20 | */ 21 | class sfYamlInline 22 | { 23 | const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; 24 | 25 | /** 26 | * Convert a YAML string to a PHP array. 27 | * 28 | * @param string $value A YAML string 29 | * 30 | * @return array A PHP array representing the YAML string 31 | */ 32 | static public function load($value) 33 | { 34 | $value = trim($value); 35 | 36 | if (0 == strlen($value)) 37 | { 38 | return ''; 39 | } 40 | 41 | if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) 42 | { 43 | $mbEncoding = mb_internal_encoding(); 44 | mb_internal_encoding('ASCII'); 45 | } 46 | 47 | switch ($value[0]) 48 | { 49 | case '[': 50 | $result = self::parseSequence($value); 51 | break; 52 | case '{': 53 | $result = self::parseMapping($value); 54 | break; 55 | default: 56 | $result = self::parseScalar($value); 57 | } 58 | 59 | if (isset($mbEncoding)) 60 | { 61 | mb_internal_encoding($mbEncoding); 62 | } 63 | 64 | return $result; 65 | } 66 | 67 | /** 68 | * Dumps a given PHP variable to a YAML string. 69 | * 70 | * @param mixed $value The PHP variable to convert 71 | * 72 | * @return string The YAML string representing the PHP array 73 | */ 74 | static public function dump($value) 75 | { 76 | if ('1.1' === sfYaml::getSpecVersion()) 77 | { 78 | $trueValues = array('true', 'on', '+', 'yes', 'y'); 79 | $falseValues = array('false', 'off', '-', 'no', 'n'); 80 | } 81 | else 82 | { 83 | $trueValues = array('true'); 84 | $falseValues = array('false'); 85 | } 86 | 87 | switch (true) 88 | { 89 | case is_resource($value): 90 | throw new InvalidArgumentException('Unable to dump PHP resources in a YAML file.'); 91 | case is_object($value): 92 | return '!!php/object:'.serialize($value); 93 | case is_array($value): 94 | return self::dumpArray($value); 95 | case null === $value: 96 | return 'null'; 97 | case true === $value: 98 | return 'true'; 99 | case false === $value: 100 | return 'false'; 101 | case ctype_digit($value): 102 | return is_string($value) ? "'$value'" : (int) $value; 103 | case is_numeric($value): 104 | return is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : (is_string($value) ? "'$value'" : $value); 105 | case false !== strpos($value, "\n") || false !== strpos($value, "\r"): 106 | return sprintf('"%s"', str_replace(array('"', "\n", "\r"), array('\\"', '\n', '\r'), $value)); 107 | case preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ - ? | < > = ! % @ ` ]/x', $value): 108 | return sprintf("'%s'", str_replace('\'', '\'\'', $value)); 109 | case '' == $value: 110 | return "''"; 111 | case preg_match(self::getTimestampRegex(), $value): 112 | return "'$value'"; 113 | case in_array(strtolower($value), $trueValues): 114 | return "'$value'"; 115 | case in_array(strtolower($value), $falseValues): 116 | return "'$value'"; 117 | case in_array(strtolower($value), array('null', '~')): 118 | return "'$value'"; 119 | default: 120 | return $value; 121 | } 122 | } 123 | 124 | /** 125 | * Dumps a PHP array to a YAML string. 126 | * 127 | * @param array $value The PHP array to dump 128 | * 129 | * @return string The YAML string representing the PHP array 130 | */ 131 | static protected function dumpArray($value) 132 | { 133 | // array 134 | $keys = array_keys($value); 135 | if ( 136 | (1 == count($keys) && '0' == $keys[0]) 137 | || 138 | (count($keys) > 1 && array_reduce($keys, create_function('$v,$w', 'return (integer) $v + $w;'), 0) == count($keys) * (count($keys) - 1) / 2)) 139 | { 140 | $output = array(); 141 | foreach ($value as $val) 142 | { 143 | $output[] = self::dump($val); 144 | } 145 | 146 | return sprintf('[%s]', implode(', ', $output)); 147 | } 148 | 149 | // mapping 150 | $output = array(); 151 | foreach ($value as $key => $val) 152 | { 153 | $output[] = sprintf('%s: %s', self::dump($key), self::dump($val)); 154 | } 155 | 156 | return sprintf('{ %s }', implode(', ', $output)); 157 | } 158 | 159 | /** 160 | * Parses a scalar to a YAML string. 161 | * 162 | * @param scalar $scalar 163 | * @param string $delimiters 164 | * @param array $stringDelimiter 165 | * @param integer $i 166 | * @param boolean $evaluate 167 | * 168 | * @return string A YAML string 169 | */ 170 | static public function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) 171 | { 172 | if (in_array($scalar[$i], $stringDelimiters)) 173 | { 174 | // quoted scalar 175 | $output = self::parseQuotedScalar($scalar, $i); 176 | } 177 | else 178 | { 179 | // "normal" string 180 | if (!$delimiters) 181 | { 182 | $output = substr($scalar, $i); 183 | $i += strlen($output); 184 | 185 | // remove comments 186 | if (false !== $strpos = strpos($output, ' #')) 187 | { 188 | $output = rtrim(substr($output, 0, $strpos)); 189 | } 190 | } 191 | else if (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) 192 | { 193 | $output = $match[1]; 194 | $i += strlen($output); 195 | } 196 | else 197 | { 198 | throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', $scalar)); 199 | } 200 | 201 | $output = $evaluate ? self::evaluateScalar($output) : $output; 202 | } 203 | 204 | return $output; 205 | } 206 | 207 | /** 208 | * Parses a quoted scalar to YAML. 209 | * 210 | * @param string $scalar 211 | * @param integer $i 212 | * 213 | * @return string A YAML string 214 | */ 215 | static protected function parseQuotedScalar($scalar, &$i) 216 | { 217 | if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) 218 | { 219 | throw new InvalidArgumentException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); 220 | } 221 | 222 | $output = substr($match[0], 1, strlen($match[0]) - 2); 223 | 224 | if ('"' == $scalar[$i]) 225 | { 226 | // evaluate the string 227 | $output = str_replace(array('\\"', '\\n', '\\r'), array('"', "\n", "\r"), $output); 228 | } 229 | else 230 | { 231 | // unescape ' 232 | $output = str_replace('\'\'', '\'', $output); 233 | } 234 | 235 | $i += strlen($match[0]); 236 | 237 | return $output; 238 | } 239 | 240 | /** 241 | * Parses a sequence to a YAML string. 242 | * 243 | * @param string $sequence 244 | * @param integer $i 245 | * 246 | * @return string A YAML string 247 | */ 248 | static protected function parseSequence($sequence, &$i = 0) 249 | { 250 | $output = array(); 251 | $len = strlen($sequence); 252 | $i += 1; 253 | 254 | // [foo, bar, ...] 255 | while ($i < $len) 256 | { 257 | switch ($sequence[$i]) 258 | { 259 | case '[': 260 | // nested sequence 261 | $output[] = self::parseSequence($sequence, $i); 262 | break; 263 | case '{': 264 | // nested mapping 265 | $output[] = self::parseMapping($sequence, $i); 266 | break; 267 | case ']': 268 | return $output; 269 | case ',': 270 | case ' ': 271 | break; 272 | default: 273 | $isQuoted = in_array($sequence[$i], array('"', "'")); 274 | $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); 275 | 276 | if (!$isQuoted && false !== strpos($value, ': ')) 277 | { 278 | // embedded mapping? 279 | try 280 | { 281 | $value = self::parseMapping('{'.$value.'}'); 282 | } 283 | catch (InvalidArgumentException $e) 284 | { 285 | // no, it's not 286 | } 287 | } 288 | 289 | $output[] = $value; 290 | 291 | --$i; 292 | } 293 | 294 | ++$i; 295 | } 296 | 297 | throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $sequence)); 298 | } 299 | 300 | /** 301 | * Parses a mapping to a YAML string. 302 | * 303 | * @param string $mapping 304 | * @param integer $i 305 | * 306 | * @return string A YAML string 307 | */ 308 | static protected function parseMapping($mapping, &$i = 0) 309 | { 310 | $output = array(); 311 | $len = strlen($mapping); 312 | $i += 1; 313 | 314 | // {foo: bar, bar:foo, ...} 315 | while ($i < $len) 316 | { 317 | switch ($mapping[$i]) 318 | { 319 | case ' ': 320 | case ',': 321 | ++$i; 322 | continue 2; 323 | case '}': 324 | return $output; 325 | } 326 | 327 | // key 328 | $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); 329 | 330 | // value 331 | $done = false; 332 | while ($i < $len) 333 | { 334 | switch ($mapping[$i]) 335 | { 336 | case '[': 337 | // nested sequence 338 | $output[$key] = self::parseSequence($mapping, $i); 339 | $done = true; 340 | break; 341 | case '{': 342 | // nested mapping 343 | $output[$key] = self::parseMapping($mapping, $i); 344 | $done = true; 345 | break; 346 | case ':': 347 | case ' ': 348 | break; 349 | default: 350 | $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); 351 | $done = true; 352 | --$i; 353 | } 354 | 355 | ++$i; 356 | 357 | if ($done) 358 | { 359 | continue 2; 360 | } 361 | } 362 | } 363 | 364 | throw new InvalidArgumentException(sprintf('Malformed inline YAML string %s', $mapping)); 365 | } 366 | 367 | /** 368 | * Evaluates scalars and replaces magic values. 369 | * 370 | * @param string $scalar 371 | * 372 | * @return string A YAML string 373 | */ 374 | static protected function evaluateScalar($scalar) 375 | { 376 | $scalar = trim($scalar); 377 | 378 | if ('1.1' === sfYaml::getSpecVersion()) 379 | { 380 | $trueValues = array('true', 'on', '+', 'yes', 'y'); 381 | $falseValues = array('false', 'off', '-', 'no', 'n'); 382 | } 383 | else 384 | { 385 | $trueValues = array('true'); 386 | $falseValues = array('false'); 387 | } 388 | 389 | switch (true) 390 | { 391 | case 'null' == strtolower($scalar): 392 | case '' == $scalar: 393 | case '~' == $scalar: 394 | return null; 395 | case 0 === strpos($scalar, '!str'): 396 | return (string) substr($scalar, 5); 397 | case 0 === strpos($scalar, '! '): 398 | return intval(self::parseScalar(substr($scalar, 2))); 399 | case 0 === strpos($scalar, '!!php/object:'): 400 | return unserialize(substr($scalar, 13)); 401 | case ctype_digit($scalar): 402 | $raw = $scalar; 403 | $cast = intval($scalar); 404 | return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); 405 | case in_array(strtolower($scalar), $trueValues): 406 | return true; 407 | case in_array(strtolower($scalar), $falseValues): 408 | return false; 409 | case is_numeric($scalar): 410 | return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); 411 | case 0 == strcasecmp($scalar, '.inf'): 412 | case 0 == strcasecmp($scalar, '.NaN'): 413 | return -log(0); 414 | case 0 == strcasecmp($scalar, '-.inf'): 415 | return log(0); 416 | case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): 417 | return floatval(str_replace(',', '', $scalar)); 418 | case preg_match(self::getTimestampRegex(), $scalar): 419 | return strtotime($scalar); 420 | default: 421 | return (string) $scalar; 422 | } 423 | } 424 | 425 | static protected function getTimestampRegex() 426 | { 427 | return <<[0-9][0-9][0-9][0-9]) 430 | -(?P[0-9][0-9]?) 431 | -(?P[0-9][0-9]?) 432 | (?:(?:[Tt]|[ \t]+) 433 | (?P[0-9][0-9]?) 434 | :(?P[0-9][0-9]) 435 | :(?P[0-9][0-9]) 436 | (?:\.(?P[0-9]*))? 437 | (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) 438 | (?::(?P[0-9][0-9]))?))?)? 439 | $~x 440 | EOF; 441 | } 442 | } 443 | -------------------------------------------------------------------------------- /test/MustacheTest.php: -------------------------------------------------------------------------------- 1 | array( 52 | array('type' => 'Natural'), 53 | array('type' => 'Hungarian'), 54 | array('type' => 'Dali'), 55 | array('type' => 'English'), 56 | array('type' => 'Imperial'), 57 | array('type' => 'Freestyle', 'last' => 'true'), 58 | ) 59 | ); 60 | $output = 'Natural, Hungarian, Dali, English, Imperial, and Freestyle'; 61 | 62 | $m1 = new Mustache(); 63 | $this->assertEquals($output, $m1->render($template, $data)); 64 | 65 | $m2 = new Mustache($template); 66 | $this->assertEquals($output, $m2->render(null, $data)); 67 | 68 | $m3 = new Mustache($template, $data); 69 | $this->assertEquals($output, $m3->render()); 70 | 71 | $m4 = new Mustache(null, $data); 72 | $this->assertEquals($output, $m4->render($template)); 73 | } 74 | 75 | /** 76 | * @dataProvider constructorOptions 77 | */ 78 | public function testConstructorOptions($options, $charset, $delimiters, $pragmas) { 79 | $mustache = new MustacheExposedOptionsStub(null, null, null, $options); 80 | $this->assertEquals($charset, $mustache->getCharset()); 81 | $this->assertEquals($delimiters, $mustache->getDelimiters()); 82 | $this->assertEquals($pragmas, $mustache->getPragmas()); 83 | } 84 | 85 | public function constructorOptions() { 86 | return array( 87 | array( 88 | array(), 89 | 'UTF-8', 90 | array('{{', '}}'), 91 | array(), 92 | ), 93 | array( 94 | array( 95 | 'charset' => 'UTF-8', 96 | 'delimiters' => '<< >>', 97 | 'pragmas' => array(Mustache::PRAGMA_UNESCAPED) 98 | ), 99 | 'UTF-8', 100 | array('<<', '>>'), 101 | array(Mustache::PRAGMA_UNESCAPED), 102 | ), 103 | array( 104 | array( 105 | 'charset' => 'cp866', 106 | 'delimiters' => array('[[[[', ']]]]'), 107 | 'pragmas' => array(Mustache::PRAGMA_UNESCAPED) 108 | ), 109 | 'cp866', 110 | array('[[[[', ']]]]'), 111 | array(Mustache::PRAGMA_UNESCAPED), 112 | ), 113 | ); 114 | } 115 | 116 | /** 117 | * @expectedException MustacheException 118 | */ 119 | public function testConstructorInvalidPragmaOptionsThrowExceptions() { 120 | $mustache = new Mustache(null, null, null, array('pragmas' => array('banana phone'))); 121 | } 122 | 123 | /** 124 | * Test __toString() function. 125 | * 126 | * @access public 127 | * @return void 128 | */ 129 | public function test__toString() { 130 | $m = new Mustache('{{first_name}} {{last_name}}', array('first_name' => 'Karl', 'last_name' => 'Marx')); 131 | 132 | $this->assertEquals('Karl Marx', $m->__toString()); 133 | $this->assertEquals('Karl Marx', (string) $m); 134 | 135 | $m2 = $this->getMock(self::TEST_CLASS, array('render'), array()); 136 | $m2->expects($this->once()) 137 | ->method('render') 138 | ->will($this->returnValue('foo')); 139 | 140 | $this->assertEquals('foo', $m2->render()); 141 | } 142 | 143 | public function test__toStringException() { 144 | $m = $this->getMock(self::TEST_CLASS, array('render'), array()); 145 | $m->expects($this->once()) 146 | ->method('render') 147 | ->will($this->throwException(new Exception)); 148 | 149 | try { 150 | $out = (string) $m; 151 | } catch (Exception $e) { 152 | $this->fail('__toString should catch all exceptions'); 153 | } 154 | } 155 | 156 | /** 157 | * Test render(). 158 | * 159 | * @access public 160 | * @return void 161 | */ 162 | public function testRender() { 163 | $m = new Mustache(); 164 | 165 | $this->assertEquals('', $m->render('')); 166 | $this->assertEquals('foo', $m->render('foo')); 167 | $this->assertEquals('', $m->render(null)); 168 | 169 | $m2 = new Mustache('foo'); 170 | $this->assertEquals('foo', $m2->render()); 171 | 172 | $m3 = new Mustache(''); 173 | $this->assertEquals('', $m3->render()); 174 | 175 | $m3 = new Mustache(); 176 | $this->assertEquals('', $m3->render(null)); 177 | } 178 | 179 | /** 180 | * Test render() with data. 181 | * 182 | * @group interpolation 183 | */ 184 | public function testRenderWithData() { 185 | $m = new Mustache('{{first_name}} {{last_name}}'); 186 | $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin'))); 187 | $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa'))); 188 | } 189 | 190 | /** 191 | * @group partials 192 | */ 193 | public function testRenderWithPartials() { 194 | $m = new Mustache('{{>stache}}', null, array('stache' => '{{first_name}} {{last_name}}')); 195 | $this->assertEquals('Charlie Chaplin', $m->render(null, array('first_name' => 'Charlie', 'last_name' => 'Chaplin'))); 196 | $this->assertEquals('Zappa, Frank', $m->render('{{last_name}}, {{first_name}}', array('first_name' => 'Frank', 'last_name' => 'Zappa'))); 197 | } 198 | 199 | /** 200 | * @group interpolation 201 | * @dataProvider interpolationData 202 | */ 203 | public function testDoubleRenderMustacheTags($template, $context, $expected) { 204 | $m = new Mustache($template, $context); 205 | $this->assertEquals($expected, $m->render()); 206 | } 207 | 208 | public function interpolationData() { 209 | return array( 210 | array( 211 | '{{#a}}{{=<% %>=}}{{b}} c<%={{ }}=%>{{/a}}', 212 | array('a' => array(array('b' => 'Do Not Render'))), 213 | '{{b}} c' 214 | ), 215 | array( 216 | '{{#a}}{{b}}{{/a}}', 217 | array('a' => array('b' => '{{c}}'), 'c' => 'FAIL'), 218 | '{{c}}' 219 | ), 220 | ); 221 | } 222 | 223 | /** 224 | * Mustache should allow newlines (and other whitespace) in comments and all other tags. 225 | * 226 | * @group comments 227 | */ 228 | public function testNewlinesInComments() { 229 | $m = new Mustache("{{! comment \n \t still a comment... }}"); 230 | $this->assertEquals('', $m->render()); 231 | } 232 | 233 | /** 234 | * Mustache should return the same thing when invoked multiple times. 235 | */ 236 | public function testMultipleInvocations() { 237 | $m = new Mustache('x'); 238 | $first = $m->render(); 239 | $second = $m->render(); 240 | 241 | $this->assertEquals('x', $first); 242 | $this->assertEquals($first, $second); 243 | } 244 | 245 | /** 246 | * Mustache should return the same thing when invoked multiple times. 247 | * 248 | * @group interpolation 249 | */ 250 | public function testMultipleInvocationsWithTags() { 251 | $m = new Mustache('{{one}} {{two}}', array('one' => 'foo', 'two' => 'bar')); 252 | $first = $m->render(); 253 | $second = $m->render(); 254 | 255 | $this->assertEquals('foo bar', $first); 256 | $this->assertEquals($first, $second); 257 | } 258 | 259 | /** 260 | * Mustache should not use templates passed to the render() method for subsequent invocations. 261 | */ 262 | public function testResetTemplateForMultipleInvocations() { 263 | $m = new Mustache('Sirve.'); 264 | $this->assertEquals('No sirve.', $m->render('No sirve.')); 265 | $this->assertEquals('Sirve.', $m->render()); 266 | 267 | $m2 = new Mustache(); 268 | $this->assertEquals('No sirve.', $m2->render('No sirve.')); 269 | $this->assertEquals('', $m2->render()); 270 | } 271 | 272 | /** 273 | * Test the __clone() magic function. 274 | * 275 | * @group examples 276 | * @dataProvider getExamples 277 | * 278 | * @param string $class 279 | * @param string $template 280 | * @param string $output 281 | */ 282 | public function test__clone($class, $template, $output) { 283 | if (isset($this->knownIssues[$class])) { 284 | return $this->markTestSkipped($this->knownIssues[$class]); 285 | } 286 | 287 | $m = new $class; 288 | $n = clone $m; 289 | 290 | $n_output = $n->render($template); 291 | 292 | $o = clone $n; 293 | 294 | $this->assertEquals($m->render($template), $n_output); 295 | $this->assertEquals($n_output, $o->render($template)); 296 | 297 | $this->assertNotSame($m, $n); 298 | $this->assertNotSame($n, $o); 299 | $this->assertNotSame($m, $o); 300 | } 301 | 302 | /** 303 | * Test everything in the `examples` directory. 304 | * 305 | * @group examples 306 | * @dataProvider getExamples 307 | * 308 | * @param string $class 309 | * @param string $template 310 | * @param string $output 311 | */ 312 | public function testExamples($class, $template, $output) { 313 | if (isset($this->knownIssues[$class])) { 314 | return $this->markTestSkipped($this->knownIssues[$class]); 315 | } 316 | 317 | $m = new $class; 318 | $this->assertEquals($output, $m->render($template)); 319 | } 320 | 321 | /** 322 | * Data provider for testExamples method. 323 | * 324 | * Assumes that an `examples` directory exists inside parent directory. 325 | * This examples directory should contain any number of subdirectories, each of which contains 326 | * three files: one Mustache class (.php), one Mustache template (.mustache), and one output file 327 | * (.txt). 328 | * 329 | * This whole mess will be refined later to be more intuitive and less prescriptive, but it'll 330 | * do for now. Especially since it means we can have unit tests :) 331 | * 332 | * @return array 333 | */ 334 | public function getExamples() { 335 | $basedir = dirname(__FILE__) . '/../examples/'; 336 | 337 | $ret = array(); 338 | 339 | $files = new RecursiveDirectoryIterator($basedir); 340 | while ($files->valid()) { 341 | 342 | if ($files->hasChildren() && $children = $files->getChildren()) { 343 | $example = $files->getSubPathname(); 344 | $class = null; 345 | $template = null; 346 | $output = null; 347 | 348 | foreach ($children as $file) { 349 | if (!$file->isFile()) continue; 350 | 351 | $filename = $file->getPathname(); 352 | $info = pathinfo($filename); 353 | 354 | if (isset($info['extension'])) { 355 | switch($info['extension']) { 356 | case 'php': 357 | $class = $info['filename']; 358 | include_once($filename); 359 | break; 360 | 361 | case 'mustache': 362 | $template = file_get_contents($filename); 363 | break; 364 | 365 | case 'txt': 366 | $output = file_get_contents($filename); 367 | break; 368 | } 369 | } 370 | } 371 | 372 | if (!empty($class)) { 373 | $ret[$example] = array($class, $template, $output); 374 | } 375 | } 376 | 377 | $files->next(); 378 | } 379 | return $ret; 380 | } 381 | 382 | /** 383 | * @group delimiters 384 | */ 385 | public function testCrazyDelimiters() { 386 | $m = new Mustache(null, array('result' => 'success')); 387 | $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]')); 388 | $this->assertEquals('success', $m->render('{{=(( ))=}}(( result ))')); 389 | $this->assertEquals('success', $m->render('{{={$ $}=}}{$ result $}')); 390 | $this->assertEquals('success', $m->render('{{=<.. ..>=}}<.. result ..>')); 391 | $this->assertEquals('success', $m->render('{{=^^ ^^}}^^ result ^^')); 392 | $this->assertEquals('success', $m->render('{{=// \\\\}}// result \\\\')); 393 | } 394 | 395 | /** 396 | * @group delimiters 397 | */ 398 | public function testResetDelimiters() { 399 | $m = new Mustache(null, array('result' => 'success')); 400 | $this->assertEquals('success', $m->render('{{=[[ ]]=}}[[ result ]]')); 401 | $this->assertEquals('success', $m->render('{{=<< >>=}}<< result >>')); 402 | $this->assertEquals('success', $m->render('{{=<% %>=}}<% result %>')); 403 | } 404 | 405 | /** 406 | * @group delimiters 407 | */ 408 | public function testStickyDelimiters() { 409 | $m = new Mustache(null, array('result' => 'FAIL')); 410 | $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}{{ result }}[[={{ }}=]]')); 411 | $this->assertEquals('{{#result}}{{/result}}', $m->render('{{=[[ ]]=}}{{#result}}{{/result}}[[={{ }}=]]')); 412 | $this->assertEquals('{{ result }}', $m->render('{{=[[ ]]=}}[[#result]]{{ result }}[[/result]][[={{ }}=]]')); 413 | $this->assertEquals('{{ result }}', $m->render('{{#result}}{{=[[ ]]=}}{{ result }}[[/result]][[^result]][[={{ }}=]][[ result ]]{{/result}}')); 414 | } 415 | 416 | /** 417 | * @group sections 418 | * @dataProvider poorlyNestedSections 419 | * @expectedException MustacheException 420 | */ 421 | public function testPoorlyNestedSections($template) { 422 | $m = new Mustache($template); 423 | $m->render(); 424 | } 425 | 426 | public function poorlyNestedSections() { 427 | return array( 428 | array('{{#foo}}'), 429 | array('{{#foo}}{{/bar}}'), 430 | array('{{#foo}}{{#bar}}{{/foo}}'), 431 | array('{{#foo}}{{#bar}}{{/foo}}{{/bar}}'), 432 | array('{{#foo}}{{/bar}}{{/foo}}'), 433 | ); 434 | } 435 | 436 | /** 437 | * Ensure that Mustache doesn't double-render sections (allowing mustache injection). 438 | * 439 | * @group sections 440 | */ 441 | public function testMustacheInjection() { 442 | $template = '{{#foo}}{{bar}}{{/foo}}'; 443 | $view = array( 444 | 'foo' => true, 445 | 'bar' => '{{win}}', 446 | 'win' => 'FAIL', 447 | ); 448 | 449 | $m = new Mustache($template, $view); 450 | $this->assertEquals('{{win}}', $m->render()); 451 | } 452 | } 453 | 454 | class MustacheExposedOptionsStub extends Mustache { 455 | public function getPragmas() { 456 | return $this->_pragmas; 457 | } 458 | public function getCharset() { 459 | return $this->_charset; 460 | } 461 | public function getDelimiters() { 462 | return array($this->_otag, $this->_ctag); 463 | } 464 | } 465 | -------------------------------------------------------------------------------- /test/lib/yaml/lib/sfYamlParser.php: -------------------------------------------------------------------------------- 1 | 6 | * 7 | * For the full copyright and license information, please view the LICENSE 8 | * file that was distributed with this source code. 9 | */ 10 | 11 | require_once(dirname(__FILE__).'/sfYamlInline.php'); 12 | 13 | if (!defined('PREG_BAD_UTF8_OFFSET_ERROR')) 14 | { 15 | define('PREG_BAD_UTF8_OFFSET_ERROR', 5); 16 | } 17 | 18 | /** 19 | * sfYamlParser parses YAML strings to convert them to PHP arrays. 20 | * 21 | * @package symfony 22 | * @subpackage yaml 23 | * @author Fabien Potencier 24 | * @version SVN: $Id: sfYamlParser.class.php 10832 2008-08-13 07:46:08Z fabien $ 25 | */ 26 | class sfYamlParser 27 | { 28 | protected 29 | $offset = 0, 30 | $lines = array(), 31 | $currentLineNb = -1, 32 | $currentLine = '', 33 | $refs = array(); 34 | 35 | /** 36 | * Constructor 37 | * 38 | * @param integer $offset The offset of YAML document (used for line numbers in error messages) 39 | */ 40 | public function __construct($offset = 0) 41 | { 42 | $this->offset = $offset; 43 | } 44 | 45 | /** 46 | * Parses a YAML string to a PHP value. 47 | * 48 | * @param string $value A YAML string 49 | * 50 | * @return mixed A PHP value 51 | * 52 | * @throws InvalidArgumentException If the YAML is not valid 53 | */ 54 | public function parse($value) 55 | { 56 | $this->currentLineNb = -1; 57 | $this->currentLine = ''; 58 | $this->lines = explode("\n", $this->cleanup($value)); 59 | 60 | if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) 61 | { 62 | $mbEncoding = mb_internal_encoding(); 63 | mb_internal_encoding('UTF-8'); 64 | } 65 | 66 | $data = array(); 67 | while ($this->moveToNextLine()) 68 | { 69 | if ($this->isCurrentLineEmpty()) 70 | { 71 | continue; 72 | } 73 | 74 | // tab? 75 | if (preg_match('#^\t+#', $this->currentLine)) 76 | { 77 | throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); 78 | } 79 | 80 | $isRef = $isInPlace = $isProcessed = false; 81 | if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) 82 | { 83 | if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) 84 | { 85 | $isRef = $matches['ref']; 86 | $values['value'] = $matches['value']; 87 | } 88 | 89 | // array 90 | if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) 91 | { 92 | $c = $this->getRealCurrentLineNb() + 1; 93 | $parser = new sfYamlParser($c); 94 | $parser->refs =& $this->refs; 95 | $data[] = $parser->parse($this->getNextEmbedBlock()); 96 | } 97 | else 98 | { 99 | if (isset($values['leadspaces']) 100 | && ' ' == $values['leadspaces'] 101 | && preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches)) 102 | { 103 | // this is a compact notation element, add to next block and parse 104 | $c = $this->getRealCurrentLineNb(); 105 | $parser = new sfYamlParser($c); 106 | $parser->refs =& $this->refs; 107 | 108 | $block = $values['value']; 109 | if (!$this->isNextLineIndented()) 110 | { 111 | $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); 112 | } 113 | 114 | $data[] = $parser->parse($block); 115 | } 116 | else 117 | { 118 | $data[] = $this->parseValue($values['value']); 119 | } 120 | } 121 | } 122 | else if (preg_match('#^(?P'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values)) 123 | { 124 | $key = sfYamlInline::parseScalar($values['key']); 125 | 126 | if ('<<' === $key) 127 | { 128 | if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) 129 | { 130 | $isInPlace = substr($values['value'], 1); 131 | if (!array_key_exists($isInPlace, $this->refs)) 132 | { 133 | throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); 134 | } 135 | } 136 | else 137 | { 138 | if (isset($values['value']) && $values['value'] !== '') 139 | { 140 | $value = $values['value']; 141 | } 142 | else 143 | { 144 | $value = $this->getNextEmbedBlock(); 145 | } 146 | $c = $this->getRealCurrentLineNb() + 1; 147 | $parser = new sfYamlParser($c); 148 | $parser->refs =& $this->refs; 149 | $parsed = $parser->parse($value); 150 | 151 | $merged = array(); 152 | if (!is_array($parsed)) 153 | { 154 | 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)); 155 | } 156 | else if (isset($parsed[0])) 157 | { 158 | // Numeric array, merge individual elements 159 | foreach (array_reverse($parsed) as $parsedItem) 160 | { 161 | if (!is_array($parsedItem)) 162 | { 163 | throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); 164 | } 165 | $merged = array_merge($parsedItem, $merged); 166 | } 167 | } 168 | else 169 | { 170 | // Associative array, merge 171 | $merged = array_merge($merge, $parsed); 172 | } 173 | 174 | $isProcessed = $merged; 175 | } 176 | } 177 | else if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) 178 | { 179 | $isRef = $matches['ref']; 180 | $values['value'] = $matches['value']; 181 | } 182 | 183 | if ($isProcessed) 184 | { 185 | // Merge keys 186 | $data = $isProcessed; 187 | } 188 | // hash 189 | else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) 190 | { 191 | // if next line is less indented or equal, then it means that the current value is null 192 | if ($this->isNextLineIndented()) 193 | { 194 | $data[$key] = null; 195 | } 196 | else 197 | { 198 | $c = $this->getRealCurrentLineNb() + 1; 199 | $parser = new sfYamlParser($c); 200 | $parser->refs =& $this->refs; 201 | $data[$key] = $parser->parse($this->getNextEmbedBlock()); 202 | } 203 | } 204 | else 205 | { 206 | if ($isInPlace) 207 | { 208 | $data = $this->refs[$isInPlace]; 209 | } 210 | else 211 | { 212 | $data[$key] = $this->parseValue($values['value']); 213 | } 214 | } 215 | } 216 | else 217 | { 218 | // 1-liner followed by newline 219 | if (2 == count($this->lines) && empty($this->lines[1])) 220 | { 221 | $value = sfYamlInline::load($this->lines[0]); 222 | if (is_array($value)) 223 | { 224 | $first = reset($value); 225 | if ('*' === substr($first, 0, 1)) 226 | { 227 | $data = array(); 228 | foreach ($value as $alias) 229 | { 230 | $data[] = $this->refs[substr($alias, 1)]; 231 | } 232 | $value = $data; 233 | } 234 | } 235 | 236 | if (isset($mbEncoding)) 237 | { 238 | mb_internal_encoding($mbEncoding); 239 | } 240 | 241 | return $value; 242 | } 243 | 244 | switch (preg_last_error()) 245 | { 246 | case PREG_INTERNAL_ERROR: 247 | $error = 'Internal PCRE error on line'; 248 | break; 249 | case PREG_BACKTRACK_LIMIT_ERROR: 250 | $error = 'pcre.backtrack_limit reached on line'; 251 | break; 252 | case PREG_RECURSION_LIMIT_ERROR: 253 | $error = 'pcre.recursion_limit reached on line'; 254 | break; 255 | case PREG_BAD_UTF8_ERROR: 256 | $error = 'Malformed UTF-8 data on line'; 257 | break; 258 | case PREG_BAD_UTF8_OFFSET_ERROR: 259 | $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; 260 | break; 261 | default: 262 | $error = 'Unable to parse line'; 263 | } 264 | 265 | throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); 266 | } 267 | 268 | if ($isRef) 269 | { 270 | $this->refs[$isRef] = end($data); 271 | } 272 | } 273 | 274 | if (isset($mbEncoding)) 275 | { 276 | mb_internal_encoding($mbEncoding); 277 | } 278 | 279 | return empty($data) ? null : $data; 280 | } 281 | 282 | /** 283 | * Returns the current line number (takes the offset into account). 284 | * 285 | * @return integer The current line number 286 | */ 287 | protected function getRealCurrentLineNb() 288 | { 289 | return $this->currentLineNb + $this->offset; 290 | } 291 | 292 | /** 293 | * Returns the current line indentation. 294 | * 295 | * @return integer The current line indentation 296 | */ 297 | protected function getCurrentLineIndentation() 298 | { 299 | return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); 300 | } 301 | 302 | /** 303 | * Returns the next embed block of YAML. 304 | * 305 | * @param integer $indentation The indent level at which the block is to be read, or null for default 306 | * 307 | * @return string A YAML string 308 | */ 309 | protected function getNextEmbedBlock($indentation = null) 310 | { 311 | $this->moveToNextLine(); 312 | 313 | if (null === $indentation) 314 | { 315 | $newIndent = $this->getCurrentLineIndentation(); 316 | 317 | if (!$this->isCurrentLineEmpty() && 0 == $newIndent) 318 | { 319 | throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); 320 | } 321 | } 322 | else 323 | { 324 | $newIndent = $indentation; 325 | } 326 | 327 | $data = array(substr($this->currentLine, $newIndent)); 328 | 329 | while ($this->moveToNextLine()) 330 | { 331 | if ($this->isCurrentLineEmpty()) 332 | { 333 | if ($this->isCurrentLineBlank()) 334 | { 335 | $data[] = substr($this->currentLine, $newIndent); 336 | } 337 | 338 | continue; 339 | } 340 | 341 | $indent = $this->getCurrentLineIndentation(); 342 | 343 | if (preg_match('#^(?P *)$#', $this->currentLine, $match)) 344 | { 345 | // empty line 346 | $data[] = $match['text']; 347 | } 348 | else if ($indent >= $newIndent) 349 | { 350 | $data[] = substr($this->currentLine, $newIndent); 351 | } 352 | else if (0 == $indent) 353 | { 354 | $this->moveToPreviousLine(); 355 | 356 | break; 357 | } 358 | else 359 | { 360 | throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); 361 | } 362 | } 363 | 364 | return implode("\n", $data); 365 | } 366 | 367 | /** 368 | * Moves the parser to the next line. 369 | */ 370 | protected function moveToNextLine() 371 | { 372 | if ($this->currentLineNb >= count($this->lines) - 1) 373 | { 374 | return false; 375 | } 376 | 377 | $this->currentLine = $this->lines[++$this->currentLineNb]; 378 | 379 | return true; 380 | } 381 | 382 | /** 383 | * Moves the parser to the previous line. 384 | */ 385 | protected function moveToPreviousLine() 386 | { 387 | $this->currentLine = $this->lines[--$this->currentLineNb]; 388 | } 389 | 390 | /** 391 | * Parses a YAML value. 392 | * 393 | * @param string $value A YAML value 394 | * 395 | * @return mixed A PHP value 396 | */ 397 | protected function parseValue($value) 398 | { 399 | if ('*' === substr($value, 0, 1)) 400 | { 401 | if (false !== $pos = strpos($value, '#')) 402 | { 403 | $value = substr($value, 1, $pos - 2); 404 | } 405 | else 406 | { 407 | $value = substr($value, 1); 408 | } 409 | 410 | if (!array_key_exists($value, $this->refs)) 411 | { 412 | throw new InvalidArgumentException(sprintf('Reference "%s" does not exist (%s).', $value, $this->currentLine)); 413 | } 414 | return $this->refs[$value]; 415 | } 416 | 417 | if (preg_match('/^(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?$/', $value, $matches)) 418 | { 419 | $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; 420 | 421 | return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); 422 | } 423 | else 424 | { 425 | return sfYamlInline::load($value); 426 | } 427 | } 428 | 429 | /** 430 | * Parses a folded scalar. 431 | * 432 | * @param string $separator The separator that was used to begin this folded scalar (| or >) 433 | * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) 434 | * @param integer $indentation The indentation that was used to begin this folded scalar 435 | * 436 | * @return string The text value 437 | */ 438 | protected function parseFoldedScalar($separator, $indicator = '', $indentation = 0) 439 | { 440 | $separator = '|' == $separator ? "\n" : ' '; 441 | $text = ''; 442 | 443 | $notEOF = $this->moveToNextLine(); 444 | 445 | while ($notEOF && $this->isCurrentLineBlank()) 446 | { 447 | $text .= "\n"; 448 | 449 | $notEOF = $this->moveToNextLine(); 450 | } 451 | 452 | if (!$notEOF) 453 | { 454 | return ''; 455 | } 456 | 457 | if (!preg_match('#^(?P'.($indentation ? str_repeat(' ', $indentation) : ' +').')(?P.*)$#u', $this->currentLine, $matches)) 458 | { 459 | $this->moveToPreviousLine(); 460 | 461 | return ''; 462 | } 463 | 464 | $textIndent = $matches['indent']; 465 | $previousIndent = 0; 466 | 467 | $text .= $matches['text'].$separator; 468 | while ($this->currentLineNb + 1 < count($this->lines)) 469 | { 470 | $this->moveToNextLine(); 471 | 472 | if (preg_match('#^(?P {'.strlen($textIndent).',})(?P.+)$#u', $this->currentLine, $matches)) 473 | { 474 | if (' ' == $separator && $previousIndent != $matches['indent']) 475 | { 476 | $text = substr($text, 0, -1)."\n"; 477 | } 478 | $previousIndent = $matches['indent']; 479 | 480 | $text .= str_repeat(' ', $diff = strlen($matches['indent']) - strlen($textIndent)).$matches['text'].($diff ? "\n" : $separator); 481 | } 482 | else if (preg_match('#^(?P *)$#', $this->currentLine, $matches)) 483 | { 484 | $text .= preg_replace('#^ {1,'.strlen($textIndent).'}#', '', $matches['text'])."\n"; 485 | } 486 | else 487 | { 488 | $this->moveToPreviousLine(); 489 | 490 | break; 491 | } 492 | } 493 | 494 | if (' ' == $separator) 495 | { 496 | // replace last separator by a newline 497 | $text = preg_replace('/ (\n*)$/', "\n$1", $text); 498 | } 499 | 500 | switch ($indicator) 501 | { 502 | case '': 503 | $text = preg_replace('#\n+$#s', "\n", $text); 504 | break; 505 | case '+': 506 | break; 507 | case '-': 508 | $text = preg_replace('#\n+$#s', '', $text); 509 | break; 510 | } 511 | 512 | return $text; 513 | } 514 | 515 | /** 516 | * Returns true if the next line is indented. 517 | * 518 | * @return Boolean Returns true if the next line is indented, false otherwise 519 | */ 520 | protected function isNextLineIndented() 521 | { 522 | $currentIndentation = $this->getCurrentLineIndentation(); 523 | $notEOF = $this->moveToNextLine(); 524 | 525 | while ($notEOF && $this->isCurrentLineEmpty()) 526 | { 527 | $notEOF = $this->moveToNextLine(); 528 | } 529 | 530 | if (false === $notEOF) 531 | { 532 | return false; 533 | } 534 | 535 | $ret = false; 536 | if ($this->getCurrentLineIndentation() <= $currentIndentation) 537 | { 538 | $ret = true; 539 | } 540 | 541 | $this->moveToPreviousLine(); 542 | 543 | return $ret; 544 | } 545 | 546 | /** 547 | * Returns true if the current line is blank or if it is a comment line. 548 | * 549 | * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise 550 | */ 551 | protected function isCurrentLineEmpty() 552 | { 553 | return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); 554 | } 555 | 556 | /** 557 | * Returns true if the current line is blank. 558 | * 559 | * @return Boolean Returns true if the current line is blank, false otherwise 560 | */ 561 | protected function isCurrentLineBlank() 562 | { 563 | return '' == trim($this->currentLine, ' '); 564 | } 565 | 566 | /** 567 | * Returns true if the current line is a comment line. 568 | * 569 | * @return Boolean Returns true if the current line is a comment line, false otherwise 570 | */ 571 | protected function isCurrentLineComment() 572 | { 573 | //checking explicitly the first char of the trim is faster than loops or strpos 574 | $ltrimmedLine = ltrim($this->currentLine, ' '); 575 | return $ltrimmedLine[0] === '#'; 576 | } 577 | 578 | /** 579 | * Cleanups a YAML string to be parsed. 580 | * 581 | * @param string $value The input YAML string 582 | * 583 | * @return string A cleaned up YAML string 584 | */ 585 | protected function cleanup($value) 586 | { 587 | $value = str_replace(array("\r\n", "\r"), "\n", $value); 588 | 589 | if (!preg_match("#\n$#", $value)) 590 | { 591 | $value .= "\n"; 592 | } 593 | 594 | // strip YAML header 595 | $count = 0; 596 | $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); 597 | $this->offset += $count; 598 | 599 | // remove leading comments 600 | $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); 601 | if ($count == 1) 602 | { 603 | // items have been removed, update the offset 604 | $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); 605 | $value = $trimmedValue; 606 | } 607 | 608 | // remove start of the document marker (---) 609 | $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); 610 | if ($count == 1) 611 | { 612 | // items have been removed, update the offset 613 | $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); 614 | $value = $trimmedValue; 615 | 616 | // remove end of the document marker (...) 617 | $value = preg_replace('#\.\.\.\s*$#s', '', $value); 618 | } 619 | 620 | return $value; 621 | } 622 | } 623 | -------------------------------------------------------------------------------- /test/lib/yaml/doc/A-License.markdown: -------------------------------------------------------------------------------- 1 | Appendix A - License 2 | ==================== 3 | 4 | Attribution-Share Alike 3.0 Unported License 5 | -------------------------------------------- 6 | 7 | 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. 8 | 9 | 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. 10 | 11 | 1. Definitions 12 | 13 | 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. 14 | 15 | 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. 16 | 17 | 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. 18 | 19 | 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. 20 | 21 | e. **"License Elements"** means the following high-level license attributes as selected by Licensor and indicated in the title of this License: Attribution, ShareAlike. 22 | 23 | f. **"Licensor"** means the individual, individuals, entity or entities that offer(s) the Work under the terms of this License. 24 | 25 | 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. 26 | 27 | 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. 28 | 29 | 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. 30 | 31 | 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. 32 | 33 | 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. 34 | 35 | 2. Fair Dealing Rights 36 | 37 | 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. 38 | 39 | 3. License Grant 40 | 41 | 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: 42 | 43 | a. to Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections; 44 | 45 | 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."; 46 | 47 | c. to Distribute and Publicly Perform the Work including as incorporated in Collections; and, 48 | 49 | d. to Distribute and Publicly Perform Adaptations. 50 | 51 | e. For the avoidance of doubt: 52 | 53 | 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; 54 | 55 | 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, 56 | 57 | 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. 58 | 59 | 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. 60 | 61 | 4. Restrictions 62 | 63 | The license granted in Section 3 above is expressly made subject to and limited by the following restrictions: 64 | 65 | 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. 66 | 67 | 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. 68 | 69 | 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. 70 | 71 | 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. 72 | 73 | 5. Representations, Warranties and Disclaimer 74 | 75 | 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. 76 | 77 | 6. Limitation on Liability 78 | 79 | 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. 80 | 81 | 7. Termination 82 | 83 | 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. 84 | 85 | 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. 86 | 87 | 8. Miscellaneous 88 | 89 | 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. 90 | 91 | 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. 92 | 93 | 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. 94 | 95 | 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. 96 | 97 | 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. 98 | 99 | 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. 100 | 101 | >**SIDEBAR** 102 | >Creative Commons Notice 103 | > 104 | >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. 105 | > 106 | >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. 107 | > 108 | >Creative Commons may be contacted at http://creativecommons.org/. 109 | -------------------------------------------------------------------------------- /Mustache.php: -------------------------------------------------------------------------------- 1 | false, 26 | MustacheException::UNCLOSED_SECTION => true, 27 | MustacheException::UNEXPECTED_CLOSE_SECTION => true, 28 | MustacheException::UNKNOWN_PARTIAL => false, 29 | MustacheException::UNKNOWN_PRAGMA => true, 30 | ); 31 | 32 | // Override charset passed to htmlentities() and htmlspecialchars(). Defaults to UTF-8. 33 | protected $_charset = 'UTF-8'; 34 | 35 | /** 36 | * Pragmas are macro-like directives that, when invoked, change the behavior or 37 | * syntax of Mustache. 38 | * 39 | * They should be considered extremely experimental. Most likely their implementation 40 | * will change in the future. 41 | */ 42 | 43 | /** 44 | * The {{%UNESCAPED}} pragma swaps the meaning of the {{normal}} and {{{unescaped}}} 45 | * Mustache tags. That is, once this pragma is activated the {{normal}} tag will not be 46 | * escaped while the {{{unescaped}}} tag will be escaped. 47 | * 48 | * Pragmas apply only to the current template. Partials, even those included after the 49 | * {{%UNESCAPED}} call, will need their own pragma declaration. 50 | * 51 | * This may be useful in non-HTML Mustache situations. 52 | */ 53 | const PRAGMA_UNESCAPED = 'UNESCAPED'; 54 | 55 | /** 56 | * Constants used for section and tag RegEx 57 | */ 58 | const SECTION_TYPES = '\^#\/'; 59 | const TAG_TYPES = '#\^\/=!<>\\{&'; 60 | 61 | protected $_otag = '{{'; 62 | protected $_ctag = '}}'; 63 | 64 | protected $_tagRegEx; 65 | 66 | protected $_template = ''; 67 | protected $_context = array(); 68 | protected $_partials = array(); 69 | protected $_pragmas = array(); 70 | 71 | protected $_pragmasImplemented = array( 72 | self::PRAGMA_UNESCAPED 73 | ); 74 | 75 | protected $_localPragmas = array(); 76 | 77 | /** 78 | * Mustache class constructor. 79 | * 80 | * This method accepts a $template string and a $view object. Optionally, pass an associative 81 | * array of partials as well. 82 | * 83 | * Passing an $options array allows overriding certain Mustache options during instantiation: 84 | * 85 | * $options = array( 86 | * // `charset` -- must be supported by `htmlspecialentities()`. defaults to 'UTF-8' 87 | * 'charset' => 'ISO-8859-1', 88 | * 89 | * // opening and closing delimiters, as an array or a space-separated string 90 | * 'delimiters' => '<% %>', 91 | * 92 | * // an array of pragmas to enable 93 | * 'pragmas' => array( 94 | * Mustache::PRAGMA_UNESCAPED 95 | * ), 96 | * ); 97 | * 98 | * @access public 99 | * @param string $template (default: null) 100 | * @param mixed $view (default: null) 101 | * @param array $partials (default: null) 102 | * @param array $options (default: array()) 103 | * @return void 104 | */ 105 | public function __construct($template = null, $view = null, $partials = null, array $options = null) { 106 | if ($template !== null) $this->_template = $template; 107 | if ($partials !== null) $this->_partials = $partials; 108 | if ($view !== null) $this->_context = array($view); 109 | if ($options !== null) $this->_setOptions($options); 110 | } 111 | 112 | /** 113 | * Helper function for setting options from constructor args. 114 | * 115 | * @access protected 116 | * @param array $options 117 | * @return void 118 | */ 119 | protected function _setOptions(array $options) { 120 | if (isset($options['charset'])) { 121 | $this->_charset = $options['charset']; 122 | } 123 | 124 | if (isset($options['delimiters'])) { 125 | $delims = $options['delimiters']; 126 | if (!is_array($delims)) { 127 | $delims = array_map('trim', explode(' ', $delims, 2)); 128 | } 129 | $this->_otag = $delims[0]; 130 | $this->_ctag = $delims[1]; 131 | } 132 | 133 | if (isset($options['pragmas'])) { 134 | foreach ($options['pragmas'] as $pragma_name) { 135 | if (!in_array($pragma_name, $this->_pragmasImplemented)) { 136 | throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); 137 | } 138 | } 139 | $this->_pragmas = $options['pragmas']; 140 | } 141 | } 142 | 143 | /** 144 | * Mustache class clone method. 145 | * 146 | * A cloned Mustache instance should have pragmas, delimeters and root context 147 | * reset to default values. 148 | * 149 | * @access public 150 | * @return void 151 | */ 152 | public function __clone() { 153 | $this->_otag = '{{'; 154 | $this->_ctag = '}}'; 155 | $this->_localPragmas = array(); 156 | 157 | if ($keys = array_keys($this->_context)) { 158 | $last = array_pop($keys); 159 | if ($this->_context[$last] instanceof Mustache) { 160 | $this->_context[$last] =& $this; 161 | } 162 | } 163 | } 164 | 165 | /** 166 | * Render the given template and view object. 167 | * 168 | * Defaults to the template and view passed to the class constructor unless a new one is provided. 169 | * Optionally, pass an associative array of partials as well. 170 | * 171 | * @access public 172 | * @param string $template (default: null) 173 | * @param mixed $view (default: null) 174 | * @param array $partials (default: null) 175 | * @return string Rendered Mustache template. 176 | */ 177 | public function render($template = null, $view = null, $partials = null) { 178 | if ($template === null) $template = $this->_template; 179 | if ($partials !== null) $this->_partials = $partials; 180 | 181 | $otag_orig = $this->_otag; 182 | $ctag_orig = $this->_ctag; 183 | 184 | if ($view) { 185 | $this->_context = array($view); 186 | } else if (empty($this->_context)) { 187 | $this->_context = array($this); 188 | } 189 | 190 | $template = $this->_renderPragmas($template); 191 | $template = $this->_renderTemplate($template, $this->_context); 192 | 193 | $this->_otag = $otag_orig; 194 | $this->_ctag = $ctag_orig; 195 | 196 | return $template; 197 | } 198 | 199 | /** 200 | * Wrap the render() function for string conversion. 201 | * 202 | * @access public 203 | * @return string 204 | */ 205 | public function __toString() { 206 | // PHP doesn't like exceptions in __toString. 207 | // catch any exceptions and convert them to strings. 208 | try { 209 | $result = $this->render(); 210 | return $result; 211 | } catch (Exception $e) { 212 | return "Error rendering mustache: " . $e->getMessage(); 213 | } 214 | } 215 | 216 | /** 217 | * Internal render function, used for recursive calls. 218 | * 219 | * @access protected 220 | * @param string $template 221 | * @return string Rendered Mustache template. 222 | */ 223 | protected function _renderTemplate($template) { 224 | if ($section = $this->_findSection($template)) { 225 | list($before, $type, $tag_name, $content, $after) = $section; 226 | 227 | $rendered_before = $this->_renderTags($before); 228 | 229 | $rendered_content = ''; 230 | $val = $this->_getVariable($tag_name); 231 | switch($type) { 232 | // inverted section 233 | case '^': 234 | if (empty($val)) { 235 | $rendered_content = $this->_renderTemplate($content); 236 | } 237 | break; 238 | 239 | // regular section 240 | case '#': 241 | if ($this->_varIsIterable($val)) { 242 | foreach ($val as $local_context) { 243 | $this->_pushContext($local_context); 244 | $rendered_content .= $this->_renderTemplate($content); 245 | $this->_popContext(); 246 | } 247 | } else if ($val) { 248 | if (is_array($val) || is_object($val)) { 249 | $this->_pushContext($val); 250 | $rendered_content = $this->_renderTemplate($content); 251 | $this->_popContext(); 252 | } else { 253 | $rendered_content = $this->_renderTemplate($content); 254 | } 255 | } 256 | break; 257 | } 258 | 259 | return $rendered_before . $rendered_content . $this->_renderTemplate($after); 260 | } 261 | 262 | return $this->_renderTags($template); 263 | } 264 | 265 | /** 266 | * Prepare a section RegEx string for the given opening/closing tags. 267 | * 268 | * @access protected 269 | * @param string $otag 270 | * @param string $ctag 271 | * @return string 272 | */ 273 | protected function _prepareSectionRegEx($otag, $ctag) { 274 | return sprintf( 275 | '/(?:(?<=\\n)[ \\t]*)?%s(?:(?P[%s])(?P.+?)|=(?P.*?)=)%s\\n?/s', 276 | preg_quote($otag, '/'), 277 | self::SECTION_TYPES, 278 | preg_quote($ctag, '/') 279 | ); 280 | } 281 | 282 | /** 283 | * Extract the first section from $template. 284 | * 285 | * @access protected 286 | * @param string $template 287 | * @return array $before, $type, $tag_name, $content and $after 288 | */ 289 | protected function _findSection($template) { 290 | $regEx = $this->_prepareSectionRegEx($this->_otag, $this->_ctag); 291 | 292 | $section_start = null; 293 | $section_type = null; 294 | $content_start = null; 295 | 296 | $search_offset = 0; 297 | 298 | $section_stack = array(); 299 | $matches = array(); 300 | while (preg_match($regEx, $template, $matches, PREG_OFFSET_CAPTURE, $search_offset)) { 301 | if (isset($matches['delims'][0])) { 302 | list($otag, $ctag) = explode(' ', $matches['delims'][0]); 303 | $regEx = $this->_prepareSectionRegEx($otag, $ctag); 304 | $search_offset = $matches[0][1] + strlen($matches[0][0]); 305 | continue; 306 | } 307 | 308 | $match = $matches[0][0]; 309 | $offset = $matches[0][1]; 310 | $type = $matches['type'][0]; 311 | $tag_name = trim($matches['tag_name'][0]); 312 | 313 | $search_offset = $offset + strlen($match); 314 | 315 | switch ($type) { 316 | case '^': 317 | case '#': 318 | if (empty($section_stack)) { 319 | $section_start = $offset; 320 | $section_type = $type; 321 | $content_start = $search_offset; 322 | } 323 | array_push($section_stack, $tag_name); 324 | break; 325 | case '/': 326 | if (empty($section_stack) || ($tag_name !== array_pop($section_stack))) { 327 | if ($this->_throwsException(MustacheException::UNEXPECTED_CLOSE_SECTION)) { 328 | throw new MustacheException('Unexpected close section: ' . $tag_name, MustacheException::UNEXPECTED_CLOSE_SECTION); 329 | } 330 | } 331 | 332 | if (empty($section_stack)) { 333 | // $before, $type, $tag_name, $content, $after 334 | return array( 335 | substr($template, 0, $section_start), 336 | $section_type, 337 | $tag_name, 338 | substr($template, $content_start, $offset - $content_start), 339 | substr($template, $search_offset), 340 | ); 341 | } 342 | break; 343 | } 344 | } 345 | 346 | if (!empty($section_stack)) { 347 | if ($this->_throwsException(MustacheException::UNCLOSED_SECTION)) { 348 | throw new MustacheException('Unclosed section: ' . $section_stack[0], MustacheException::UNCLOSED_SECTION); 349 | } 350 | } 351 | } 352 | 353 | /** 354 | * Prepare a pragma RegEx for the given opening/closing tags. 355 | * 356 | * @access protected 357 | * @param string $otag 358 | * @param string $ctag 359 | * @return string 360 | */ 361 | protected function _preparePragmaRegEx($otag, $ctag) { 362 | return sprintf( 363 | '/%s%%\\s*(?P[\\w_-]+)(?P(?: [\\w]+=[\\w]+)*)\\s*%s\\n?/s', 364 | preg_quote($otag, '/'), 365 | preg_quote($ctag, '/') 366 | ); 367 | } 368 | 369 | /** 370 | * Initialize pragmas and remove all pragma tags. 371 | * 372 | * @access protected 373 | * @param string $template 374 | * @return string 375 | */ 376 | protected function _renderPragmas($template) { 377 | $this->_localPragmas = $this->_pragmas; 378 | 379 | // no pragmas 380 | if (strpos($template, $this->_otag . '%') === false) { 381 | return $template; 382 | } 383 | 384 | $regEx = $this->_preparePragmaRegEx($this->_otag, $this->_ctag); 385 | return preg_replace_callback($regEx, array($this, '_renderPragma'), $template); 386 | } 387 | 388 | /** 389 | * A preg_replace helper to remove {{%PRAGMA}} tags and enable requested pragma. 390 | * 391 | * @access protected 392 | * @param mixed $matches 393 | * @return void 394 | * @throws MustacheException unknown pragma 395 | */ 396 | protected function _renderPragma($matches) { 397 | $pragma = $matches[0]; 398 | $pragma_name = $matches['pragma_name']; 399 | $options_string = $matches['options_string']; 400 | 401 | if (!in_array($pragma_name, $this->_pragmasImplemented)) { 402 | throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); 403 | } 404 | 405 | $options = array(); 406 | foreach (explode(' ', trim($options_string)) as $o) { 407 | if ($p = trim($o)) { 408 | $p = explode('=', $p); 409 | $options[$p[0]] = $p[1]; 410 | } 411 | } 412 | 413 | if (empty($options)) { 414 | $this->_localPragmas[$pragma_name] = true; 415 | } else { 416 | $this->_localPragmas[$pragma_name] = $options; 417 | } 418 | 419 | return ''; 420 | } 421 | 422 | /** 423 | * Check whether this Mustache has a specific pragma. 424 | * 425 | * @access protected 426 | * @param string $pragma_name 427 | * @return bool 428 | */ 429 | protected function _hasPragma($pragma_name) { 430 | if (array_key_exists($pragma_name, $this->_localPragmas) && $this->_localPragmas[$pragma_name]) { 431 | return true; 432 | } else { 433 | return false; 434 | } 435 | } 436 | 437 | /** 438 | * Return pragma options, if any. 439 | * 440 | * @access protected 441 | * @param string $pragma_name 442 | * @return mixed 443 | * @throws MustacheException Unknown pragma 444 | */ 445 | protected function _getPragmaOptions($pragma_name) { 446 | if (!$this->_hasPragma($pragma_name)) { 447 | throw new MustacheException('Unknown pragma: ' . $pragma_name, MustacheException::UNKNOWN_PRAGMA); 448 | } 449 | 450 | return (is_array($this->_localPragmas[$pragma_name])) ? $this->_localPragmas[$pragma_name] : array(); 451 | } 452 | 453 | /** 454 | * Check whether this Mustache instance throws a given exception. 455 | * 456 | * Expects exceptions to be MustacheException error codes (i.e. class constants). 457 | * 458 | * @access protected 459 | * @param mixed $exception 460 | * @return void 461 | */ 462 | protected function _throwsException($exception) { 463 | return (isset($this->_throwsExceptions[$exception]) && $this->_throwsExceptions[$exception]); 464 | } 465 | 466 | /** 467 | * Prepare a tag RegEx for the given opening/closing tags. 468 | * 469 | * @access protected 470 | * @param string $otag 471 | * @param string $ctag 472 | * @return string 473 | */ 474 | protected function _prepareTagRegEx($otag, $ctag, $first = false) { 475 | return sprintf( 476 | '/(?P(?:%s\\r?\\n)[ \\t]*)?%s(?P[%s]?)(?P.+?)(?:\\2|})?%s(?P\\s*(?:\\r?\\n|\\Z))?/s', 477 | ($first ? '\\A|' : ''), 478 | preg_quote($otag, '/'), 479 | self::TAG_TYPES, 480 | preg_quote($ctag, '/') 481 | ); 482 | } 483 | 484 | /** 485 | * Loop through and render individual Mustache tags. 486 | * 487 | * @access protected 488 | * @param string $template 489 | * @return void 490 | */ 491 | protected function _renderTags($template) { 492 | if (strpos($template, $this->_otag) === false) { 493 | return $template; 494 | } 495 | 496 | $first = true; 497 | $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag, true); 498 | 499 | $html = ''; 500 | $matches = array(); 501 | while (preg_match($this->_tagRegEx, $template, $matches, PREG_OFFSET_CAPTURE)) { 502 | $tag = $matches[0][0]; 503 | $offset = $matches[0][1]; 504 | $modifier = $matches['type'][0]; 505 | $tag_name = trim($matches['tag_name'][0]); 506 | 507 | if (isset($matches['leading']) && $matches['leading'][1] > -1) { 508 | $leading = $matches['leading'][0]; 509 | } else { 510 | $leading = null; 511 | } 512 | 513 | if (isset($matches['trailing']) && $matches['trailing'][1] > -1) { 514 | $trailing = $matches['trailing'][0]; 515 | } else { 516 | $trailing = null; 517 | } 518 | 519 | $html .= substr($template, 0, $offset); 520 | 521 | $next_offset = $offset + strlen($tag); 522 | if ((substr($html, -1) == "\n") && (substr($template, $next_offset, 1) == "\n")) { 523 | $next_offset++; 524 | } 525 | $template = substr($template, $next_offset); 526 | 527 | $html .= $this->_renderTag($modifier, $tag_name, $leading, $trailing); 528 | 529 | if ($first == true) { 530 | $first = false; 531 | $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); 532 | } 533 | } 534 | 535 | return $html . $template; 536 | } 537 | 538 | /** 539 | * Render the named tag, given the specified modifier. 540 | * 541 | * Accepted modifiers are `=` (change delimiter), `!` (comment), `>` (partial) 542 | * `{` or `&` (don't escape output), or none (render escaped output). 543 | * 544 | * @access protected 545 | * @param string $modifier 546 | * @param string $tag_name 547 | * @param string $leading Whitespace 548 | * @param string $trailing Whitespace 549 | * @throws MustacheException Unmatched section tag encountered. 550 | * @return string 551 | */ 552 | protected function _renderTag($modifier, $tag_name, $leading, $trailing) { 553 | switch ($modifier) { 554 | case '=': 555 | return $this->_changeDelimiter($tag_name, $leading, $trailing); 556 | break; 557 | case '!': 558 | return $this->_renderComment($tag_name, $leading, $trailing); 559 | break; 560 | case '>': 561 | case '<': 562 | return $this->_renderPartial($tag_name, $leading, $trailing); 563 | break; 564 | case '{': 565 | // strip the trailing } ... 566 | if ($tag_name[(strlen($tag_name) - 1)] == '}') { 567 | $tag_name = substr($tag_name, 0, -1); 568 | } 569 | case '&': 570 | if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { 571 | return $this->_renderEscaped($tag_name, $leading, $trailing); 572 | } else { 573 | return $this->_renderUnescaped($tag_name, $leading, $trailing); 574 | } 575 | break; 576 | case '#': 577 | case '^': 578 | case '/': 579 | // remove any leftover section tags 580 | return $leading . $trailing; 581 | break; 582 | default: 583 | if ($this->_hasPragma(self::PRAGMA_UNESCAPED)) { 584 | return $this->_renderUnescaped($modifier . $tag_name, $leading, $trailing); 585 | } else { 586 | return $this->_renderEscaped($modifier . $tag_name, $leading, $trailing); 587 | } 588 | break; 589 | } 590 | } 591 | 592 | /** 593 | * Returns true if any of its args contains the "\r" character. 594 | * 595 | * @access protected 596 | * @param string $str 597 | * @return boolean 598 | */ 599 | protected function _stringHasR($str) { 600 | foreach (func_get_args() as $arg) { 601 | if (strpos($arg, "\r") !== false) { 602 | return true; 603 | } 604 | } 605 | return false; 606 | } 607 | 608 | /** 609 | * Escape and return the requested tag. 610 | * 611 | * @access protected 612 | * @param string $tag_name 613 | * @param string $leading Whitespace 614 | * @param string $trailing Whitespace 615 | * @return string 616 | */ 617 | protected function _renderEscaped($tag_name, $leading, $trailing) { 618 | return $leading . htmlentities($this->_getVariable($tag_name), ENT_COMPAT, $this->_charset) . $trailing; 619 | } 620 | 621 | /** 622 | * Render a comment (i.e. return an empty string). 623 | * 624 | * @access protected 625 | * @param string $tag_name 626 | * @param string $leading Whitespace 627 | * @param string $trailing Whitespace 628 | * @return string 629 | */ 630 | protected function _renderComment($tag_name, $leading, $trailing) { 631 | if ($leading !== null && $trailing !== null) { 632 | if (strpos($leading, "\n") === false) { 633 | return ''; 634 | } 635 | return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; 636 | } 637 | return $leading . $trailing; 638 | } 639 | 640 | /** 641 | * Return the requested tag unescaped. 642 | * 643 | * @access protected 644 | * @param string $tag_name 645 | * @param string $leading Whitespace 646 | * @param string $trailing Whitespace 647 | * @return string 648 | */ 649 | protected function _renderUnescaped($tag_name, $leading, $trailing) { 650 | return $leading . $this->_getVariable($tag_name) . $trailing; 651 | } 652 | 653 | /** 654 | * Render the requested partial. 655 | * 656 | * @access protected 657 | * @param string $tag_name 658 | * @param string $leading Whitespace 659 | * @param string $trailing Whitespace 660 | * @return string 661 | */ 662 | protected function _renderPartial($tag_name, $leading, $trailing) { 663 | $partial = $this->_getPartial($tag_name); 664 | if ($leading !== null && $trailing !== null) { 665 | $whitespace = trim($leading, "\r\n"); 666 | $partial = preg_replace('/(\\r?\\n)(?!$)/s', "\\1" . $whitespace, $partial); 667 | } 668 | 669 | $view = clone($this); 670 | 671 | if ($leading !== null && $trailing !== null) { 672 | return $leading . $view->render($partial); 673 | } else { 674 | return $leading . $view->render($partial) . $trailing; 675 | } 676 | } 677 | 678 | /** 679 | * Change the Mustache tag delimiter. This method also replaces this object's current 680 | * tag RegEx with one using the new delimiters. 681 | * 682 | * @access protected 683 | * @param string $tag_name 684 | * @param string $leading Whitespace 685 | * @param string $trailing Whitespace 686 | * @return string 687 | */ 688 | protected function _changeDelimiter($tag_name, $leading, $trailing) { 689 | list($otag, $ctag) = explode(' ', $tag_name); 690 | $this->_otag = $otag; 691 | $this->_ctag = $ctag; 692 | 693 | $this->_tagRegEx = $this->_prepareTagRegEx($this->_otag, $this->_ctag); 694 | 695 | if ($leading !== null && $trailing !== null) { 696 | if (strpos($leading, "\n") === false) { 697 | return ''; 698 | } 699 | return $this->_stringHasR($leading, $trailing) ? "\r\n" : "\n"; 700 | } 701 | return $leading . $trailing; 702 | } 703 | 704 | /** 705 | * Push a local context onto the stack. 706 | * 707 | * @access protected 708 | * @param array &$local_context 709 | * @return void 710 | */ 711 | protected function _pushContext(&$local_context) { 712 | $new = array(); 713 | $new[] =& $local_context; 714 | foreach (array_keys($this->_context) as $key) { 715 | $new[] =& $this->_context[$key]; 716 | } 717 | $this->_context = $new; 718 | } 719 | 720 | /** 721 | * Remove the latest context from the stack. 722 | * 723 | * @access protected 724 | * @return void 725 | */ 726 | protected function _popContext() { 727 | $new = array(); 728 | 729 | $keys = array_keys($this->_context); 730 | array_shift($keys); 731 | foreach ($keys as $key) { 732 | $new[] =& $this->_context[$key]; 733 | } 734 | $this->_context = $new; 735 | } 736 | 737 | /** 738 | * Get a variable from the context array. 739 | * 740 | * If the view is an array, returns the value with array key $tag_name. 741 | * If the view is an object, this will check for a public member variable 742 | * named $tag_name. If none is available, this method will execute and return 743 | * any class method named $tag_name. Failing all of the above, this method will 744 | * return an empty string. 745 | * 746 | * @access protected 747 | * @param string $tag_name 748 | * @throws MustacheException Unknown variable name. 749 | * @return string 750 | */ 751 | protected function _getVariable($tag_name) { 752 | if ($tag_name === '.') { 753 | return $this->_context[0]; 754 | } else if (strpos($tag_name, '.') !== false) { 755 | $chunks = explode('.', $tag_name); 756 | $first = array_shift($chunks); 757 | 758 | $ret = $this->_findVariableInContext($first, $this->_context); 759 | while ($next = array_shift($chunks)) { 760 | // Slice off a chunk of context for dot notation traversal. 761 | $c = array($ret); 762 | $ret = $this->_findVariableInContext($next, $c); 763 | } 764 | return $ret; 765 | } else { 766 | return $this->_findVariableInContext($tag_name, $this->_context); 767 | } 768 | } 769 | 770 | /** 771 | * Get a variable from the context array. Internal helper used by getVariable() to abstract 772 | * variable traversal for dot notation. 773 | * 774 | * @access protected 775 | * @param string $tag_name 776 | * @param array $context 777 | * @throws MustacheException Unknown variable name. 778 | * @return string 779 | */ 780 | protected function _findVariableInContext($tag_name, $context) { 781 | foreach ($context as $view) { 782 | if (is_object($view)) { 783 | if (method_exists($view, $tag_name)) { 784 | return $view->$tag_name(); 785 | } else if (isset($view->$tag_name)) { 786 | return $view->$tag_name; 787 | } 788 | } else if (is_array($view) && array_key_exists($tag_name, $view)) { 789 | return $view[$tag_name]; 790 | } 791 | } 792 | 793 | if ($this->_throwsException(MustacheException::UNKNOWN_VARIABLE)) { 794 | throw new MustacheException("Unknown variable: " . $tag_name, MustacheException::UNKNOWN_VARIABLE); 795 | } else { 796 | return ''; 797 | } 798 | } 799 | 800 | /** 801 | * Retrieve the partial corresponding to the requested tag name. 802 | * 803 | * Silently fails (i.e. returns '') when the requested partial is not found. 804 | * 805 | * @access protected 806 | * @param string $tag_name 807 | * @throws MustacheException Unknown partial name. 808 | * @return string 809 | */ 810 | protected function _getPartial($tag_name) { 811 | if (is_array($this->_partials) && isset($this->_partials[$tag_name])) { 812 | return $this->_partials[$tag_name]; 813 | } 814 | 815 | if ($this->_throwsException(MustacheException::UNKNOWN_PARTIAL)) { 816 | throw new MustacheException('Unknown partial: ' . $tag_name, MustacheException::UNKNOWN_PARTIAL); 817 | } else { 818 | return ''; 819 | } 820 | } 821 | 822 | /** 823 | * Check whether the given $var should be iterated (i.e. in a section context). 824 | * 825 | * @access protected 826 | * @param mixed $var 827 | * @return bool 828 | */ 829 | protected function _varIsIterable($var) { 830 | return $var instanceof Traversable || (is_array($var) && !array_diff_key($var, array_keys(array_keys($var)))); 831 | } 832 | } 833 | 834 | 835 | /** 836 | * MustacheException class. 837 | * 838 | * @extends Exception 839 | */ 840 | class MustacheException extends Exception { 841 | 842 | // An UNKNOWN_VARIABLE exception is thrown when a {{variable}} is not found 843 | // in the current context. 844 | const UNKNOWN_VARIABLE = 0; 845 | 846 | // An UNCLOSED_SECTION exception is thrown when a {{#section}} is not closed. 847 | const UNCLOSED_SECTION = 1; 848 | 849 | // An UNEXPECTED_CLOSE_SECTION exception is thrown when {{/section}} appears 850 | // without a corresponding {{#section}} or {{^section}}. 851 | const UNEXPECTED_CLOSE_SECTION = 2; 852 | 853 | // An UNKNOWN_PARTIAL exception is thrown whenever a {{>partial}} tag appears 854 | // with no associated partial. 855 | const UNKNOWN_PARTIAL = 3; 856 | 857 | // An UNKNOWN_PRAGMA exception is thrown whenever a {{%PRAGMA}} tag appears 858 | // which can't be handled by this Mustache instance. 859 | const UNKNOWN_PRAGMA = 4; 860 | 861 | } 862 | 863 | --------------------------------------------------------------------------------