ier string
*
* @return DateTime A new date object
*/
function twig_date_modify_filter(Twig_Environment $env, $date, $modifier)
{
$date = twig_date_converter($env, $date, false);
$date->modify($modifier);
return $date;
}
/**
* Converts an input to a DateTime instance.
*
*
* {% if date(user.created_at) < date('+2days') %}
* {# do something #}
* {% endif %}
*
*
* @param Twig_Environment $env A Twig_Environment instance
* @param DateTime|string $date A date
* @param DateTimeZone|string $timezone A timezone
*
* @return DateTime A DateTime instance
*/
function twig_date_converter(Twig_Environment $env, $date = null, $timezone = null)
{
// determine the timezone
if (!$timezone) {
$defaultTimezone = $env->getExtension('core')->getTimezone();
} elseif (!$timezone instanceof DateTimeZone) {
$defaultTimezone = new DateTimeZone($timezone);
} else {
$defaultTimezone = $timezone;
}
if ($date instanceof DateTime || $date instanceof DateTimeInterface) {
$returningDate = new DateTime($date->format('c'));
if (false !== $timezone) {
$returningDate->setTimezone($defaultTimezone);
} else {
$returningDate->setTimezone($date->getTimezone());
}
return $returningDate;
}
$asString = (string) $date;
if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString, 1)))) {
$date = '@'.$date;
}
$date = new DateTime($date, $defaultTimezone);
if (false !== $timezone) {
$date->setTimezone($defaultTimezone);
}
return $date;
}
/**
* Number format filter.
*
* All of the formatting options can be left null, in that case the defaults will
* be used. Supplying any of the parameters will override the defaults set in the
* environment object.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $number A float/int/string of the number to format
* @param integer $decimal The number of decimal points to display.
* @param string $decimalPoint The character(s) to use for the decimal point.
* @param string $thousandSep The character(s) to use for the thousands separator.
*
* @return string The formatted number
*/
function twig_number_format_filter(Twig_Environment $env, $number, $decimal = null, $decimalPoint = null, $thousandSep = null)
{
$defaults = $env->getExtension('core')->getNumberFormat();
if (null === $decimal) {
$decimal = $defaults[0];
}
if (null === $decimalPoint) {
$decimalPoint = $defaults[1];
}
if (null === $thousandSep) {
$thousandSep = $defaults[2];
}
return number_format((float) $number, $decimal, $decimalPoint, $thousandSep);
}
/**
* URL encodes a string as a path segment or an array as a query string.
*
* @param string|array $url A URL or an array of query parameters
* @param bool $raw true to use rawurlencode() instead of urlencode
*
* @return string The URL encoded value
*/
function twig_urlencode_filter($url, $raw = false)
{
if (is_array($url)) {
return http_build_query($url, '', '&');
}
if ($raw) {
return rawurlencode($url);
}
return urlencode($url);
}
if (version_compare(PHP_VERSION, '5.3.0', '<')) {
/**
* JSON encodes a variable.
*
* @param mixed $value The value to encode.
* @param integer $options Not used on PHP 5.2.x
*
* @return mixed The JSON encoded value
*/
function twig_jsonencode_filter($value, $options = 0)
{
if ($value instanceof Twig_Markup) {
$value = (string) $value;
} elseif (is_array($value)) {
array_walk_recursive($value, '_twig_markup2string');
}
return json_encode($value);
}
} else {
/**
* JSON encodes a 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) {
$value = (string) $value;
} elseif (is_array($value)) {
array_walk_recursive($value, '_twig_markup2string');
}
return json_encode($value, $options);
}
}
function _twig_markup2string(&$value)
{
if ($value instanceof Twig_Markup) {
$value = (string) $value;
}
}
/**
* Merges an array with another one.
*
*
* {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
*
* {% set items = items|merge({ 'peugeot': 'car' }) %}
*
* {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
*
*
* @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)) {
throw new Twig_Error_Runtime('The merge filter only works with arrays or hashes.');
}
return array_merge($arr1, $arr2);
}
/**
* Slices a variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $item A variable
* @param integer $start Start of the slice
* @param integer $length Size of the slice
* @param Boolean $preserveKeys Whether to preserve key or not (when the input is an array)
*
* @return mixed The sliced variable
*/
function twig_slice(Twig_Environment $env, $item, $start, $length = null, $preserveKeys = false)
{
if (is_object($item) && $item instanceof Traversable) {
$item = iterator_to_array($item, false);
}
if (is_array($item)) {
return array_slice($item, $start, $length, $preserveKeys);
}
$item = (string) $item;
if (function_exists('mb_get_info') && null !== $charset = $env->getCharset()) {
return mb_substr($item, $start, null === $length ? mb_strlen($item, $charset) - $start : $length, $charset);
}
return null === $length ? substr($item, $start) : substr($item, $start, $length);
}
/**
* Returns the first element of the item.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $item A variable
*
* @return mixed The first element of the item
*/
function twig_first(Twig_Environment $env, $item)
{
$elements = twig_slice($env, $item, 0, 1, false);
return is_string($elements) ? $elements[0] : current($elements);
}
/**
* Returns the last element of the item.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $item A variable
*
* @return mixed The last element of the item
*/
function twig_last(Twig_Environment $env, $item)
{
$elements = twig_slice($env, $item, -1, 1, false);
return is_string($elements) ? $elements[0] : current($elements);
}
/**
* Joins the values to a string.
*
* The separator between elements is an empty string per default, you can define it with the optional parameter.
*
*
* {{ [1, 2, 3]|join('|') }}
* {# returns 1|2|3 #}
*
* {{ [1, 2, 3]|join }}
* {# returns 123 #}
*
*
* @param array $value An array
* @param string $glue The separator
*
* @return string The concatenated string
*/
function twig_join_filter($value, $glue = '')
{
if (is_object($value) && $value instanceof Traversable) {
$value = iterator_to_array($value, false);
}
return implode($glue, (array) $value);
}
/**
* Splits the string into an array.
*
*
* {{ "one,two,three"|split(',') }}
* {# returns [one, two, three] #}
*
* {{ "one,two,three,four,five"|split(',', 3) }}
* {# returns [one, two, "three,four,five"] #}
*
* {{ "123"|split('') }}
* {# returns [1, 2, 3] #}
*
* {{ "aabbcc"|split('', 2) }}
* {# returns [aa, bb, cc] #}
*
*
* @param string $value A string
* @param string $delimiter The delimiter
* @param integer $limit The limit
*
* @return array The split string as an array
*/
function twig_split_filter($value, $delimiter, $limit = null)
{
if (empty($delimiter)) {
return str_split($value, null === $limit ? 1 : $limit);
}
return null === $limit ? explode($delimiter, $value) : explode($delimiter, $value, $limit);
}
// The '_default' filter is used internally to avoid using the ternary operator
// which costs a lot for big contexts (before PHP 5.4). So, on average,
// a function call is cheaper.
function _twig_default_filter($value, $default = '')
{
if (twig_test_empty($value)) {
return $default;
}
return $value;
}
/**
* Returns the keys for the given array.
*
* It is useful when you want to iterate over the keys of an array:
*
*
* {% for key in array|keys %}
* {# ... #}
* {% endfor %}
*
*
* @param array $array An array
*
* @return array The keys
*/
function twig_get_array_keys_filter($array)
{
if (is_object($array) && $array instanceof Traversable) {
return array_keys(iterator_to_array($array));
}
if (!is_array($array)) {
return array();
}
return array_keys($array);
}
/**
* Reverses a variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param array|Traversable|string $item An array, a Traversable instance, or a string
* @param Boolean $preserveKeys Whether to preserve key or not
*
* @return mixed The reversed input
*/
function twig_reverse_filter(Twig_Environment $env, $item, $preserveKeys = false)
{
if (is_object($item) && $item instanceof Traversable) {
return array_reverse(iterator_to_array($item), $preserveKeys);
}
if (is_array($item)) {
return array_reverse($item, $preserveKeys);
}
if (null !== $charset = $env->getCharset()) {
$string = (string) $item;
if ('UTF-8' != $charset) {
$item = twig_convert_encoding($string, 'UTF-8', $charset);
}
preg_match_all('/./us', $item, $matches);
$string = implode('', array_reverse($matches[0]));
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, $charset, 'UTF-8');
}
return $string;
}
return strrev((string) $item);
}
/**
* Sorts an array.
*
* @param array $array An array
*/
function twig_sort_filter($array)
{
asort($array);
return $array;
}
/* used internally */
function twig_in_filter($value, $compare)
{
if (is_array($compare)) {
return in_array($value, $compare, is_object($value));
} elseif (is_string($compare)) {
if (!strlen($value)) {
return empty($compare);
}
return false !== strpos($compare, (string) $value);
} elseif (is_object($compare) && $compare instanceof Traversable) {
return in_array($value, iterator_to_array($compare, false), is_object($value));
}
return false;
}
/**
* Escapes a string.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param string $string The value to be escaped
* @param string $strategy The escaping strategy
* @param string $charset The charset
* @param Boolean $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false)
*/
function twig_escape_filter(Twig_Environment $env, $string, $strategy = 'html', $charset = null, $autoescape = false)
{
if ($autoescape && $string instanceof Twig_Markup) {
return $string;
}
if (!is_string($string)) {
if (is_object($string) && method_exists($string, '__toString')) {
$string = (string) $string;
} else {
return $string;
}
}
if (null === $charset) {
$charset = $env->getCharset();
}
switch ($strategy) {
case 'html':
// see http://php.net/htmlspecialchars
// Using a static variable to avoid initializing the array
// each time the function is called. Moving the declaration on the
// top of the function slow downs other escaping strategies.
static $htmlspecialcharsCharsets;
if (null === $htmlspecialcharsCharsets) {
if ('hiphop' === substr(PHP_VERSION, -6)) {
$htmlspecialcharsCharsets = array('utf-8' => true, 'UTF-8' => true);
} else {
$htmlspecialcharsCharsets = array(
'ISO-8859-1' => true, 'ISO8859-1' => true,
'ISO-8859-15' => true, 'ISO8859-15' => true,
'utf-8' => true, 'UTF-8' => true,
'CP866' => true, 'IBM866' => true, '866' => true,
'CP1251' => true, 'WINDOWS-1251' => true, 'WIN-1251' => true,
'1251' => true,
'CP1252' => true, 'WINDOWS-1252' => true, '1252' => true,
'KOI8-R' => true, 'KOI8-RU' => true, 'KOI8R' => true,
'BIG5' => true, '950' => true,
'GB2312' => true, '936' => true,
'BIG5-HKSCS' => true,
'SHIFT_JIS' => true, 'SJIS' => true, '932' => true,
'EUC-JP' => true, 'EUCJP' => true,
'ISO8859-5' => true, 'ISO-8859-5' => true, 'MACROMAN' => true,
);
}
}
if (isset($htmlspecialcharsCharsets[$charset])) {
return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
}
if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
// cache the lowercase variant for future iterations
$htmlspecialcharsCharsets[$charset] = true;
return htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, $charset);
}
$string = twig_convert_encoding($string, 'UTF-8', $charset);
$string = htmlspecialchars($string, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
return twig_convert_encoding($string, $charset, 'UTF-8');
case 'js':
// escape all non-alphanumeric characters
// into their \xHH or \uHHHH representations
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', '_twig_escape_js_callback', $string);
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, $charset, 'UTF-8');
}
return $string;
case 'css':
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9]#Su', '_twig_escape_css_callback', $string);
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, $charset, 'UTF-8');
}
return $string;
case 'html_attr':
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, 'UTF-8', $charset);
}
if (0 == strlen($string) ? false : (1 == preg_match('/^./su', $string) ? false : true)) {
throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
}
$string = preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', '_twig_escape_html_attr_callback', $string);
if ('UTF-8' != $charset) {
$string = twig_convert_encoding($string, $charset, 'UTF-8');
}
return $string;
case 'url':
// hackish test to avoid version_compare that is much slower, this works unless PHP releases a 5.10.*
// at that point however PHP 5.2.* support can be removed
if (PHP_VERSION < '5.3.0') {
return str_replace('%7E', '~', rawurlencode($string));
}
return rawurlencode($string);
default:
static $escapers;
if (null === $escapers) {
$escapers = $env->getExtension('core')->getEscapers();
}
if (isset($escapers[$strategy])) {
return call_user_func($escapers[$strategy], $env, $string, $charset);
}
$validStrategies = implode(', ', array_merge(array('html', 'js', 'url', 'css', 'html_attr'), array_keys($escapers)));
throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: %s).', $strategy, $validStrategies));
}
}
/* used internally */
function twig_escape_filter_is_safe(Twig_Node $filterArgs)
{
foreach ($filterArgs as $arg) {
if ($arg instanceof Twig_Node_Expression_Constant) {
return array($arg->getAttribute('value'));
}
return array();
}
return array('html');
}
if (function_exists('mb_convert_encoding')) {
function twig_convert_encoding($string, $to, $from)
{
return mb_convert_encoding($string, $to, $from);
}
} elseif (function_exists('iconv')) {
function twig_convert_encoding($string, $to, $from)
{
return iconv($from, $to, $string);
}
} else {
function twig_convert_encoding($string, $to, $from)
{
throw new Twig_Error_Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
}
}
function _twig_escape_js_callback($matches)
{
$char = $matches[0];
// \xHH
if (!isset($char[1])) {
return '\\x'.strtoupper(substr('00'.bin2hex($char), -2));
}
// \uHHHH
$char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
return '\\u'.strtoupper(substr('0000'.bin2hex($char), -4));
}
function _twig_escape_css_callback($matches)
{
$char = $matches[0];
// \xHH
if (!isset($char[1])) {
$hex = ltrim(strtoupper(bin2hex($char)), '0');
if (0 === strlen($hex)) {
$hex = '0';
}
return '\\'.$hex.' ';
}
// \uHHHH
$char = twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' ';
}
/**
* This function is adapted from code coming from Zend Framework.
*
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
function _twig_escape_html_attr_callback($matches)
{
/*
* While HTML supports far more named entities, the lowest common denominator
* has become HTML5's XML Serialisation which is restricted to the those named
* entities that XML supports. Using HTML entities would result in this error:
* XML Parsing Error: undefined entity
*/
static $entityMap = array(
34 => 'quot', /* quotation mark */
38 => 'amp', /* ampersand */
60 => 'lt', /* less-than sign */
62 => 'gt', /* greater-than sign */
);
$chr = $matches[0];
$ord = ord($chr);
/**
* The following replaces characters undefined in HTML with the
* hex entity for the Unicode replacement character.
*/
if (($ord <= 0x1f && $chr != "\t" && $chr != "\n" && $chr != "\r") || ($ord >= 0x7f && $ord <= 0x9f)) {
return '�';
}
/**
* Check if the current character to escape has a name entity we should
* replace it with while grabbing the hex value of the character.
*/
if (strlen($chr) == 1) {
$hex = strtoupper(substr('00'.bin2hex($chr), -2));
} else {
$chr = twig_convert_encoding($chr, 'UTF-16BE', 'UTF-8');
$hex = strtoupper(substr('0000'.bin2hex($chr), -4));
}
$int = hexdec($hex);
if (array_key_exists($int, $entityMap)) {
return sprintf('&%s;', $entityMap[$int]);
}
/**
* Per OWASP recommendations, we'll use hex entities for any other
* characters where a named entity does not exist.
*/
return sprintf('%s;', $hex);
}
// add multibyte extensions if possible
if (function_exists('mb_get_info')) {
/**
* Returns the length of a variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $thing A 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())) {
return mb_strtoupper($string, $charset);
}
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())) {
return mb_strtolower($string, $charset);
}
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())) {
return mb_convert_case($string, MB_CASE_TITLE, $charset);
}
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())) {
return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).
mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
}
return ucfirst(strtolower($string));
}
}
// and byte fallback
else {
/**
* Returns the length of a variable.
*
* @param Twig_Environment $env A Twig_Environment instance
* @param mixed $thing A 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 ($seq instanceof Traversable || is_array($seq)) {
return $seq;
}
return array();
}
/**
* Checks if a variable is empty.
*
*
* {# evaluates to true if the foo variable is null, false, or the empty string #}
* {% if foo is empty %}
* {# ... #}
* {% endif %}
*
*
* @param mixed $value A variable
*
* @return Boolean true if the value is empty, false otherwise
*/
function twig_test_empty($value)
{
if ($value instanceof Countable) {
return 0 == count($value);
}
return '' === $value || false === $value || null === $value || array() === $value;
}
/**
* Checks if a variable is traversable.
*
*
* {# evaluates to true if the foo variable is an array or a traversable object #}
* {% if foo is traversable %}
* {# ... #}
* {% endif %}
*
*
* @param mixed $value A variable
*
* @return Boolean true if the value is traversable
*/
function twig_test_iterable($value)
{
return $value instanceof Traversable || is_array($value);
}
/**
* Renders a template.
*
* @param string|array $template The template to render or an array of templates to try consecutively
* @param array $variables The variables to pass to the template
* @param Boolean $with_context Whether to pass the current context variables or not
* @param Boolean $ignore_missing Whether to ignore missing templates or not
* @param Boolean $sandboxed Whether to sandbox the template or not
*
* @return string The rendered template
*/
function twig_include(Twig_Environment $env, $context, $template, $variables = array(), $withContext = true, $ignoreMissing = false, $sandboxed = false)
{
if ($withContext) {
$variables = array_merge($context, $variables);
}
if ($isSandboxed = $sandboxed && $env->hasExtension('sandbox')) {
$sandbox = $env->getExtension('sandbox');
if (!$alreadySandboxed = $sandbox->isSandboxed()) {
$sandbox->enableSandbox();
}
}
try {
return $env->resolveTemplate($template)->render($variables);
} catch (Twig_Error_Loader $e) {
if (!$ignoreMissing) {
throw $e;
}
}
if ($isSandboxed && !$alreadySandboxed) {
$sandbox->disableSandbox();
}
}
/**
* Provides the ability to get constants from instances as well as class/global constants.
*
* @param string $constant The name of the constant
* @param null|object $object The object to get the constant from
*
* @return string
*/
function twig_constant($constant, $object = null)
{
if (null !== $object) {
$constant = get_class($object).'::'.$constant;
}
return constant($constant);
}
/**
* Batches item.
*
* @param array $items An array of items
* @param integer $size The size of the batch
* @param mixed $fill A value used to fill missing items
*
* @return array
*/
function twig_array_batch($items, $size, $fill = null)
{
if (is_object($items) && $items instanceof Traversable) {
$items = iterator_to_array($items, false);
}
$size = ceil($size);
$result = array_chunk($items, $size, true);
if (null !== $fill) {
$last = count($result) - 1;
if ($fillCount = $size - count($result[$last])) {
$result[$last] = array_merge(
$result[$last],
array_fill(0, $fillCount, $fill)
);
}
}
return $result;
}