vendor/twig/twig/lib/Twig/Extension/Core.php line 1326

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of Twig.
  4.  *
  5.  * (c) Fabien Potencier
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. final class Twig_Extension_Core extends Twig_Extension
  11. {
  12.     private $dateFormats = array('F j, Y H:i''%d days');
  13.     private $numberFormat = array(0'.'',');
  14.     private $timezone null;
  15.     private $escapers = array();
  16.     /**
  17.      * Defines a new escaper to be used via the escape filter.
  18.      *
  19.      * @param string   $strategy The strategy name that should be used as a strategy in the escape call
  20.      * @param callable $callable A valid PHP callable
  21.      */
  22.     public function setEscaper($strategy, callable $callable)
  23.     {
  24.         $this->escapers[$strategy] = $callable;
  25.     }
  26.     /**
  27.      * Gets all defined escapers.
  28.      *
  29.      * @return callable[] An array of escapers
  30.      */
  31.     public function getEscapers()
  32.     {
  33.         return $this->escapers;
  34.     }
  35.     /**
  36.      * Sets the default format to be used by the date filter.
  37.      *
  38.      * @param string $format             The default date format string
  39.      * @param string $dateIntervalFormat The default date interval format string
  40.      */
  41.     public function setDateFormat($format null$dateIntervalFormat null)
  42.     {
  43.         if (null !== $format) {
  44.             $this->dateFormats[0] = $format;
  45.         }
  46.         if (null !== $dateIntervalFormat) {
  47.             $this->dateFormats[1] = $dateIntervalFormat;
  48.         }
  49.     }
  50.     /**
  51.      * Gets the default format to be used by the date filter.
  52.      *
  53.      * @return array The default date format string and the default date interval format string
  54.      */
  55.     public function getDateFormat()
  56.     {
  57.         return $this->dateFormats;
  58.     }
  59.     /**
  60.      * Sets the default timezone to be used by the date filter.
  61.      *
  62.      * @param DateTimeZone|string $timezone The default timezone string or a DateTimeZone object
  63.      */
  64.     public function setTimezone($timezone)
  65.     {
  66.         $this->timezone $timezone instanceof DateTimeZone $timezone : new DateTimeZone($timezone);
  67.     }
  68.     /**
  69.      * Gets the default timezone to be used by the date filter.
  70.      *
  71.      * @return DateTimeZone The default timezone currently in use
  72.      */
  73.     public function getTimezone()
  74.     {
  75.         if (null === $this->timezone) {
  76.             $this->timezone = new DateTimeZone(date_default_timezone_get());
  77.         }
  78.         return $this->timezone;
  79.     }
  80.     /**
  81.      * Sets the default format to be used by the number_format filter.
  82.      *
  83.      * @param int    $decimal      the number of decimal places to use
  84.      * @param string $decimalPoint the character(s) to use for the decimal point
  85.      * @param string $thousandSep  the character(s) to use for the thousands separator
  86.      */
  87.     public function setNumberFormat($decimal$decimalPoint$thousandSep)
  88.     {
  89.         $this->numberFormat = array($decimal$decimalPoint$thousandSep);
  90.     }
  91.     /**
  92.      * Get the default format used by the number_format filter.
  93.      *
  94.      * @return array The arguments for number_format()
  95.      */
  96.     public function getNumberFormat()
  97.     {
  98.         return $this->numberFormat;
  99.     }
  100.     public function getTokenParsers()
  101.     {
  102.         return array(
  103.             new Twig_TokenParser_For(),
  104.             new Twig_TokenParser_If(),
  105.             new Twig_TokenParser_Extends(),
  106.             new Twig_TokenParser_Include(),
  107.             new Twig_TokenParser_Block(),
  108.             new Twig_TokenParser_Use(),
  109.             new Twig_TokenParser_Filter(),
  110.             new Twig_TokenParser_Macro(),
  111.             new Twig_TokenParser_Import(),
  112.             new Twig_TokenParser_From(),
  113.             new Twig_TokenParser_Set(),
  114.             new Twig_TokenParser_Spaceless(),
  115.             new Twig_TokenParser_Flush(),
  116.             new Twig_TokenParser_Do(),
  117.             new Twig_TokenParser_Embed(),
  118.             new Twig_TokenParser_With(),
  119.         );
  120.     }
  121.     public function getFilters()
  122.     {
  123.         return array(
  124.             // formatting filters
  125.             new Twig_Filter('date''twig_date_format_filter', array('needs_environment' => true)),
  126.             new Twig_Filter('date_modify''twig_date_modify_filter', array('needs_environment' => true)),
  127.             new Twig_Filter('format''sprintf'),
  128.             new Twig_Filter('replace''twig_replace_filter'),
  129.             new Twig_Filter('number_format''twig_number_format_filter', array('needs_environment' => true)),
  130.             new Twig_Filter('abs''abs'),
  131.             new Twig_Filter('round''twig_round'),
  132.             // encoding
  133.             new Twig_Filter('url_encode''twig_urlencode_filter'),
  134.             new Twig_Filter('json_encode''json_encode'),
  135.             new Twig_Filter('convert_encoding''twig_convert_encoding'),
  136.             // string filters
  137.             new Twig_Filter('title''twig_title_string_filter', array('needs_environment' => true)),
  138.             new Twig_Filter('capitalize''twig_capitalize_string_filter', array('needs_environment' => true)),
  139.             new Twig_Filter('upper''twig_upper_filter', array('needs_environment' => true)),
  140.             new Twig_Filter('lower''twig_lower_filter', array('needs_environment' => true)),
  141.             new Twig_Filter('striptags''strip_tags'),
  142.             new Twig_Filter('trim''twig_trim_filter'),
  143.             new Twig_Filter('nl2br''nl2br', array('pre_escape' => 'html''is_safe' => array('html'))),
  144.             // array helpers
  145.             new Twig_Filter('join''twig_join_filter'),
  146.             new Twig_Filter('split''twig_split_filter', array('needs_environment' => true)),
  147.             new Twig_Filter('sort''twig_sort_filter'),
  148.             new Twig_Filter('merge''twig_array_merge'),
  149.             new Twig_Filter('batch''twig_array_batch'),
  150.             // string/array filters
  151.             new Twig_Filter('reverse''twig_reverse_filter', array('needs_environment' => true)),
  152.             new Twig_Filter('length''twig_length_filter', array('needs_environment' => true)),
  153.             new Twig_Filter('slice''twig_slice', array('needs_environment' => true)),
  154.             new Twig_Filter('first''twig_first', array('needs_environment' => true)),
  155.             new Twig_Filter('last''twig_last', array('needs_environment' => true)),
  156.             // iteration and runtime
  157.             new Twig_Filter('default''_twig_default_filter', array('node_class' => 'Twig_Node_Expression_Filter_Default')),
  158.             new Twig_Filter('keys''twig_get_array_keys_filter'),
  159.             // escaping
  160.             new Twig_Filter('escape''twig_escape_filter', array('needs_environment' => true'is_safe_callback' => 'twig_escape_filter_is_safe')),
  161.             new Twig_Filter('e''twig_escape_filter', array('needs_environment' => true'is_safe_callback' => 'twig_escape_filter_is_safe')),
  162.         );
  163.     }
  164.     public function getFunctions()
  165.     {
  166.         return array(
  167.             new Twig_Function('max''max'),
  168.             new Twig_Function('min''min'),
  169.             new Twig_Function('range''range'),
  170.             new Twig_Function('constant''twig_constant'),
  171.             new Twig_Function('cycle''twig_cycle'),
  172.             new Twig_Function('random''twig_random', array('needs_environment' => true)),
  173.             new Twig_Function('date''twig_date_converter', array('needs_environment' => true)),
  174.             new Twig_Function('include''twig_include', array('needs_environment' => true'needs_context' => true'is_safe' => array('all'))),
  175.             new Twig_Function('source''twig_source', array('needs_environment' => true'is_safe' => array('all'))),
  176.         );
  177.     }
  178.     public function getTests()
  179.     {
  180.         return array(
  181.             new Twig_Test('even'null, array('node_class' => 'Twig_Node_Expression_Test_Even')),
  182.             new Twig_Test('odd'null, array('node_class' => 'Twig_Node_Expression_Test_Odd')),
  183.             new Twig_Test('defined'null, array('node_class' => 'Twig_Node_Expression_Test_Defined')),
  184.             new Twig_Test('same as'null, array('node_class' => 'Twig_Node_Expression_Test_Sameas')),
  185.             new Twig_Test('none'null, array('node_class' => 'Twig_Node_Expression_Test_Null')),
  186.             new Twig_Test('null'null, array('node_class' => 'Twig_Node_Expression_Test_Null')),
  187.             new Twig_Test('divisible by'null, array('node_class' => 'Twig_Node_Expression_Test_Divisibleby')),
  188.             new Twig_Test('constant'null, array('node_class' => 'Twig_Node_Expression_Test_Constant')),
  189.             new Twig_Test('empty''twig_test_empty'),
  190.             new Twig_Test('iterable''twig_test_iterable'),
  191.         );
  192.     }
  193.     public function getOperators()
  194.     {
  195.         return array(
  196.             array(
  197.                 'not' => array('precedence' => 50'class' => 'Twig_Node_Expression_Unary_Not'),
  198.                 '-' => array('precedence' => 500'class' => 'Twig_Node_Expression_Unary_Neg'),
  199.                 '+' => array('precedence' => 500'class' => 'Twig_Node_Expression_Unary_Pos'),
  200.             ),
  201.             array(
  202.                 'or' => array('precedence' => 10'class' => 'Twig_Node_Expression_Binary_Or''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  203.                 'and' => array('precedence' => 15'class' => 'Twig_Node_Expression_Binary_And''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  204.                 'b-or' => array('precedence' => 16'class' => 'Twig_Node_Expression_Binary_BitwiseOr''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  205.                 'b-xor' => array('precedence' => 17'class' => 'Twig_Node_Expression_Binary_BitwiseXor''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  206.                 'b-and' => array('precedence' => 18'class' => 'Twig_Node_Expression_Binary_BitwiseAnd''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  207.                 '==' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_Equal''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  208.                 '!=' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_NotEqual''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  209.                 '<' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_Less''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  210.                 '>' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_Greater''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  211.                 '>=' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_GreaterEqual''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  212.                 '<=' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_LessEqual''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  213.                 'not in' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_NotIn''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  214.                 'in' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_In''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  215.                 'matches' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_Matches''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  216.                 'starts with' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_StartsWith''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  217.                 'ends with' => array('precedence' => 20'class' => 'Twig_Node_Expression_Binary_EndsWith''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  218.                 '..' => array('precedence' => 25'class' => 'Twig_Node_Expression_Binary_Range''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  219.                 '+' => array('precedence' => 30'class' => 'Twig_Node_Expression_Binary_Add''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  220.                 '-' => array('precedence' => 30'class' => 'Twig_Node_Expression_Binary_Sub''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  221.                 '~' => array('precedence' => 40'class' => 'Twig_Node_Expression_Binary_Concat''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  222.                 '*' => array('precedence' => 60'class' => 'Twig_Node_Expression_Binary_Mul''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  223.                 '/' => array('precedence' => 60'class' => 'Twig_Node_Expression_Binary_Div''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  224.                 '//' => array('precedence' => 60'class' => 'Twig_Node_Expression_Binary_FloorDiv''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  225.                 '%' => array('precedence' => 60'class' => 'Twig_Node_Expression_Binary_Mod''associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  226.                 'is' => array('precedence' => 100'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  227.                 'is not' => array('precedence' => 100'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  228.                 '**' => array('precedence' => 200'class' => 'Twig_Node_Expression_Binary_Power''associativity' => Twig_ExpressionParser::OPERATOR_RIGHT),
  229.                 '??' => array('precedence' => 300'class' => 'Twig_Node_Expression_NullCoalesce''associativity' => Twig_ExpressionParser::OPERATOR_RIGHT),
  230.             ),
  231.         );
  232.     }
  233. }
  234. /**
  235.  * Cycles over a value.
  236.  *
  237.  * @param ArrayAccess|array $values
  238.  * @param int               $position The cycle position
  239.  *
  240.  * @return string The next value in the cycle
  241.  */
  242. function twig_cycle($values$position)
  243. {
  244.     if (!is_array($values) && !$values instanceof ArrayAccess) {
  245.         return $values;
  246.     }
  247.     return $values[$position count($values)];
  248. }
  249. /**
  250.  * Returns a random value depending on the supplied parameter type:
  251.  * - a random item from a Traversable or array
  252.  * - a random character from a string
  253.  * - a random integer between 0 and the integer parameter.
  254.  *
  255.  * @param Twig_Environment                   $env
  256.  * @param Traversable|array|int|float|string $values The values to pick a random item from
  257.  *
  258.  * @throws Twig_Error_Runtime when $values is an empty array (does not apply to an empty string which is returned as is)
  259.  *
  260.  * @return mixed A random value from the given sequence
  261.  */
  262. function twig_random(Twig_Environment $env$values null)
  263. {
  264.     if (null === $values) {
  265.         return mt_rand();
  266.     }
  267.     if (is_int($values) || is_float($values)) {
  268.         return $values mt_rand($values0) : mt_rand(0$values);
  269.     }
  270.     if ($values instanceof Traversable) {
  271.         $values iterator_to_array($values);
  272.     } elseif (is_string($values)) {
  273.         if ('' === $values) {
  274.             return '';
  275.         }
  276.         $charset $env->getCharset();
  277.         if ('UTF-8' !== $charset) {
  278.             $values iconv($charset'UTF-8'$values);
  279.         }
  280.         // unicode version of str_split()
  281.         // split at all positions, but not after the start and not before the end
  282.         $values preg_split('/(?<!^)(?!$)/u'$values);
  283.         if ('UTF-8' !== $charset) {
  284.             foreach ($values as $i => $value) {
  285.                 $values[$i] = iconv('UTF-8'$charset$value);
  286.             }
  287.         }
  288.     }
  289.     if (!is_array($values)) {
  290.         return $values;
  291.     }
  292.     if (=== count($values)) {
  293.         throw new Twig_Error_Runtime('The random function cannot pick from an empty array.');
  294.     }
  295.     return $values[array_rand($values1)];
  296. }
  297. /**
  298.  * Converts a date to the given format.
  299.  *
  300.  * <pre>
  301.  *   {{ post.published_at|date("m/d/Y") }}
  302.  * </pre>
  303.  *
  304.  * @param Twig_Environment                      $env
  305.  * @param DateTimeInterface|DateInterval|string $date     A date
  306.  * @param string|null                           $format   The target format, null to use the default
  307.  * @param DateTimeZone|string|null|false        $timezone The target timezone, null to use the default, false to leave unchanged
  308.  *
  309.  * @return string The formatted date
  310.  */
  311. function twig_date_format_filter(Twig_Environment $env$date$format null$timezone null)
  312. {
  313.     if (null === $format) {
  314.         $formats $env->getExtension('Twig_Extension_Core')->getDateFormat();
  315.         $format $date instanceof DateInterval $formats[1] : $formats[0];
  316.     }
  317.     if ($date instanceof DateInterval) {
  318.         return $date->format($format);
  319.     }
  320.     return twig_date_converter($env$date$timezone)->format($format);
  321. }
  322. /**
  323.  * Returns a new date object modified.
  324.  *
  325.  * <pre>
  326.  *   {{ post.published_at|date_modify("-1day")|date("m/d/Y") }}
  327.  * </pre>
  328.  *
  329.  * @param Twig_Environment         $env
  330.  * @param DateTimeInterface|string $date     A date
  331.  * @param string                   $modifier A modifier string
  332.  *
  333.  * @return DateTimeInterface A new date object
  334.  */
  335. function twig_date_modify_filter(Twig_Environment $env$date$modifier)
  336. {
  337.     $date twig_date_converter($env$datefalse);
  338.     return $date->modify($modifier);
  339. }
  340. /**
  341.  * Converts an input to a DateTime instance.
  342.  *
  343.  * <pre>
  344.  *    {% if date(user.created_at) < date('+2days') %}
  345.  *      {# do something #}
  346.  *    {% endif %}
  347.  * </pre>
  348.  *
  349.  * @param Twig_Environment               $env
  350.  * @param DateTimeInterface|string|null  $date     A date or null to use the current time
  351.  * @param DateTimeZone|string|null|false $timezone The target timezone, null to use the default, false to leave unchanged
  352.  *
  353.  * @return DateTime A DateTime instance
  354.  */
  355. function twig_date_converter(Twig_Environment $env$date null$timezone null)
  356. {
  357.     // determine the timezone
  358.     if (false !== $timezone) {
  359.         if (null === $timezone) {
  360.             $timezone $env->getExtension('Twig_Extension_Core')->getTimezone();
  361.         } elseif (!$timezone instanceof DateTimeZone) {
  362.             $timezone = new DateTimeZone($timezone);
  363.         }
  364.     }
  365.     // immutable dates
  366.     if ($date instanceof DateTimeImmutable) {
  367.         return false !== $timezone $date->setTimezone($timezone) : $date;
  368.     }
  369.     if ($date instanceof DateTimeInterface) {
  370.         $date = clone $date;
  371.         if (false !== $timezone) {
  372.             $date->setTimezone($timezone);
  373.         }
  374.         return $date;
  375.     }
  376.     if (null === $date || 'now' === $date) {
  377.         return new DateTime($datefalse !== $timezone $timezone $env->getExtension('Twig_Extension_Core')->getTimezone());
  378.     }
  379.     $asString = (string) $date;
  380.     if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString1)))) {
  381.         $date = new DateTime('@'.$date);
  382.     } else {
  383.         $date = new DateTime($date$env->getExtension('Twig_Extension_Core')->getTimezone());
  384.     }
  385.     if (false !== $timezone) {
  386.         $date->setTimezone($timezone);
  387.     }
  388.     return $date;
  389. }
  390. /**
  391.  * Replaces strings within a string.
  392.  *
  393.  * @param string            $str  String to replace in
  394.  * @param array|Traversable $from Replace values
  395.  *
  396.  * @return string
  397.  */
  398. function twig_replace_filter($str$from)
  399. {
  400.     if ($from instanceof Traversable) {
  401.         $from iterator_to_array($from);
  402.     } elseif (!is_array($from)) {
  403.         throw new Twig_Error_Runtime(sprintf('The "replace" filter expects an array or "Traversable" as replace values, got "%s".'is_object($from) ? get_class($from) : gettype($from)));
  404.     }
  405.     return strtr($str$from);
  406. }
  407. /**
  408.  * Rounds a number.
  409.  *
  410.  * @param int|float $value     The value to round
  411.  * @param int|float $precision The rounding precision
  412.  * @param string    $method    The method to use for rounding
  413.  *
  414.  * @return int|float The rounded number
  415.  */
  416. function twig_round($value$precision 0$method 'common')
  417. {
  418.     if ('common' == $method) {
  419.         return round($value$precision);
  420.     }
  421.     if ('ceil' != $method && 'floor' != $method) {
  422.         throw new Twig_Error_Runtime('The round filter only supports the "common", "ceil", and "floor" methods.');
  423.     }
  424.     return $method($value pow(10$precision)) / pow(10$precision);
  425. }
  426. /**
  427.  * Number format filter.
  428.  *
  429.  * All of the formatting options can be left null, in that case the defaults will
  430.  * be used.  Supplying any of the parameters will override the defaults set in the
  431.  * environment object.
  432.  *
  433.  * @param Twig_Environment $env
  434.  * @param mixed            $number       A float/int/string of the number to format
  435.  * @param int              $decimal      the number of decimal points to display
  436.  * @param string           $decimalPoint the character(s) to use for the decimal point
  437.  * @param string           $thousandSep  the character(s) to use for the thousands separator
  438.  *
  439.  * @return string The formatted number
  440.  */
  441. function twig_number_format_filter(Twig_Environment $env$number$decimal null$decimalPoint null$thousandSep null)
  442. {
  443.     $defaults $env->getExtension('Twig_Extension_Core')->getNumberFormat();
  444.     if (null === $decimal) {
  445.         $decimal $defaults[0];
  446.     }
  447.     if (null === $decimalPoint) {
  448.         $decimalPoint $defaults[1];
  449.     }
  450.     if (null === $thousandSep) {
  451.         $thousandSep $defaults[2];
  452.     }
  453.     return number_format((float) $number$decimal$decimalPoint$thousandSep);
  454. }
  455. /**
  456.  * URL encodes (RFC 3986) a string as a path segment or an array as a query string.
  457.  *
  458.  * @param string|array $url A URL or an array of query parameters
  459.  *
  460.  * @return string The URL encoded value
  461.  */
  462. function twig_urlencode_filter($url)
  463. {
  464.     if (is_array($url)) {
  465.         return http_build_query($url'''&'PHP_QUERY_RFC3986);
  466.     }
  467.     return rawurlencode($url);
  468. }
  469. /**
  470.  * Merges an array with another one.
  471.  *
  472.  * <pre>
  473.  *  {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
  474.  *
  475.  *  {% set items = items|merge({ 'peugeot': 'car' }) %}
  476.  *
  477.  *  {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
  478.  * </pre>
  479.  *
  480.  * @param array|Traversable $arr1 An array
  481.  * @param array|Traversable $arr2 An array
  482.  *
  483.  * @return array The merged array
  484.  */
  485. function twig_array_merge($arr1$arr2)
  486. {
  487.     if ($arr1 instanceof Traversable) {
  488.         $arr1 iterator_to_array($arr1);
  489.     } elseif (!is_array($arr1)) {
  490.         throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.'gettype($arr1)));
  491.     }
  492.     if ($arr2 instanceof Traversable) {
  493.         $arr2 iterator_to_array($arr2);
  494.     } elseif (!is_array($arr2)) {
  495.         throw new Twig_Error_Runtime(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.'gettype($arr2)));
  496.     }
  497.     return array_merge($arr1$arr2);
  498. }
  499. /**
  500.  * Slices a variable.
  501.  *
  502.  * @param Twig_Environment $env
  503.  * @param mixed            $item         A variable
  504.  * @param int              $start        Start of the slice
  505.  * @param int              $length       Size of the slice
  506.  * @param bool             $preserveKeys Whether to preserve key or not (when the input is an array)
  507.  *
  508.  * @return mixed The sliced variable
  509.  */
  510. function twig_slice(Twig_Environment $env$item$start$length null$preserveKeys false)
  511. {
  512.     if ($item instanceof Traversable) {
  513.         while ($item instanceof IteratorAggregate) {
  514.             $item $item->getIterator();
  515.         }
  516.         if ($start >= && $length >= && $item instanceof Iterator) {
  517.             try {
  518.                 return iterator_to_array(new LimitIterator($item$startnull === $length ? -$length), $preserveKeys);
  519.             } catch (OutOfBoundsException $exception) {
  520.                 return array();
  521.             }
  522.         }
  523.         $item iterator_to_array($item$preserveKeys);
  524.     }
  525.     if (is_array($item)) {
  526.         return array_slice($item$start$length$preserveKeys);
  527.     }
  528.     $item = (string) $item;
  529.     return (string) mb_substr($item$start$length$env->getCharset());
  530. }
  531. /**
  532.  * Returns the first element of the item.
  533.  *
  534.  * @param Twig_Environment $env
  535.  * @param mixed            $item A variable
  536.  *
  537.  * @return mixed The first element of the item
  538.  */
  539. function twig_first(Twig_Environment $env$item)
  540. {
  541.     $elements twig_slice($env$item01false);
  542.     return is_string($elements) ? $elements current($elements);
  543. }
  544. /**
  545.  * Returns the last element of the item.
  546.  *
  547.  * @param Twig_Environment $env
  548.  * @param mixed            $item A variable
  549.  *
  550.  * @return mixed The last element of the item
  551.  */
  552. function twig_last(Twig_Environment $env$item)
  553. {
  554.     $elements twig_slice($env$item, -11false);
  555.     return is_string($elements) ? $elements current($elements);
  556. }
  557. /**
  558.  * Joins the values to a string.
  559.  *
  560.  * The separator between elements is an empty string per default, you can define it with the optional parameter.
  561.  *
  562.  * <pre>
  563.  *  {{ [1, 2, 3]|join('|') }}
  564.  *  {# returns 1|2|3 #}
  565.  *
  566.  *  {{ [1, 2, 3]|join }}
  567.  *  {# returns 123 #}
  568.  * </pre>
  569.  *
  570.  * @param array  $value An array
  571.  * @param string $glue  The separator
  572.  *
  573.  * @return string The concatenated string
  574.  */
  575. function twig_join_filter($value$glue '')
  576. {
  577.     if ($value instanceof Traversable) {
  578.         $value iterator_to_array($valuefalse);
  579.     }
  580.     return implode($glue, (array) $value);
  581. }
  582. /**
  583.  * Splits the string into an array.
  584.  *
  585.  * <pre>
  586.  *  {{ "one,two,three"|split(',') }}
  587.  *  {# returns [one, two, three] #}
  588.  *
  589.  *  {{ "one,two,three,four,five"|split(',', 3) }}
  590.  *  {# returns [one, two, "three,four,five"] #}
  591.  *
  592.  *  {{ "123"|split('') }}
  593.  *  {# returns [1, 2, 3] #}
  594.  *
  595.  *  {{ "aabbcc"|split('', 2) }}
  596.  *  {# returns [aa, bb, cc] #}
  597.  * </pre>
  598.  *
  599.  * @param Twig_Environment $env
  600.  * @param string           $value     A string
  601.  * @param string           $delimiter The delimiter
  602.  * @param int              $limit     The limit
  603.  *
  604.  * @return array The split string as an array
  605.  */
  606. function twig_split_filter(Twig_Environment $env$value$delimiter$limit null)
  607. {
  608.     if (!empty($delimiter)) {
  609.         return null === $limit explode($delimiter$value) : explode($delimiter$value$limit);
  610.     }
  611.     if ($limit <= 1) {
  612.         return preg_split('/(?<!^)(?!$)/u'$value);
  613.     }
  614.     $length mb_strlen($value$env->getCharset());
  615.     if ($length $limit) {
  616.         return array($value);
  617.     }
  618.     $r = array();
  619.     for ($i 0$i $length$i += $limit) {
  620.         $r[] = mb_substr($value$i$limit$env->getCharset());
  621.     }
  622.     return $r;
  623. }
  624. // The '_default' filter is used internally to avoid using the ternary operator
  625. // which costs a lot for big contexts (before PHP 5.4). So, on average,
  626. // a function call is cheaper.
  627. /**
  628.  * @internal
  629.  */
  630. function _twig_default_filter($value$default '')
  631. {
  632.     if (twig_test_empty($value)) {
  633.         return $default;
  634.     }
  635.     return $value;
  636. }
  637. /**
  638.  * Returns the keys for the given array.
  639.  *
  640.  * It is useful when you want to iterate over the keys of an array:
  641.  *
  642.  * <pre>
  643.  *  {% for key in array|keys %}
  644.  *      {# ... #}
  645.  *  {% endfor %}
  646.  * </pre>
  647.  *
  648.  * @param array $array An array
  649.  *
  650.  * @return array The keys
  651.  */
  652. function twig_get_array_keys_filter($array)
  653. {
  654.     if ($array instanceof Traversable) {
  655.         while ($array instanceof IteratorAggregate) {
  656.             $array $array->getIterator();
  657.         }
  658.         if ($array instanceof Iterator) {
  659.             $keys = array();
  660.             $array->rewind();
  661.             while ($array->valid()) {
  662.                 $keys[] = $array->key();
  663.                 $array->next();
  664.             }
  665.             return $keys;
  666.         }
  667.         $keys = array();
  668.         foreach ($array as $key => $item) {
  669.             $keys[] = $key;
  670.         }
  671.         return $keys;
  672.     }
  673.     if (!is_array($array)) {
  674.         return array();
  675.     }
  676.     return array_keys($array);
  677. }
  678. /**
  679.  * Reverses a variable.
  680.  *
  681.  * @param Twig_Environment         $env
  682.  * @param array|Traversable|string $item         An array, a Traversable instance, or a string
  683.  * @param bool                     $preserveKeys Whether to preserve key or not
  684.  *
  685.  * @return mixed The reversed input
  686.  */
  687. function twig_reverse_filter(Twig_Environment $env$item$preserveKeys false)
  688. {
  689.     if ($item instanceof Traversable) {
  690.         return array_reverse(iterator_to_array($item), $preserveKeys);
  691.     }
  692.     if (is_array($item)) {
  693.         return array_reverse($item$preserveKeys);
  694.     }
  695.     $string = (string) $item;
  696.     $charset $env->getCharset();
  697.     if ('UTF-8' !== $charset) {
  698.         $item iconv($charset'UTF-8'$string);
  699.     }
  700.     preg_match_all('/./us'$item$matches);
  701.     $string implode(''array_reverse($matches[0]));
  702.     if ('UTF-8' !== $charset) {
  703.         $string iconv('UTF-8'$charset$string);
  704.     }
  705.     return $string;
  706. }
  707. /**
  708.  * Sorts an array.
  709.  *
  710.  * @param array|Traversable $array
  711.  *
  712.  * @return array
  713.  */
  714. function twig_sort_filter($array)
  715. {
  716.     if ($array instanceof Traversable) {
  717.         $array iterator_to_array($array);
  718.     } elseif (!is_array($array)) {
  719.         throw new Twig_Error_Runtime(sprintf('The sort filter only works with arrays or "Traversable", got "%s".'gettype($array)));
  720.     }
  721.     asort($array);
  722.     return $array;
  723. }
  724. /**
  725.  * @internal
  726.  */
  727. function twig_in_filter($value$compare)
  728. {
  729.     if (is_array($compare)) {
  730.         return in_array($value$compareis_object($value) || is_resource($value));
  731.     } elseif (is_string($compare) && (is_string($value) || is_int($value) || is_float($value))) {
  732.         return '' === $value || false !== strpos($compare, (string) $value);
  733.     } elseif ($compare instanceof Traversable) {
  734.         if (is_object($value) || is_resource($value)) {
  735.             foreach ($compare as $item) {
  736.                 if ($item === $value) {
  737.                     return true;
  738.                 }
  739.             }
  740.         } else {
  741.             foreach ($compare as $item) {
  742.                 if ($item == $value) {
  743.                     return true;
  744.                 }
  745.             }
  746.         }
  747.         return false;
  748.     }
  749.     return false;
  750. }
  751. /**
  752.  * Returns a trimmed string.
  753.  *
  754.  * @return string
  755.  *
  756.  * @throws Twig_Error_Runtime When an invalid trimming side is used (not a string or not 'left', 'right', or 'both')
  757.  */
  758. function twig_trim_filter($string$characterMask null$side 'both')
  759. {
  760.     if (null === $characterMask) {
  761.         $characterMask " \t\n\r\0\x0B";
  762.     }
  763.     switch ($side) {
  764.         case 'both':
  765.             return trim($string$characterMask);
  766.         case 'left':
  767.             return ltrim($string$characterMask);
  768.         case 'right':
  769.             return rtrim($string$characterMask);
  770.         default:
  771.             throw new Twig_Error_Runtime('Trimming side must be "left", "right" or "both".');
  772.     }
  773. }
  774. /**
  775.  * Escapes a string.
  776.  *
  777.  * @param Twig_Environment $env
  778.  * @param mixed            $string     The value to be escaped
  779.  * @param string           $strategy   The escaping strategy
  780.  * @param string           $charset    The charset
  781.  * @param bool             $autoescape Whether the function is called by the auto-escaping feature (true) or by the developer (false)
  782.  *
  783.  * @return string
  784.  */
  785. function twig_escape_filter(Twig_Environment $env$string$strategy 'html'$charset null$autoescape false)
  786. {
  787.     if ($autoescape && $string instanceof Twig_Markup) {
  788.         return $string;
  789.     }
  790.     if (!is_string($string)) {
  791.         if (is_object($string) && method_exists($string'__toString')) {
  792.             $string = (string) $string;
  793.         } elseif (in_array($strategy, array('html''js''css''html_attr''url'))) {
  794.             return $string;
  795.         }
  796.     }
  797.     if (null === $charset) {
  798.         $charset $env->getCharset();
  799.     }
  800.     switch ($strategy) {
  801.         case 'html':
  802.             // see https://secure.php.net/htmlspecialchars
  803.             // Using a static variable to avoid initializing the array
  804.             // each time the function is called. Moving the declaration on the
  805.             // top of the function slow downs other escaping strategies.
  806.             static $htmlspecialcharsCharsets = array(
  807.                 'ISO-8859-1' => true'ISO8859-1' => true,
  808.                 'ISO-8859-15' => true'ISO8859-15' => true,
  809.                 'utf-8' => true'UTF-8' => true,
  810.                 'CP866' => true'IBM866' => true'866' => true,
  811.                 'CP1251' => true'WINDOWS-1251' => true'WIN-1251' => true,
  812.                 '1251' => true,
  813.                 'CP1252' => true'WINDOWS-1252' => true'1252' => true,
  814.                 'KOI8-R' => true'KOI8-RU' => true'KOI8R' => true,
  815.                 'BIG5' => true'950' => true,
  816.                 'GB2312' => true'936' => true,
  817.                 'BIG5-HKSCS' => true,
  818.                 'SHIFT_JIS' => true'SJIS' => true'932' => true,
  819.                 'EUC-JP' => true'EUCJP' => true,
  820.                 'ISO8859-5' => true'ISO-8859-5' => true'MACROMAN' => true,
  821.             );
  822.             if (isset($htmlspecialcharsCharsets[$charset])) {
  823.                 return htmlspecialchars($stringENT_QUOTES ENT_SUBSTITUTE$charset);
  824.             }
  825.             if (isset($htmlspecialcharsCharsets[strtoupper($charset)])) {
  826.                 // cache the lowercase variant for future iterations
  827.                 $htmlspecialcharsCharsets[$charset] = true;
  828.                 return htmlspecialchars($stringENT_QUOTES ENT_SUBSTITUTE$charset);
  829.             }
  830.             $string iconv($charset'UTF-8'$string);
  831.             $string htmlspecialchars($stringENT_QUOTES ENT_SUBSTITUTE'UTF-8');
  832.             return iconv('UTF-8'$charset$string);
  833.         case 'js':
  834.             // escape all non-alphanumeric characters
  835.             // into their \x or \uHHHH representations
  836.             if ('UTF-8' !== $charset) {
  837.                 $string iconv($charset'UTF-8'$string);
  838.             }
  839.             if (== strlen($string) ? false !== preg_match('/^./su'$string)) {
  840.                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  841.             }
  842.             $string preg_replace_callback('#[^a-zA-Z0-9,\._]#Su', function ($matches) {
  843.                 $char $matches[0];
  844.                 /*
  845.                  * A few characters have short escape sequences in JSON and JavaScript.
  846.                  * Escape sequences supported only by JavaScript, not JSON, are ommitted.
  847.                  * \" is also supported but omitted, because the resulting string is not HTML safe.
  848.                  */
  849.                 static $shortMap = array(
  850.                     '\\' => '\\\\',
  851.                     '/' => '\\/',
  852.                     "\x08" => '\b',
  853.                     "\x0C" => '\f',
  854.                     "\x0A" => '\n',
  855.                     "\x0D" => '\r',
  856.                     "\x09" => '\t',
  857.                 );
  858.                 if (isset($shortMap[$char])) {
  859.                     return $shortMap[$char];
  860.                 }
  861.                 // \uHHHH
  862.                 $char twig_convert_encoding($char'UTF-16BE''UTF-8');
  863.                 $char strtoupper(bin2hex($char));
  864.                 if (>= strlen($char)) {
  865.                     return sprintf('\u%04s'$char);
  866.                 }
  867.                 return sprintf('\u%04s\u%04s'substr($char0, -4), substr($char, -4));
  868.             }, $string);
  869.             if ('UTF-8' !== $charset) {
  870.                 $string iconv('UTF-8'$charset$string);
  871.             }
  872.             return $string;
  873.         case 'css':
  874.             if ('UTF-8' !== $charset) {
  875.                 $string iconv($charset'UTF-8'$string);
  876.             }
  877.             if (== strlen($string) ? false !== preg_match('/^./su'$string)) {
  878.                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  879.             }
  880.             $string preg_replace_callback('#[^a-zA-Z0-9]#Su', function ($matches) {
  881.                 $char $matches[0];
  882.                 // \xHH
  883.                 if (!isset($char[1])) {
  884.                     $hex ltrim(strtoupper(bin2hex($char)), '0');
  885.                     if (=== strlen($hex)) {
  886.                         $hex '0';
  887.                     }
  888.                     return '\\'.$hex.' ';
  889.                 }
  890.                 // \uHHHH
  891.                 $char twig_convert_encoding($char'UTF-16BE''UTF-8');
  892.                 return '\\'.ltrim(strtoupper(bin2hex($char)), '0').' ';
  893.             }, $string);
  894.             if ('UTF-8' !== $charset) {
  895.                 $string iconv('UTF-8'$charset$string);
  896.             }
  897.             return $string;
  898.         case 'html_attr':
  899.             if ('UTF-8' !== $charset) {
  900.                 $string iconv($charset'UTF-8'$string);
  901.             }
  902.             if (== strlen($string) ? false !== preg_match('/^./su'$string)) {
  903.                 throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  904.             }
  905.             $string preg_replace_callback('#[^a-zA-Z0-9,\.\-_]#Su', function ($matches) {
  906.                 /**
  907.                  * This function is adapted from code coming from Zend Framework.
  908.                  *
  909.                  * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (https://www.zend.com)
  910.                  * @license   https://framework.zend.com/license/new-bsd New BSD License
  911.                  */
  912.                 /*
  913.                  * While HTML supports far more named entities, the lowest common denominator
  914.                  * has become HTML5's XML Serialisation which is restricted to the those named
  915.                  * entities that XML supports. Using HTML entities would result in this error:
  916.                  *     XML Parsing Error: undefined entity
  917.                  */
  918.                 static $entityMap = array(
  919.                     34 => 'quot'/* quotation mark */
  920.                     38 => 'amp',  /* ampersand */
  921.                     60 => 'lt',   /* less-than sign */
  922.                     62 => 'gt',   /* greater-than sign */
  923.                 );
  924.                 $chr $matches[0];
  925.                 $ord ord($chr);
  926.                 /*
  927.                  * The following replaces characters undefined in HTML with the
  928.                  * hex entity for the Unicode replacement character.
  929.                  */
  930.                 if (($ord <= 0x1f && "\t" != $chr && "\n" != $chr && "\r" != $chr) || ($ord >= 0x7f && $ord <= 0x9f)) {
  931.                     return '&#xFFFD;';
  932.                 }
  933.                 /*
  934.                  * Check if the current character to escape has a name entity we should
  935.                  * replace it with while grabbing the hex value of the character.
  936.                  */
  937.                 if (== strlen($chr)) {
  938.                     $hex strtoupper(substr('00'.bin2hex($chr), -2));
  939.                 } else {
  940.                     $chr twig_convert_encoding($chr'UTF-16BE''UTF-8');
  941.                     $hex strtoupper(substr('0000'.bin2hex($chr), -4));
  942.                 }
  943.                 $int hexdec($hex);
  944.                 if (array_key_exists($int$entityMap)) {
  945.                     return sprintf('&%s;'$entityMap[$int]);
  946.                 }
  947.                 /*
  948.                  * Per OWASP recommendations, we'll use hex entities for any other
  949.                  * characters where a named entity does not exist.
  950.                  */
  951.                 return sprintf('&#x%s;'$hex);
  952.             }, $string);
  953.             if ('UTF-8' !== $charset) {
  954.                 $string iconv('UTF-8'$charset$string);
  955.             }
  956.             return $string;
  957.         case 'url':
  958.             return rawurlencode($string);
  959.         default:
  960.             static $escapers;
  961.             if (null === $escapers) {
  962.                 $escapers $env->getExtension('Twig_Extension_Core')->getEscapers();
  963.             }
  964.             if (isset($escapers[$strategy])) {
  965.                 return $escapers[$strategy]($env$string$charset);
  966.             }
  967.             $validStrategies implode(', 'array_merge(array('html''js''url''css''html_attr'), array_keys($escapers)));
  968.             throw new Twig_Error_Runtime(sprintf('Invalid escaping strategy "%s" (valid ones: %s).'$strategy$validStrategies));
  969.     }
  970. }
  971. /**
  972.  * @internal
  973.  */
  974. function twig_escape_filter_is_safe(Twig_Node $filterArgs)
  975. {
  976.     foreach ($filterArgs as $arg) {
  977.         if ($arg instanceof Twig_Node_Expression_Constant) {
  978.             return array($arg->getAttribute('value'));
  979.         }
  980.         return array();
  981.     }
  982.     return array('html');
  983. }
  984. function twig_convert_encoding($string$to$from)
  985. {
  986.     return iconv($from$to$string);
  987. }
  988. /**
  989.  * Returns the length of a variable.
  990.  *
  991.  * @param Twig_Environment $env   A Twig_Environment instance
  992.  * @param mixed            $thing A variable
  993.  *
  994.  * @return int The length of the value
  995.  */
  996. function twig_length_filter(Twig_Environment $env$thing)
  997. {
  998.     if (null === $thing) {
  999.         return 0;
  1000.     }
  1001.     if (is_scalar($thing)) {
  1002.         return mb_strlen($thing$env->getCharset());
  1003.     }
  1004.     if ($thing instanceof \SimpleXMLElement) {
  1005.         return count($thing);
  1006.     }
  1007.     if (method_exists($thing'__toString') && !$thing instanceof \Countable) {
  1008.         return mb_strlen((string) $thing$env->getCharset());
  1009.     }
  1010.     if ($thing instanceof \Countable || is_array($thing)) {
  1011.         return count($thing);
  1012.     }
  1013.     if ($thing instanceof \IteratorAggregate) {
  1014.         return iterator_count($thing);
  1015.     }
  1016.     return 1;
  1017. }
  1018. /**
  1019.  * Converts a string to uppercase.
  1020.  *
  1021.  * @param Twig_Environment $env
  1022.  * @param string           $string A string
  1023.  *
  1024.  * @return string The uppercased string
  1025.  */
  1026. function twig_upper_filter(Twig_Environment $env$string)
  1027. {
  1028.     return mb_strtoupper($string$env->getCharset());
  1029. }
  1030. /**
  1031.  * Converts a string to lowercase.
  1032.  *
  1033.  * @param Twig_Environment $env
  1034.  * @param string           $string A string
  1035.  *
  1036.  * @return string The lowercased string
  1037.  */
  1038. function twig_lower_filter(Twig_Environment $env$string)
  1039. {
  1040.     return mb_strtolower($string$env->getCharset());
  1041. }
  1042. /**
  1043.  * Returns a titlecased string.
  1044.  *
  1045.  * @param Twig_Environment $env
  1046.  * @param string           $string A string
  1047.  *
  1048.  * @return string The titlecased string
  1049.  */
  1050. function twig_title_string_filter(Twig_Environment $env$string)
  1051. {
  1052.     if (null !== $charset $env->getCharset()) {
  1053.         return mb_convert_case($stringMB_CASE_TITLE$charset);
  1054.     }
  1055.     return ucwords(strtolower($string));
  1056. }
  1057. /**
  1058.  * Returns a capitalized string.
  1059.  *
  1060.  * @param Twig_Environment $env
  1061.  * @param string           $string A string
  1062.  *
  1063.  * @return string The capitalized string
  1064.  */
  1065. function twig_capitalize_string_filter(Twig_Environment $env$string)
  1066. {
  1067.     $charset $env->getCharset();
  1068.     return mb_strtoupper(mb_substr($string01$charset), $charset).mb_strtolower(mb_substr($string1null$charset), $charset);
  1069. }
  1070. /**
  1071.  * @internal
  1072.  */
  1073. function twig_ensure_traversable($seq)
  1074. {
  1075.     if ($seq instanceof Traversable || is_array($seq)) {
  1076.         return $seq;
  1077.     }
  1078.     return array();
  1079. }
  1080. /**
  1081.  * Checks if a variable is empty.
  1082.  *
  1083.  * <pre>
  1084.  * {# evaluates to true if the foo variable is null, false, or the empty string #}
  1085.  * {% if foo is empty %}
  1086.  *     {# ... #}
  1087.  * {% endif %}
  1088.  * </pre>
  1089.  *
  1090.  * @param mixed $value A variable
  1091.  *
  1092.  * @return bool true if the value is empty, false otherwise
  1093.  */
  1094. function twig_test_empty($value)
  1095. {
  1096.     if ($value instanceof Countable) {
  1097.         return == count($value);
  1098.     }
  1099.     if (is_object($value) && method_exists($value'__toString')) {
  1100.         return '' === (string) $value;
  1101.     }
  1102.     return '' === $value || false === $value || null === $value || array() === $value;
  1103. }
  1104. /**
  1105.  * Checks if a variable is traversable.
  1106.  *
  1107.  * <pre>
  1108.  * {# evaluates to true if the foo variable is an array or a traversable object #}
  1109.  * {% if foo is iterable %}
  1110.  *     {# ... #}
  1111.  * {% endif %}
  1112.  * </pre>
  1113.  *
  1114.  * @param mixed $value A variable
  1115.  *
  1116.  * @return bool true if the value is traversable
  1117.  */
  1118. function twig_test_iterable($value)
  1119. {
  1120.     return $value instanceof Traversable || is_array($value);
  1121. }
  1122. /**
  1123.  * Renders a template.
  1124.  *
  1125.  * @param Twig_Environment $env
  1126.  * @param array            $context
  1127.  * @param string|array     $template      The template to render or an array of templates to try consecutively
  1128.  * @param array            $variables     The variables to pass to the template
  1129.  * @param bool             $withContext
  1130.  * @param bool             $ignoreMissing Whether to ignore missing templates or not
  1131.  * @param bool             $sandboxed     Whether to sandbox the template or not
  1132.  *
  1133.  * @return string The rendered template
  1134.  */
  1135. function twig_include(Twig_Environment $env$context$template$variables = array(), $withContext true$ignoreMissing false$sandboxed false)
  1136. {
  1137.     $alreadySandboxed false;
  1138.     $sandbox null;
  1139.     if ($withContext) {
  1140.         $variables array_merge($context$variables);
  1141.     }
  1142.     if ($isSandboxed $sandboxed && $env->hasExtension('Twig_Extension_Sandbox')) {
  1143.         $sandbox $env->getExtension('Twig_Extension_Sandbox');
  1144.         if (!$alreadySandboxed $sandbox->isSandboxed()) {
  1145.             $sandbox->enableSandbox();
  1146.         }
  1147.     }
  1148.     $result null;
  1149.     try {
  1150.         $result $env->resolveTemplate($template)->render($variables);
  1151.     } catch (Twig_Error_Loader $e) {
  1152.         if (!$ignoreMissing) {
  1153.             if ($isSandboxed && !$alreadySandboxed) {
  1154.                 $sandbox->disableSandbox();
  1155.             }
  1156.             throw $e;
  1157.         }
  1158.     } catch (Throwable $e) {
  1159.         if ($isSandboxed && !$alreadySandboxed) {
  1160.             $sandbox->disableSandbox();
  1161.         }
  1162.         throw $e;
  1163.     }
  1164.     if ($isSandboxed && !$alreadySandboxed) {
  1165.         $sandbox->disableSandbox();
  1166.     }
  1167.     return $result;
  1168. }
  1169. /**
  1170.  * Returns a template content without rendering it.
  1171.  *
  1172.  * @param Twig_Environment $env
  1173.  * @param string           $name          The template name
  1174.  * @param bool             $ignoreMissing Whether to ignore missing templates or not
  1175.  *
  1176.  * @return string The template source
  1177.  */
  1178. function twig_source(Twig_Environment $env$name$ignoreMissing false)
  1179. {
  1180.     $loader $env->getLoader();
  1181.     try {
  1182.         return $loader->getSourceContext($name)->getCode();
  1183.     } catch (Twig_Error_Loader $e) {
  1184.         if (!$ignoreMissing) {
  1185.             throw $e;
  1186.         }
  1187.     }
  1188. }
  1189. /**
  1190.  * Provides the ability to get constants from instances as well as class/global constants.
  1191.  *
  1192.  * @param string      $constant The name of the constant
  1193.  * @param null|object $object   The object to get the constant from
  1194.  *
  1195.  * @return string
  1196.  */
  1197. function twig_constant($constant$object null)
  1198. {
  1199.     if (null !== $object) {
  1200.         $constant get_class($object).'::'.$constant;
  1201.     }
  1202.     return constant($constant);
  1203. }
  1204. /**
  1205.  * Checks if a constant exists.
  1206.  *
  1207.  * @param string      $constant The name of the constant
  1208.  * @param null|object $object   The object to get the constant from
  1209.  *
  1210.  * @return bool
  1211.  */
  1212. function twig_constant_is_defined($constant$object null)
  1213. {
  1214.     if (null !== $object) {
  1215.         $constant get_class($object).'::'.$constant;
  1216.     }
  1217.     return defined($constant);
  1218. }
  1219. /**
  1220.  * Batches item.
  1221.  *
  1222.  * @param array $items An array of items
  1223.  * @param int   $size  The size of the batch
  1224.  * @param mixed $fill  A value used to fill missing items
  1225.  *
  1226.  * @return array
  1227.  */
  1228. function twig_array_batch($items$size$fill null)
  1229. {
  1230.     if ($items instanceof Traversable) {
  1231.         $items iterator_to_array($itemsfalse);
  1232.     }
  1233.     $size ceil($size);
  1234.     $result array_chunk($items$sizetrue);
  1235.     if (null !== $fill && !empty($result)) {
  1236.         $last count($result) - 1;
  1237.         if ($fillCount $size count($result[$last])) {
  1238.             $result[$last] = array_merge(
  1239.                 $result[$last],
  1240.                 array_fill(0$fillCount$fill)
  1241.             );
  1242.         }
  1243.     }
  1244.     return $result;
  1245. }
  1246. /**
  1247.  * Returns the attribute value for a given array/object.
  1248.  *
  1249.  * @param mixed  $object            The object or array from where to get the item
  1250.  * @param mixed  $item              The item to get from the array or object
  1251.  * @param array  $arguments         An array of arguments to pass if the item is an object method
  1252.  * @param string $type              The type of attribute (@see Twig_Template constants)
  1253.  * @param bool   $isDefinedTest     Whether this is only a defined check
  1254.  * @param bool   $ignoreStrictCheck Whether to ignore the strict attribute check or not
  1255.  *
  1256.  * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
  1257.  *
  1258.  * @throws Twig_Error_Runtime if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
  1259.  *
  1260.  * @internal
  1261.  */
  1262. function twig_get_attribute(Twig_Environment $envTwig_Source $source$object$item, array $arguments = array(), $type /* Twig_Template::ANY_CALL */ 'any'$isDefinedTest false$ignoreStrictCheck false$sandboxed false)
  1263. {
  1264.     // array
  1265.     if (/* Twig_Template::METHOD_CALL */ 'method' !== $type) {
  1266.         $arrayItem is_bool($item) || is_float($item) ? (int) $item $item;
  1267.         if ((is_array($object) && (isset($object[$arrayItem]) || array_key_exists($arrayItem$object)))
  1268.             || ($object instanceof ArrayAccess && isset($object[$arrayItem]))
  1269.         ) {
  1270.             if ($isDefinedTest) {
  1271.                 return true;
  1272.             }
  1273.             return $object[$arrayItem];
  1274.         }
  1275.         if (/* Twig_Template::ARRAY_CALL */ 'array' === $type || !is_object($object)) {
  1276.             if ($isDefinedTest) {
  1277.                 return false;
  1278.             }
  1279.             if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1280.                 return;
  1281.             }
  1282.             if ($object instanceof ArrayAccess) {
  1283.                 $message sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.'$arrayItemget_class($object));
  1284.             } elseif (is_object($object)) {
  1285.                 $message sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.'$itemget_class($object));
  1286.             } elseif (is_array($object)) {
  1287.                 if (empty($object)) {
  1288.                     $message sprintf('Key "%s" does not exist as the array is empty.'$arrayItem);
  1289.                 } else {
  1290.                     $message sprintf('Key "%s" for array with keys "%s" does not exist.'$arrayItemimplode(', 'array_keys($object)));
  1291.                 }
  1292.             } elseif (/* Twig_Template::ARRAY_CALL */ 'array' === $type) {
  1293.                 if (null === $object) {
  1294.                     $message sprintf('Impossible to access a key ("%s") on a null variable.'$item);
  1295.                 } else {
  1296.                     $message sprintf('Impossible to access a key ("%s") on a %s variable ("%s").'$itemgettype($object), $object);
  1297.                 }
  1298.             } elseif (null === $object) {
  1299.                 $message sprintf('Impossible to access an attribute ("%s") on a null variable.'$item);
  1300.             } else {
  1301.                 $message sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").'$itemgettype($object), $object);
  1302.             }
  1303.             throw new Twig_Error_Runtime($message, -1$source);
  1304.         }
  1305.     }
  1306.     if (!is_object($object)) {
  1307.         if ($isDefinedTest) {
  1308.             return false;
  1309.         }
  1310.         if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1311.             return;
  1312.         }
  1313.         if (null === $object) {
  1314.             $message sprintf('Impossible to invoke a method ("%s") on a null variable.'$item);
  1315.         } elseif (is_array($object)) {
  1316.             $message sprintf('Impossible to invoke a method ("%s") on an array.'$item);
  1317.         } else {
  1318.             $message sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").'$itemgettype($object), $object);
  1319.         }
  1320.         throw new Twig_Error_Runtime($message, -1$source);
  1321.     }
  1322.     if ($object instanceof Twig_Template) {
  1323.         throw new Twig_Error_Runtime('Accessing Twig_Template attributes is forbidden.');
  1324.     }
  1325.     // object property
  1326.     if (/* Twig_Template::METHOD_CALL */ 'method' !== $type) {
  1327.         if (isset($object->$item) || array_key_exists((string) $item$object)) {
  1328.             if ($isDefinedTest) {
  1329.                 return true;
  1330.             }
  1331.             if ($sandboxed) {
  1332.                 $env->getExtension('Twig_Extension_Sandbox')->checkPropertyAllowed($object$item);
  1333.             }
  1334.             return $object->$item;
  1335.         }
  1336.     }
  1337.     static $cache = array();
  1338.     $class get_class($object);
  1339.     // object method
  1340.     // precedence: getXxx() > isXxx() > hasXxx()
  1341.     if (!isset($cache[$class])) {
  1342.         $methods get_class_methods($object);
  1343.         sort($methods);
  1344.         $lcMethods array_map('strtolower'$methods);
  1345.         $classCache = array();
  1346.         foreach ($methods as $i => $method) {
  1347.             $classCache[$method] = $method;
  1348.             $classCache[$lcName $lcMethods[$i]] = $method;
  1349.             if ('g' === $lcName[0] && === strpos($lcName'get')) {
  1350.                 $name substr($method3);
  1351.                 $lcName substr($lcName3);
  1352.             } elseif ('i' === $lcName[0] && === strpos($lcName'is')) {
  1353.                 $name substr($method2);
  1354.                 $lcName substr($lcName2);
  1355.             } elseif ('h' === $lcName[0] && === strpos($lcName'has')) {
  1356.                 $name substr($method3);
  1357.                 $lcName substr($lcName3);
  1358.                 if (in_array('is'.$lcName$lcMethods)) {
  1359.                     continue;
  1360.                 }
  1361.             } else {
  1362.                 continue;
  1363.             }
  1364.             // skip get() and is() methods (in which case, $name is empty)
  1365.             if ($name) {
  1366.                 if (!isset($classCache[$name])) {
  1367.                     $classCache[$name] = $method;
  1368.                 }
  1369.                 if (!isset($classCache[$lcName])) {
  1370.                     $classCache[$lcName] = $method;
  1371.                 }
  1372.             }
  1373.         }
  1374.         $cache[$class] = $classCache;
  1375.     }
  1376.     $call false;
  1377.     if (isset($cache[$class][$item])) {
  1378.         $method $cache[$class][$item];
  1379.     } elseif (isset($cache[$class][$lcItem strtolower($item)])) {
  1380.         $method $cache[$class][$lcItem];
  1381.     } elseif (isset($cache[$class]['__call'])) {
  1382.         $method $item;
  1383.         $call true;
  1384.     } else {
  1385.         if ($isDefinedTest) {
  1386.             return false;
  1387.         }
  1388.         if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1389.             return;
  1390.         }
  1391.         throw new Twig_Error_Runtime(sprintf('Neither the property "%1$s" nor one of the methods "%1$s()", "get%1$s()"/"is%1$s()"/"has%1$s()" or "__call()" exist and have public access in class "%2$s".'$item$class), -1$source);
  1392.     }
  1393.     if ($isDefinedTest) {
  1394.         return true;
  1395.     }
  1396.     if ($sandboxed) {
  1397.         $env->getExtension('Twig_Extension_Sandbox')->checkMethodAllowed($object$method);
  1398.     }
  1399.     // Some objects throw exceptions when they have __call, and the method we try
  1400.     // to call is not supported. If ignoreStrictCheck is true, we should return null.
  1401.     try {
  1402.         $ret $object->$method(...$arguments);
  1403.     } catch (BadMethodCallException $e) {
  1404.         if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) {
  1405.             return;
  1406.         }
  1407.         throw $e;
  1408.     }
  1409.     return $ret;
  1410. }
  1411. class_alias('Twig_Extension_Core''Twig\Extension\CoreExtension'false);