vendor/twig/twig/src/Extension/CoreExtension.php line 1230

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