Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Jannis Grimm
2011-07-25 22:32:17 +02:00
21 changed files with 556 additions and 23 deletions
+8
View File
@@ -1,3 +1,11 @@
* 1.1.2
Changes:
* fixed output when a macro throws an exception
* fixed a parsing problem when a large chunk of text is enclosed in a comment tag
* added PHPDoc for all Token parsers and Core extension functions
* 1.1.1 (2011-07-17)
Changes:
+304 -11
View File
@@ -182,6 +182,14 @@ class Twig_Extension_Core extends Twig_Extension
}
}
/**
* Cycles over a value.
*
* @param ArrayAccess|array $values An array or an ArrayAccess instance
* @param integer $i The cycle value
*
* @return string The next value in the cycle
*/
function twig_cycle($values, $i)
{
if (!is_array($values) && !$values instanceof ArrayAccess) {
@@ -191,6 +199,19 @@ function twig_cycle($values, $i)
return $values[$i % count($values)];
}
/**
* Converts a date to the given format.
*
* <pre>
* {{ post.published_at|date("m/d/Y") }}
* </pre>
*
* @param DateTime|string $date A date
* @param string $format A format
* @param DateTimeZone|string $timezone A timezone
*
* @return string The formatter date
*/
function twig_date_format_filter($date, $format = 'F j, Y H:i', $timezone = null)
{
if (!$date instanceof DateTime) {
@@ -213,6 +234,14 @@ function twig_date_format_filter($date, $format = 'F j, Y H:i', $timezone = null
return $date->format($format);
}
/**
* URL encodes a string.
*
* @param string $url A URL
* @param bool $raw true to use rawurlencode() instead of urlencode
*
* @return string The URL encoded value
*/
function twig_urlencode_filter($url, $raw = false)
{
if ($raw) {
@@ -222,6 +251,14 @@ function twig_urlencode_filter($url, $raw = false)
return urlencode($url);
}
/**
* JSON encodes a PHP variable.
*
* @param mixed $value The value to encode.
* @param integer $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
*
* @return mixed The JSON encoded value
*/
function twig_jsonencode_filter($value, $options = 0)
{
if ($value instanceof Twig_Markup) {
@@ -240,6 +277,22 @@ function _twig_markup2string(&$value)
}
}
/**
* Merges an array with another one.
*
* <pre>
* {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
*
* {% set items = items|merge({ 'peugeot': 'car' }) %}
*
* {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
* </pre>
*
* @param array $arr1 An array
* @param array $arr2 An array
*
* @return array The merged array
*/
function twig_array_merge($arr1, $arr2)
{
if (!is_array($arr1) || !is_array($arr2)) {
@@ -249,16 +302,67 @@ function twig_array_merge($arr1, $arr2)
return array_merge($arr1, $arr2);
}
/**
* Joins the values to a string.
*
* The separator between elements is an empty string per default, you can define it with the optional parameter.
*
* <pre>
* {{ [1, 2, 3]|join('|') }}
* {# returns 1|2|3 #}
*
* {{ [1, 2, 3]|join }}
* {# returns 123 #}
* </pre>
*
* @param array $value An array
* @param string $glue The separator
*
* @return string The concatenated string
*/
function twig_join_filter($value, $glue = '')
{
return implode($glue, (array) $value);
}
/**
* Returns the value or the default value when it is undefined or empty.
*
* <pre>
*
* {{ var.foo|default('foo item on var is not defined') }}
*
* </pre>
*
* @param mixed $value A value
* @param mixed $default The default value
*
* @param mixed The value or the default value;
*/
function twig_default_filter($value, $default = '')
{
return twig_test_empty($value) ? $default : $value;
if (twig_test_empty($value)) {
return $default;
} else {
return $value;
}
}
/**
* Returns the keys for the given array.
*
* It is useful when you want to iterate over the keys of an array:
*
* <pre>
* {% for key in array|keys %}
* {# ... #}
* {% endfor %}
* </pre>
*
* @param array $array An array
*
* @return array The keys
*/
function twig_get_array_keys_filter($array)
{
if (is_object($array) && $array instanceof Traversable) {
@@ -272,6 +376,13 @@ function twig_get_array_keys_filter($array)
return array_keys($array);
}
/**
* Reverses an array.
*
* @param array|Traversable $array An array or a Traversable instance
*
* return array The array reversed
*/
function twig_reverse_filter($array)
{
if (is_object($array) && $array instanceof Traversable) {
@@ -285,6 +396,11 @@ function twig_reverse_filter($array)
return array_reverse($array);
}
/**
* Sorts an array.
*
* @param array $array An array
*/
function twig_sort_filter($array)
{
asort($array);
@@ -292,6 +408,7 @@ function twig_sort_filter($array)
return $array;
}
/* used internally */
function twig_in_filter($value, $compare)
{
if (is_array($compare)) {
@@ -305,22 +422,30 @@ function twig_in_filter($value, $compare)
return false;
}
/**
* Replaces placeholders in a string.
*
* <pre>
* {{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }}
* </pre>
*
* @param string $pattern A string
* @param string $replacements The values for the placeholders
*
* @return string The string where the placeholders have been replaced
*/
function twig_strtr($pattern, $replacements)
{
return str_replace(array_keys($replacements), array_values($replacements), $pattern);
}
/*
* Each type specifies a way for applying a transformation to a string
* The purpose is for the string to be "escaped" so it is suitable for
* the format it is being displayed in.
/**
* Escapes a string.
*
* For example, the string: "It's required that you enter a username & password.\n"
* If this were to be displayed as HTML it would be sensible to turn the
* ampersand into '&amp;' and the apostrophe into '&aps;'. However if it were
* going to be used as a string in JavaScript to be displayed in an alert box
* it would be right to leave the string as-is, but c-escape the apostrophe and
* the new line.
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string The value to be escaped
* @param string $type The escaping strategy
* @param string $charset The charset
*/
function twig_escape_filter(Twig_Environment $env, $string, $type = 'html', $charset = null)
{
@@ -362,6 +487,7 @@ function twig_escape_filter(Twig_Environment $env, $string, $type = 'html', $cha
}
}
/* used internally */
function twig_escape_filter_is_safe(Twig_Node $filterArgs)
{
foreach ($filterArgs as $arg) {
@@ -411,11 +537,27 @@ function _twig_escape_js_callback($matches)
// add multibyte extensions if possible
if (function_exists('mb_get_info')) {
/**
* Returns the length of a PHP variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $thing A PHP variable
*
* @return integer The length of the value
*/
function twig_length_filter(Twig_Environment $env, $thing)
{
return is_scalar($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing);
}
/**
* Converts a string to uppercase.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The uppercased string
*/
function twig_upper_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
@@ -425,6 +567,14 @@ if (function_exists('mb_get_info')) {
return strtoupper($string);
}
/**
* Converts a string to lowercase.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The lowercased string
*/
function twig_lower_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
@@ -434,6 +584,14 @@ if (function_exists('mb_get_info')) {
return strtolower($string);
}
/**
* Returns a titlecased string.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The titlecased string
*/
function twig_title_string_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
@@ -443,6 +601,14 @@ if (function_exists('mb_get_info')) {
return ucwords(strtolower($string));
}
/**
* Returns a capitalized string.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The capitalized string
*/
function twig_capitalize_string_filter(Twig_Environment $env, $string)
{
if (null !== ($charset = $env->getCharset())) {
@@ -456,22 +622,47 @@ if (function_exists('mb_get_info')) {
// and byte fallback
else
{
/**
* Returns the length of a PHP variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $thing A PHP variable
*
* @return integer The length of the value
*/
function twig_length_filter(Twig_Environment $env, $thing)
{
return is_scalar($thing) ? strlen($thing) : count($thing);
}
/**
* Returns a titlecased string.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The titlecased string
*/
function twig_title_string_filter(Twig_Environment $env, $string)
{
return ucwords(strtolower($string));
}
/**
* Returns a capitalized string.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string A string
*
* @return string The capitalized string
*/
function twig_capitalize_string_filter(Twig_Environment $env, $string)
{
return ucfirst(strtolower($string));
}
}
/* used internally */
function twig_ensure_traversable($seq)
{
if (is_array($seq) || (is_object($seq) && $seq instanceof Traversable)) {
@@ -481,41 +672,143 @@ function twig_ensure_traversable($seq)
}
}
/**
* Checks that a variable points to the same memory address than another one.
*
* <pre>
* {% if foo.attribute is sameas(false) %}
* the foo attribute really is the ``false`` PHP value
* {% endif %}
* </pre>
*
* @param mixed $value A PHP variable
* @param mixed $test The PHP variable to test against
*
* @return Boolean true if the values are the same, false otherwise
*/
function twig_test_sameas($value, $test)
{
return $value === $test;
}
/**
* Checks that a variable is null.
*
* <pre>
* {{ var is none }}
* </pre>
*
* @param mixed $value a PHP variable.
*
* @return Boolean true if the value is null, false otherwise
*/
function twig_test_none($value)
{
return null === $value;
}
/**
* Checks if a variable is divisible by a number.
*
* <pre>
* {% if loop.index is divisibleby(3) %}
* </pre>
*
* @param integer $value A PHP value
* @param integer $num A number
*
* @return Boolean true if the value is divisible by the number, false otherwise
*/
function twig_test_divisibleby($value, $num)
{
return 0 == $value % $num;
}
/**
* Checks if a number is even.
*
* <pre>
* {{ var is even }}
* </pre>
*
* @param integer $value An integer
*
* @return Boolean true if the value is even, false otherwise
*/
function twig_test_even($value)
{
return $value % 2 == 0;
}
/**
* Checks if a number is odd.
*
* <pre>
* {{ var is odd }}
* </pre>
*
* @param integer $value An integer
*
* @return Boolean true if the value is odd, false otherwise
*/
function twig_test_odd($value)
{
return $value % 2 == 1;
}
/**
* Checks if a variable is the exact same value as a constant.
*
* <pre>
* {% if post.status is constant('Post::PUBLISHED') %}
* the status attribute is exactly the same as Post::PUBLISHED
* {% endif %}
* </pre>
*
* @param mixed $value A PHP value
* @param mixed $constant The constant to test against
*
* @return Boolean true if the value is the same as the constant, false otherwise
*/
function twig_test_constant($value, $constant)
{
return constant($constant) === $value;
}
/**
* Checks if a variable is defined in the current context.
*
* <pre>
* {# defined works with variable names #}
* {% if foo is defined %}
* {# ... #}
* {% endif %}
* </pre>
*
* @param mixed $name A PHP variable
* @param array $context The current context
*
* @return Boolean true if the value is defined, false otherwise
*/
function twig_test_defined($name, $context)
{
return array_key_exists($name, $context);
}
/**
* Checks if a variable is empty.
*
* <pre>
* {# evaluates to true if the foo variable is null, false, or the empty string #}
* {% if foo is empty %}
* {# ... #}
* {% endif %}
* </pre>
*
* @param mixed $value A PHP variable
*
* @return Boolean true if the value is empty, false otherwise
*/
function twig_test_empty($value)
{
return false === $value || (empty($value) && '0' != $value);
+5 -1
View File
@@ -65,7 +65,11 @@ class Twig_Extension_Escaper extends Twig_Extension
}
}
// tells the escaper node visitor that the string is safe
/**
* Marks a variable as being safe.
*
* @param string $string A PHP variable
*/
function twig_raw_filter($string)
{
return $string;
+14 -9
View File
@@ -145,15 +145,7 @@ class Twig_Lexer implements Twig_LexerInterface
switch ($token) {
case $this->options['tag_comment'][0]:
$commentEndRegex = '/.*?(?:'.preg_quote($this->options['whitespace_trim'], '/')
.preg_quote($this->options['tag_comment'][1], '/').'\s*|'
.preg_quote($this->options['tag_comment'][1], '/').')\n?/As';
if (!preg_match($commentEndRegex, $this->code, $match, null, $this->cursor)) {
throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
}
$this->moveCursor($match[0]);
$this->lexComment();
break;
case $this->options['tag_block'][0]:
@@ -276,6 +268,19 @@ class Twig_Lexer implements Twig_LexerInterface
$this->moveCursor($text.$match[0][0]);
}
protected function lexComment()
{
$commentEndRegex = '/(?:'.preg_quote($this->options['whitespace_trim'], '/')
.preg_quote($this->options['tag_comment'][1], '/').'\s*|'
.preg_quote($this->options['tag_comment'][1], '/').')\n?/s';
if (!preg_match($commentEndRegex, $this->code, $match, PREG_OFFSET_CAPTURE, $this->cursor)) {
throw new Twig_Error_Syntax('Unclosed comment', $this->lineno, $this->filename);
}
$this->moveCursor(substr($this->code, $this->cursor, $match[0][1] - $this->cursor).$match[0][0]);
}
protected function pushToken($type, $value = '')
{
// do not push empty text tokens
+9 -1
View File
@@ -55,8 +55,16 @@ class Twig_Node_Macro extends Twig_Node
->outdent()
->write("));\n\n")
->write("ob_start();\n")
->write("try {\n")
->indent()
->subcompile($this->getNode('body'))
->raw("\n")
->outdent()
->write("} catch(Exception \$e) {\n")
->indent()
->write("ob_end_clean();\n\n")
->write("throw \$e;\n")
->outdent()
->write("}\n\n")
->write("return ob_get_clean();\n")
->outdent()
->write("}\n\n")
+19
View File
@@ -8,6 +8,25 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Marks a section of a template to be escaped or not.
*
* <pre>
* {% autoescape true %}
* Everything will be automatically escaped in this block
* {% endautoescape %}
*
* {% autoescape false %}
* Everything will be outputed as is in this block
* {% endautoescape %}
*
* {% autoescape true js %}
* Everything will be automatically escaped in this block
* using the js escaping strategy
* {% endautoescape %}
* </pre>
*/
class Twig_TokenParser_AutoEscape extends Twig_TokenParser
{
/**
+11
View File
@@ -9,6 +9,17 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Marks a section of a template as being reusable.
*
* <pre>
* {% block head %}
* <link rel="stylesheet" href="style.css" />
* <title>{% block title %}{% endblock %} - My Webpage</title>
* {% endblock %}
* </pre>
*/
class Twig_TokenParser_Block extends Twig_TokenParser
{
/**
+8
View File
@@ -9,6 +9,14 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Extends a template by another one.
*
* <pre>
* {% extends "base.html" %}
* </pre>
*/
class Twig_TokenParser_Extends extends Twig_TokenParser
{
/**
+10
View File
@@ -8,6 +8,16 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Filters a section of a template by applying filters.
*
* <pre>
* {% filter upper %}
* This text becomes uppercase
* {% endfilter %}
* </pre>
*/
class Twig_TokenParser_Filter extends Twig_TokenParser
{
/**
+12
View File
@@ -9,6 +9,18 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Loops over each item of a sequence.
*
* <pre>
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
* </pre>
*/
class Twig_TokenParser_For extends Twig_TokenParser
{
/**
+8
View File
@@ -8,6 +8,14 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Imports macros.
*
* <pre>
* {% from 'forms.html' import forms %}
* </pre>
*/
class Twig_TokenParser_From extends Twig_TokenParser
{
/**
+14
View File
@@ -9,6 +9,20 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Tests a condition.
*
* <pre>
* {% if users %}
* <ul>
* {% for user in users %}
* <li>{{ user.username|e }}</li>
* {% endfor %}
* </ul>
* {% endif %}
* </pre>
*/
class Twig_TokenParser_If extends Twig_TokenParser
{
/**
+8
View File
@@ -8,6 +8,14 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Imports macros.
*
* <pre>
* {% import 'forms.html' as forms %}
* </pre>
*/
class Twig_TokenParser_Import extends Twig_TokenParser
{
/**
+10
View File
@@ -9,6 +9,16 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Includes a template.
*
* <pre>
* {% include 'header.html' %}
* Body
* {% include 'footer.html' %}
* </pre>
*/
class Twig_TokenParser_Include extends Twig_TokenParser
{
/**
+10
View File
@@ -8,6 +8,16 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Defines a macro.
*
* <pre>
* {% macro input(name, value, type, size) %}
* <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
* {% endmacro %}
* </pre>
*/
class Twig_TokenParser_Macro extends Twig_TokenParser
{
/**
+12
View File
@@ -8,6 +8,18 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Marks a section of a template as untrusted code that must be evaluated in the sandbox mode.
*
* <pre>
* {% sandbox %}
* {% include 'user.html' %}
* {% endsandbox %}
* </pre>
*
* @see http://www.twig-project.org/doc/api.html#sandbox-extension for details
*/
class Twig_TokenParser_Sandbox extends Twig_TokenParser
{
/**
+18
View File
@@ -8,6 +8,24 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Defines a variable.
*
* <pre>
* {% set foo = 'foo' %}
*
* {% set foo = [1, 2] %}
*
* {% set foo = {'foo': 'bar'} %}
*
* {% set foo = 'foo' ~ 'bar' %}
*
* {% set foo, bar = 'foo', 'bar' %}
*
* {% set foo %}Some content{% endset %}
* </pre>
*/
class Twig_TokenParser_Set extends Twig_TokenParser
{
/**
+14
View File
@@ -8,6 +8,20 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Remove whitespaces between HTML tags.
*
* <pre>
* {% spaceless %}
* <div>
* <strong>foo</strong>
* </div>
* {% endspaceless %}
*
* {# output will be <div><strong>foo</strong></div> #}
* </pre>
*/
class Twig_TokenParser_Spaceless extends Twig_TokenParser
{
/**
+15
View File
@@ -8,6 +8,21 @@
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Imports blocks defined in another template into the current template.
*
* <pre>
* {% extends "base.html" %}
*
* {% use "blocks.html" %}
*
* {% block title %}{% endblock %}
* {% block content %}{% endblock %}
* </pre>
*
* @see http://www.twig-project.org/doc/templates.html#horizontal-reuse for details.
*/
class Twig_TokenParser_Use extends Twig_TokenParser
{
/**
+40
View File
@@ -76,4 +76,44 @@ class Twig_Tests_LexerTest extends PHPUnit_Framework_TestCase
// baz
$this->assertSame(11, $stream->expect(Twig_Token::NAME_TYPE)->getLine());
}
public function testLongComments()
{
$template = '{# '.str_repeat('*', 100000).' #}';
$lexer = new Twig_Lexer(new Twig_Environment());
$lexer->tokenize($template);
// should not throw an exception
}
public function testLongRaw()
{
$template = '{% raw %}'.str_repeat('*', 100000).'{% endraw %}';
$lexer = new Twig_Lexer(new Twig_Environment());
$stream = $lexer->tokenize($template);
// should not throw an exception
}
public function testLongBlock()
{
$template = '{{ '.str_repeat('*', 100000).' }}';
$lexer = new Twig_Lexer(new Twig_Environment());
$stream = $lexer->tokenize($template);
// should not throw an exception
}
public function testLongBlock1()
{
$template = '{% '.str_repeat('*', 100000).' %}';
$lexer = new Twig_Lexer(new Twig_Environment());
$stream = $lexer->tokenize($template);
// should not throw an exception
}
}
+7 -1
View File
@@ -51,7 +51,13 @@ public function getfoo(\$foo = null)
));
ob_start();
echo "foo";
try {
echo "foo";
} catch(Exception \$e) {
ob_end_clean();
throw \$e;
}
return ob_get_clean();
}