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

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