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

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', ['needs_environment' => true]),
  225.             new TwigFilter('map''twig_array_map', ['needs_environment' => true]),
  226.             new TwigFilter('reduce''twig_array_reduce', ['needs_environment' => true]),
  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, 'one_mandatory_argument' => true]),
  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, 'one_mandatory_argument' => true]),
  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.     use Twig\TemplateWrapper;
  325. /**
  326.  * Cycles over a value.
  327.  *
  328.  * @param \ArrayAccess|array $values
  329.  * @param int                $position The cycle position
  330.  *
  331.  * @return string The next value in the cycle
  332.  */
  333. function twig_cycle($values$position)
  334. {
  335.     if (!\is_array($values) && !$values instanceof \ArrayAccess) {
  336.         return $values;
  337.     }
  338.     return $values[$position % \count($values)];
  339. }
  340. /**
  341.  * Returns a random value depending on the supplied parameter type:
  342.  * - a random item from a \Traversable or array
  343.  * - a random character from a string
  344.  * - a random integer between 0 and the integer parameter.
  345.  *
  346.  * @param \Traversable|array|int|float|string $values The values to pick a random item from
  347.  * @param int|null                            $max    Maximum value used when $values is an int
  348.  *
  349.  * @throws RuntimeError when $values is an empty array (does not apply to an empty string which is returned as is)
  350.  *
  351.  * @return mixed A random value from the given sequence
  352.  */
  353. function twig_random(Environment $env$values null$max null)
  354. {
  355.     if (null === $values) {
  356.         return null === $max mt_rand() : mt_rand(0, (int) $max);
  357.     }
  358.     if (\is_int($values) || \is_float($values)) {
  359.         if (null === $max) {
  360.             if ($values 0) {
  361.                 $max 0;
  362.                 $min $values;
  363.             } else {
  364.                 $max $values;
  365.                 $min 0;
  366.             }
  367.         } else {
  368.             $min $values;
  369.             $max $max;
  370.         }
  371.         return mt_rand((int) $min, (int) $max);
  372.     }
  373.     if (\is_string($values)) {
  374.         if ('' === $values) {
  375.             return '';
  376.         }
  377.         $charset $env->getCharset();
  378.         if ('UTF-8' !== $charset) {
  379.             $values twig_convert_encoding($values'UTF-8'$charset);
  380.         }
  381.         // unicode version of str_split()
  382.         // split at all positions, but not after the start and not before the end
  383.         $values preg_split('/(?<!^)(?!$)/u'$values);
  384.         if ('UTF-8' !== $charset) {
  385.             foreach ($values as $i => $value) {
  386.                 $values[$i] = twig_convert_encoding($value$charset'UTF-8');
  387.             }
  388.         }
  389.     }
  390.     if (!twig_test_iterable($values)) {
  391.         return $values;
  392.     }
  393.     $values twig_to_array($values);
  394.     if (=== \count($values)) {
  395.         throw new RuntimeError('The random function cannot pick from an empty array.');
  396.     }
  397.     return $values[array_rand($values1)];
  398. }
  399. /**
  400.  * Converts a date to the given format.
  401.  *
  402.  *   {{ post.published_at|date("m/d/Y") }}
  403.  *
  404.  * @param \DateTimeInterface|\DateInterval|string $date     A date
  405.  * @param string|null                             $format   The target format, null to use the default
  406.  * @param \DateTimeZone|string|false|null         $timezone The target timezone, null to use the default, false to leave unchanged
  407.  *
  408.  * @return string The formatted date
  409.  */
  410. function twig_date_format_filter(Environment $env$date$format null$timezone null)
  411. {
  412.     if (null === $format) {
  413.         $formats $env->getExtension(CoreExtension::class)->getDateFormat();
  414.         $format $date instanceof \DateInterval $formats[1] : $formats[0];
  415.     }
  416.     if ($date instanceof \DateInterval) {
  417.         return $date->format($format);
  418.     }
  419.     return twig_date_converter($env$date$timezone)->format($format);
  420. }
  421. /**
  422.  * Returns a new date object modified.
  423.  *
  424.  *   {{ post.published_at|date_modify("-1day")|date("m/d/Y") }}
  425.  *
  426.  * @param \DateTimeInterface|string $date     A date
  427.  * @param string                    $modifier A modifier string
  428.  *
  429.  * @return \DateTimeInterface
  430.  */
  431. function twig_date_modify_filter(Environment $env$date$modifier)
  432. {
  433.     $date twig_date_converter($env$datefalse);
  434.     return $date->modify($modifier);
  435. }
  436. /**
  437.  * Converts an input to a \DateTime instance.
  438.  *
  439.  *    {% if date(user.created_at) < date('+2days') %}
  440.  *      {# do something #}
  441.  *    {% endif %}
  442.  *
  443.  * @param \DateTimeInterface|string|null  $date     A date or null to use the current time
  444.  * @param \DateTimeZone|string|false|null $timezone The target timezone, null to use the default, false to leave unchanged
  445.  *
  446.  * @return \DateTimeInterface
  447.  */
  448. function twig_date_converter(Environment $env$date null$timezone null)
  449. {
  450.     // determine the timezone
  451.     if (false !== $timezone) {
  452.         if (null === $timezone) {
  453.             $timezone $env->getExtension(CoreExtension::class)->getTimezone();
  454.         } elseif (!$timezone instanceof \DateTimeZone) {
  455.             $timezone = new \DateTimeZone($timezone);
  456.         }
  457.     }
  458.     // immutable dates
  459.     if ($date instanceof \DateTimeImmutable) {
  460.         return false !== $timezone $date->setTimezone($timezone) : $date;
  461.     }
  462.     if ($date instanceof \DateTimeInterface) {
  463.         $date = clone $date;
  464.         if (false !== $timezone) {
  465.             $date->setTimezone($timezone);
  466.         }
  467.         return $date;
  468.     }
  469.     if (null === $date || 'now' === $date) {
  470.         if (null === $date) {
  471.             $date 'now';
  472.         }
  473.         return new \DateTime($datefalse !== $timezone $timezone $env->getExtension(CoreExtension::class)->getTimezone());
  474.     }
  475.     $asString = (string) $date;
  476.     if (ctype_digit($asString) || (!empty($asString) && '-' === $asString[0] && ctype_digit(substr($asString1)))) {
  477.         $date = new \DateTime('@'.$date);
  478.     } else {
  479.         $date = new \DateTime($date$env->getExtension(CoreExtension::class)->getTimezone());
  480.     }
  481.     if (false !== $timezone) {
  482.         $date->setTimezone($timezone);
  483.     }
  484.     return $date;
  485. }
  486. /**
  487.  * Replaces strings within a string.
  488.  *
  489.  * @param string             $str  String to replace in
  490.  * @param array|\Traversable $from Replace values
  491.  *
  492.  * @return string
  493.  */
  494. function twig_replace_filter($str$from)
  495. {
  496.     if (!twig_test_iterable($from)) {
  497.         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)));
  498.     }
  499.     return strtr($strtwig_to_array($from));
  500. }
  501. /**
  502.  * Rounds a number.
  503.  *
  504.  * @param int|float $value     The value to round
  505.  * @param int|float $precision The rounding precision
  506.  * @param string    $method    The method to use for rounding
  507.  *
  508.  * @return int|float The rounded number
  509.  */
  510. function twig_round($value$precision 0$method 'common')
  511. {
  512.     if ('common' === $method) {
  513.         return round($value$precision);
  514.     }
  515.     if ('ceil' !== $method && 'floor' !== $method) {
  516.         throw new RuntimeError('The round filter only supports the "common", "ceil", and "floor" methods.');
  517.     }
  518.     return $method($value 10 ** $precision) / 10 ** $precision;
  519. }
  520. /**
  521.  * Number format filter.
  522.  *
  523.  * All of the formatting options can be left null, in that case the defaults will
  524.  * be used.  Supplying any of the parameters will override the defaults set in the
  525.  * environment object.
  526.  *
  527.  * @param mixed  $number       A float/int/string of the number to format
  528.  * @param int    $decimal      the number of decimal points to display
  529.  * @param string $decimalPoint the character(s) to use for the decimal point
  530.  * @param string $thousandSep  the character(s) to use for the thousands separator
  531.  *
  532.  * @return string The formatted number
  533.  */
  534. function twig_number_format_filter(Environment $env$number$decimal null$decimalPoint null$thousandSep null)
  535. {
  536.     $defaults $env->getExtension(CoreExtension::class)->getNumberFormat();
  537.     if (null === $decimal) {
  538.         $decimal $defaults[0];
  539.     }
  540.     if (null === $decimalPoint) {
  541.         $decimalPoint $defaults[1];
  542.     }
  543.     if (null === $thousandSep) {
  544.         $thousandSep $defaults[2];
  545.     }
  546.     return number_format((float) $number$decimal$decimalPoint$thousandSep);
  547. }
  548. /**
  549.  * URL encodes (RFC 3986) a string as a path segment or an array as a query string.
  550.  *
  551.  * @param string|array $url A URL or an array of query parameters
  552.  *
  553.  * @return string The URL encoded value
  554.  */
  555. function twig_urlencode_filter($url)
  556. {
  557.     if (\is_array($url)) {
  558.         return http_build_query($url'''&', \PHP_QUERY_RFC3986);
  559.     }
  560.     return rawurlencode($url);
  561. }
  562. /**
  563.  * Merges an array with another one.
  564.  *
  565.  *  {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
  566.  *
  567.  *  {% set items = items|merge({ 'peugeot': 'car' }) %}
  568.  *
  569.  *  {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
  570.  *
  571.  * @param array|\Traversable $arr1 An array
  572.  * @param array|\Traversable $arr2 An array
  573.  *
  574.  * @return array The merged array
  575.  */
  576. function twig_array_merge($arr1$arr2)
  577. {
  578.     if (!twig_test_iterable($arr1)) {
  579.         throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($arr1)));
  580.     }
  581.     if (!twig_test_iterable($arr2)) {
  582.         throw new RuntimeError(sprintf('The merge filter only works with arrays or "Traversable", got "%s" as second argument.', \gettype($arr2)));
  583.     }
  584.     return array_merge(twig_to_array($arr1), twig_to_array($arr2));
  585. }
  586. /**
  587.  * Slices a variable.
  588.  *
  589.  * @param mixed $item         A variable
  590.  * @param int   $start        Start of the slice
  591.  * @param int   $length       Size of the slice
  592.  * @param bool  $preserveKeys Whether to preserve key or not (when the input is an array)
  593.  *
  594.  * @return mixed The sliced variable
  595.  */
  596. function twig_slice(Environment $env$item$start$length null$preserveKeys false)
  597. {
  598.     if ($item instanceof \Traversable) {
  599.         while ($item instanceof \IteratorAggregate) {
  600.             $item $item->getIterator();
  601.         }
  602.         if ($start >= && $length >= && $item instanceof \Iterator) {
  603.             try {
  604.                 return iterator_to_array(new \LimitIterator($item$startnull === $length ? -$length), $preserveKeys);
  605.             } catch (\OutOfBoundsException $e) {
  606.                 return [];
  607.             }
  608.         }
  609.         $item iterator_to_array($item$preserveKeys);
  610.     }
  611.     if (\is_array($item)) {
  612.         return \array_slice($item$start$length$preserveKeys);
  613.     }
  614.     $item = (string) $item;
  615.     return (string) mb_substr($item$start$length$env->getCharset());
  616. }
  617. /**
  618.  * Returns the first element of the item.
  619.  *
  620.  * @param mixed $item A variable
  621.  *
  622.  * @return mixed The first element of the item
  623.  */
  624. function twig_first(Environment $env$item)
  625. {
  626.     $elements twig_slice($env$item01false);
  627.     return \is_string($elements) ? $elements current($elements);
  628. }
  629. /**
  630.  * Returns the last element of the item.
  631.  *
  632.  * @param mixed $item A variable
  633.  *
  634.  * @return mixed The last element of the item
  635.  */
  636. function twig_last(Environment $env$item)
  637. {
  638.     $elements twig_slice($env$item, -11false);
  639.     return \is_string($elements) ? $elements current($elements);
  640. }
  641. /**
  642.  * Joins the values to a string.
  643.  *
  644.  * The separators between elements are empty strings per default, you can define them with the optional parameters.
  645.  *
  646.  *  {{ [1, 2, 3]|join(', ', ' and ') }}
  647.  *  {# returns 1, 2 and 3 #}
  648.  *
  649.  *  {{ [1, 2, 3]|join('|') }}
  650.  *  {# returns 1|2|3 #}
  651.  *
  652.  *  {{ [1, 2, 3]|join }}
  653.  *  {# returns 123 #}
  654.  *
  655.  * @param array       $value An array
  656.  * @param string      $glue  The separator
  657.  * @param string|null $and   The separator for the last pair
  658.  *
  659.  * @return string The concatenated string
  660.  */
  661. function twig_join_filter($value$glue ''$and null)
  662. {
  663.     if (!twig_test_iterable($value)) {
  664.         $value = (array) $value;
  665.     }
  666.     $value twig_to_array($valuefalse);
  667.     if (=== \count($value)) {
  668.         return '';
  669.     }
  670.     if (null === $and || $and === $glue) {
  671.         return implode($glue$value);
  672.     }
  673.     if (=== \count($value)) {
  674.         return $value[0];
  675.     }
  676.     return implode($glue, \array_slice($value0, -1)).$and.$value[\count($value) - 1];
  677. }
  678. /**
  679.  * Splits the string into an array.
  680.  *
  681.  *  {{ "one,two,three"|split(',') }}
  682.  *  {# returns [one, two, three] #}
  683.  *
  684.  *  {{ "one,two,three,four,five"|split(',', 3) }}
  685.  *  {# returns [one, two, "three,four,five"] #}
  686.  *
  687.  *  {{ "123"|split('') }}
  688.  *  {# returns [1, 2, 3] #}
  689.  *
  690.  *  {{ "aabbcc"|split('', 2) }}
  691.  *  {# returns [aa, bb, cc] #}
  692.  *
  693.  * @param string $value     A string
  694.  * @param string $delimiter The delimiter
  695.  * @param int    $limit     The limit
  696.  *
  697.  * @return array The split string as an array
  698.  */
  699. function twig_split_filter(Environment $env$value$delimiter$limit null)
  700. {
  701.     if (\strlen($delimiter) > 0) {
  702.         return null === $limit explode($delimiter$value) : explode($delimiter$value$limit);
  703.     }
  704.     if ($limit <= 1) {
  705.         return preg_split('/(?<!^)(?!$)/u'$value);
  706.     }
  707.     $length mb_strlen($value$env->getCharset());
  708.     if ($length $limit) {
  709.         return [$value];
  710.     }
  711.     $r = [];
  712.     for ($i 0$i $length$i += $limit) {
  713.         $r[] = mb_substr($value$i$limit$env->getCharset());
  714.     }
  715.     return $r;
  716. }
  717. // The '_default' filter is used internally to avoid using the ternary operator
  718. // which costs a lot for big contexts (before PHP 5.4). So, on average,
  719. // a function call is cheaper.
  720. /**
  721.  * @internal
  722.  */
  723. function _twig_default_filter($value$default '')
  724. {
  725.     if (twig_test_empty($value)) {
  726.         return $default;
  727.     }
  728.     return $value;
  729. }
  730. /**
  731.  * Returns the keys for the given array.
  732.  *
  733.  * It is useful when you want to iterate over the keys of an array:
  734.  *
  735.  *  {% for key in array|keys %}
  736.  *      {# ... #}
  737.  *  {% endfor %}
  738.  *
  739.  * @param array $array An array
  740.  *
  741.  * @return array The keys
  742.  */
  743. function twig_get_array_keys_filter($array)
  744. {
  745.     if ($array instanceof \Traversable) {
  746.         while ($array instanceof \IteratorAggregate) {
  747.             $array $array->getIterator();
  748.         }
  749.         if ($array instanceof \Iterator) {
  750.             $keys = [];
  751.             $array->rewind();
  752.             while ($array->valid()) {
  753.                 $keys[] = $array->key();
  754.                 $array->next();
  755.             }
  756.             return $keys;
  757.         }
  758.         $keys = [];
  759.         foreach ($array as $key => $item) {
  760.             $keys[] = $key;
  761.         }
  762.         return $keys;
  763.     }
  764.     if (!\is_array($array)) {
  765.         return [];
  766.     }
  767.     return array_keys($array);
  768. }
  769. /**
  770.  * Reverses a variable.
  771.  *
  772.  * @param array|\Traversable|string $item         An array, a \Traversable instance, or a string
  773.  * @param bool                      $preserveKeys Whether to preserve key or not
  774.  *
  775.  * @return mixed The reversed input
  776.  */
  777. function twig_reverse_filter(Environment $env$item$preserveKeys false)
  778. {
  779.     if ($item instanceof \Traversable) {
  780.         return array_reverse(iterator_to_array($item), $preserveKeys);
  781.     }
  782.     if (\is_array($item)) {
  783.         return array_reverse($item$preserveKeys);
  784.     }
  785.     $string = (string) $item;
  786.     $charset $env->getCharset();
  787.     if ('UTF-8' !== $charset) {
  788.         $item twig_convert_encoding($string'UTF-8'$charset);
  789.     }
  790.     preg_match_all('/./us'$item$matches);
  791.     $string implode(''array_reverse($matches[0]));
  792.     if ('UTF-8' !== $charset) {
  793.         $string twig_convert_encoding($string$charset'UTF-8');
  794.     }
  795.     return $string;
  796. }
  797. /**
  798.  * Sorts an array.
  799.  *
  800.  * @param array|\Traversable $array
  801.  *
  802.  * @return array
  803.  */
  804. function twig_sort_filter($array$arrow null)
  805. {
  806.     if ($array instanceof \Traversable) {
  807.         $array iterator_to_array($array);
  808.     } elseif (!\is_array($array)) {
  809.         throw new RuntimeError(sprintf('The sort filter only works with arrays or "Traversable", got "%s".', \gettype($array)));
  810.     }
  811.     if (null !== $arrow) {
  812.         uasort($array$arrow);
  813.     } else {
  814.         asort($array);
  815.     }
  816.     return $array;
  817. }
  818. /**
  819.  * @internal
  820.  */
  821. function twig_in_filter($value$compare)
  822. {
  823.     if ($value instanceof Markup) {
  824.         $value = (string) $value;
  825.     }
  826.     if ($compare instanceof Markup) {
  827.         $compare = (string) $compare;
  828.     }
  829.     if (\is_array($compare)) {
  830.         return \in_array($value$compare, \is_object($value) || \is_resource($value));
  831.     } elseif (\is_string($compare) && (\is_string($value) || \is_int($value) || \is_float($value))) {
  832.         return '' === $value || false !== strpos($compare, (string) $value);
  833.     } elseif ($compare instanceof \Traversable) {
  834.         if (\is_object($value) || \is_resource($value)) {
  835.             foreach ($compare as $item) {
  836.                 if ($item === $value) {
  837.                     return true;
  838.                 }
  839.             }
  840.         } else {
  841.             foreach ($compare as $item) {
  842.                 if ($item == $value) {
  843.                     return true;
  844.                 }
  845.             }
  846.         }
  847.         return false;
  848.     }
  849.     return false;
  850. }
  851. /**
  852.  * Returns a trimmed string.
  853.  *
  854.  * @return string
  855.  *
  856.  * @throws RuntimeError When an invalid trimming side is used (not a string or not 'left', 'right', or 'both')
  857.  */
  858. function twig_trim_filter($string$characterMask null$side 'both')
  859. {
  860.     if (null === $characterMask) {
  861.         $characterMask " \t\n\r\0\x0B";
  862.     }
  863.     switch ($side) {
  864.         case 'both':
  865.             return trim($string$characterMask);
  866.         case 'left':
  867.             return ltrim($string$characterMask);
  868.         case 'right':
  869.             return rtrim($string$characterMask);
  870.         default:
  871.             throw new RuntimeError('Trimming side must be "left", "right" or "both".');
  872.     }
  873. }
  874. /**
  875.  * Removes whitespaces between HTML tags.
  876.  *
  877.  * @return string
  878.  */
  879. function twig_spaceless($content)
  880. {
  881.     return trim(preg_replace('/>\s+</''><'$content));
  882. }
  883. function twig_convert_encoding($string$to$from)
  884. {
  885.     if (!\function_exists('iconv')) {
  886.         throw new RuntimeError('Unable to convert encoding: required function iconv() does not exist. You should install ext-iconv or symfony/polyfill-iconv.');
  887.     }
  888.     return iconv($from$to$string);
  889. }
  890. /**
  891.  * Returns the length of a variable.
  892.  *
  893.  * @param mixed $thing A variable
  894.  *
  895.  * @return int The length of the value
  896.  */
  897. function twig_length_filter(Environment $env$thing)
  898. {
  899.     if (null === $thing) {
  900.         return 0;
  901.     }
  902.     if (is_scalar($thing)) {
  903.         return mb_strlen($thing$env->getCharset());
  904.     }
  905.     if ($thing instanceof \Countable || \is_array($thing) || $thing instanceof \SimpleXMLElement) {
  906.         return \count($thing);
  907.     }
  908.     if ($thing instanceof \Traversable) {
  909.         return iterator_count($thing);
  910.     }
  911.     if (method_exists($thing'__toString') && !$thing instanceof \Countable) {
  912.         return mb_strlen((string) $thing$env->getCharset());
  913.     }
  914.     return 1;
  915. }
  916. /**
  917.  * Converts a string to uppercase.
  918.  *
  919.  * @param string $string A string
  920.  *
  921.  * @return string The uppercased string
  922.  */
  923. function twig_upper_filter(Environment $env$string)
  924. {
  925.     return mb_strtoupper($string$env->getCharset());
  926. }
  927. /**
  928.  * Converts a string to lowercase.
  929.  *
  930.  * @param string $string A string
  931.  *
  932.  * @return string The lowercased string
  933.  */
  934. function twig_lower_filter(Environment $env$string)
  935. {
  936.     return mb_strtolower($string$env->getCharset());
  937. }
  938. /**
  939.  * Returns a titlecased string.
  940.  *
  941.  * @param string $string A string
  942.  *
  943.  * @return string The titlecased string
  944.  */
  945. function twig_title_string_filter(Environment $env$string)
  946. {
  947.     if (null !== $charset $env->getCharset()) {
  948.         return mb_convert_case($string, \MB_CASE_TITLE$charset);
  949.     }
  950.     return ucwords(strtolower($string));
  951. }
  952. /**
  953.  * Returns a capitalized string.
  954.  *
  955.  * @param string $string A string
  956.  *
  957.  * @return string The capitalized string
  958.  */
  959. function twig_capitalize_string_filter(Environment $env$string)
  960. {
  961.     $charset $env->getCharset();
  962.     return mb_strtoupper(mb_substr($string01$charset), $charset).mb_strtolower(mb_substr($string1null$charset), $charset);
  963. }
  964. /**
  965.  * @internal
  966.  */
  967. function twig_call_macro(Template $templatestring $method, array $argsint $lineno, array $contextSource $source)
  968. {
  969.     if (!method_exists($template$method)) {
  970.         $parent $template;
  971.         while ($parent $parent->getParent($context)) {
  972.             if (method_exists($parent$method)) {
  973.                 return $parent->$method(...$args);
  974.             }
  975.         }
  976.         throw new RuntimeError(sprintf('Macro "%s" is not defined in template "%s".'substr($method, \strlen('macro_')), $template->getTemplateName()), $lineno$source);
  977.     }
  978.     return $template->$method(...$args);
  979. }
  980. /**
  981.  * @internal
  982.  */
  983. function twig_ensure_traversable($seq)
  984. {
  985.     if ($seq instanceof \Traversable || \is_array($seq)) {
  986.         return $seq;
  987.     }
  988.     return [];
  989. }
  990. /**
  991.  * @internal
  992.  */
  993. function twig_to_array($seq$preserveKeys true)
  994. {
  995.     if ($seq instanceof \Traversable) {
  996.         return iterator_to_array($seq$preserveKeys);
  997.     }
  998.     if (!\is_array($seq)) {
  999.         return $seq;
  1000.     }
  1001.     return $preserveKeys $seq array_values($seq);
  1002. }
  1003. /**
  1004.  * Checks if a variable is empty.
  1005.  *
  1006.  *    {# evaluates to true if the foo variable is null, false, or the empty string #}
  1007.  *    {% if foo is empty %}
  1008.  *        {# ... #}
  1009.  *    {% endif %}
  1010.  *
  1011.  * @param mixed $value A variable
  1012.  *
  1013.  * @return bool true if the value is empty, false otherwise
  1014.  */
  1015. function twig_test_empty($value)
  1016. {
  1017.     if ($value instanceof \Countable) {
  1018.         return === \count($value);
  1019.     }
  1020.     if ($value instanceof \Traversable) {
  1021.         return !iterator_count($value);
  1022.     }
  1023.     if (\is_object($value) && method_exists($value'__toString')) {
  1024.         return '' === (string) $value;
  1025.     }
  1026.     return '' === $value || false === $value || null === $value || [] === $value;
  1027. }
  1028. /**
  1029.  * Checks if a variable is traversable.
  1030.  *
  1031.  *    {# evaluates to true if the foo variable is an array or a traversable object #}
  1032.  *    {% if foo is iterable %}
  1033.  *        {# ... #}
  1034.  *    {% endif %}
  1035.  *
  1036.  * @param mixed $value A variable
  1037.  *
  1038.  * @return bool true if the value is traversable
  1039.  */
  1040. function twig_test_iterable($value)
  1041. {
  1042.     return $value instanceof \Traversable || \is_array($value);
  1043. }
  1044. /**
  1045.  * Renders a template.
  1046.  *
  1047.  * @param array        $context
  1048.  * @param string|array $template      The template to render or an array of templates to try consecutively
  1049.  * @param array        $variables     The variables to pass to the template
  1050.  * @param bool         $withContext
  1051.  * @param bool         $ignoreMissing Whether to ignore missing templates or not
  1052.  * @param bool         $sandboxed     Whether to sandbox the template or not
  1053.  *
  1054.  * @return string The rendered template
  1055.  */
  1056. function twig_include(Environment $env$context$template$variables = [], $withContext true$ignoreMissing false$sandboxed false)
  1057. {
  1058.     $alreadySandboxed false;
  1059.     $sandbox null;
  1060.     if ($withContext) {
  1061.         $variables array_merge($context$variables);
  1062.     }
  1063.     if ($isSandboxed $sandboxed && $env->hasExtension(SandboxExtension::class)) {
  1064.         $sandbox $env->getExtension(SandboxExtension::class);
  1065.         if (!$alreadySandboxed $sandbox->isSandboxed()) {
  1066.             $sandbox->enableSandbox();
  1067.         }
  1068.         foreach ((\is_array($template) ? $template : [$template]) as $name) {
  1069.             // if a Template instance is passed, it might have been instantiated outside of a sandbox, check security
  1070.             if ($name instanceof TemplateWrapper || $name instanceof Template) {
  1071.                 $name->unwrap()->checkSecurity();
  1072.             }
  1073.         }
  1074.     }
  1075.     try {
  1076.         $loaded null;
  1077.         try {
  1078.             $loaded $env->resolveTemplate($template);
  1079.         } catch (LoaderError $e) {
  1080.             if (!$ignoreMissing) {
  1081.                 throw $e;
  1082.             }
  1083.         }
  1084.         return $loaded $loaded->render($variables) : '';
  1085.     } finally {
  1086.         if ($isSandboxed && !$alreadySandboxed) {
  1087.             $sandbox->disableSandbox();
  1088.         }
  1089.     }
  1090. }
  1091. /**
  1092.  * Returns a template content without rendering it.
  1093.  *
  1094.  * @param string $name          The template name
  1095.  * @param bool   $ignoreMissing Whether to ignore missing templates or not
  1096.  *
  1097.  * @return string The template source
  1098.  */
  1099. function twig_source(Environment $env$name$ignoreMissing false)
  1100. {
  1101.     $loader $env->getLoader();
  1102.     try {
  1103.         return $loader->getSourceContext($name)->getCode();
  1104.     } catch (LoaderError $e) {
  1105.         if (!$ignoreMissing) {
  1106.             throw $e;
  1107.         }
  1108.     }
  1109. }
  1110. /**
  1111.  * Provides the ability to get constants from instances as well as class/global constants.
  1112.  *
  1113.  * @param string      $constant The name of the constant
  1114.  * @param object|null $object   The object to get the constant from
  1115.  *
  1116.  * @return string
  1117.  */
  1118. function twig_constant($constant$object null)
  1119. {
  1120.     if (null !== $object) {
  1121.         $constant = \get_class($object).'::'.$constant;
  1122.     }
  1123.     return \constant($constant);
  1124. }
  1125. /**
  1126.  * Checks if a constant exists.
  1127.  *
  1128.  * @param string      $constant The name of the constant
  1129.  * @param object|null $object   The object to get the constant from
  1130.  *
  1131.  * @return bool
  1132.  */
  1133. function twig_constant_is_defined($constant$object null)
  1134. {
  1135.     if (null !== $object) {
  1136.         $constant = \get_class($object).'::'.$constant;
  1137.     }
  1138.     return \defined($constant);
  1139. }
  1140. /**
  1141.  * Batches item.
  1142.  *
  1143.  * @param array $items An array of items
  1144.  * @param int   $size  The size of the batch
  1145.  * @param mixed $fill  A value used to fill missing items
  1146.  *
  1147.  * @return array
  1148.  */
  1149. function twig_array_batch($items$size$fill null$preserveKeys true)
  1150. {
  1151.     if (!twig_test_iterable($items)) {
  1152.         throw new RuntimeError(sprintf('The "batch" filter expects an array or "Traversable", got "%s".', \is_object($items) ? \get_class($items) : \gettype($items)));
  1153.     }
  1154.     $size ceil($size);
  1155.     $result array_chunk(twig_to_array($items$preserveKeys), $size$preserveKeys);
  1156.     if (null !== $fill && $result) {
  1157.         $last = \count($result) - 1;
  1158.         if ($fillCount $size - \count($result[$last])) {
  1159.             for ($i 0$i $fillCount; ++$i) {
  1160.                 $result[$last][] = $fill;
  1161.             }
  1162.         }
  1163.     }
  1164.     return $result;
  1165. }
  1166. /**
  1167.  * Returns the attribute value for a given array/object.
  1168.  *
  1169.  * @param mixed  $object            The object or array from where to get the item
  1170.  * @param mixed  $item              The item to get from the array or object
  1171.  * @param array  $arguments         An array of arguments to pass if the item is an object method
  1172.  * @param string $type              The type of attribute (@see \Twig\Template constants)
  1173.  * @param bool   $isDefinedTest     Whether this is only a defined check
  1174.  * @param bool   $ignoreStrictCheck Whether to ignore the strict attribute check or not
  1175.  * @param int    $lineno            The template line where the attribute was called
  1176.  *
  1177.  * @return mixed The attribute value, or a Boolean when $isDefinedTest is true, or null when the attribute is not set and $ignoreStrictCheck is true
  1178.  *
  1179.  * @throws RuntimeError if the attribute does not exist and Twig is running in strict mode and $isDefinedTest is false
  1180.  *
  1181.  * @internal
  1182.  */
  1183. function twig_get_attribute(Environment $envSource $source$object$item, array $arguments = [], $type /* Template::ANY_CALL */ 'any'$isDefinedTest false$ignoreStrictCheck false$sandboxed falseint $lineno = -1)
  1184. {
  1185.     // array
  1186.     if (/* Template::METHOD_CALL */ 'method' !== $type) {
  1187.         $arrayItem = \is_bool($item) || \is_float($item) ? (int) $item $item;
  1188.         if (((\is_array($object) || $object instanceof \ArrayObject) && (isset($object[$arrayItem]) || \array_key_exists($arrayItem, (array) $object)))
  1189.             || ($object instanceof ArrayAccess && isset($object[$arrayItem]))
  1190.         ) {
  1191.             if ($isDefinedTest) {
  1192.                 return true;
  1193.             }
  1194.             return $object[$arrayItem];
  1195.         }
  1196.         if (/* Template::ARRAY_CALL */ 'array' === $type || !\is_object($object)) {
  1197.             if ($isDefinedTest) {
  1198.                 return false;
  1199.             }
  1200.             if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1201.                 return;
  1202.             }
  1203.             if ($object instanceof ArrayAccess) {
  1204.                 $message sprintf('Key "%s" in object with ArrayAccess of class "%s" does not exist.'$arrayItem, \get_class($object));
  1205.             } elseif (\is_object($object)) {
  1206.                 $message sprintf('Impossible to access a key "%s" on an object of class "%s" that does not implement ArrayAccess interface.'$item, \get_class($object));
  1207.             } elseif (\is_array($object)) {
  1208.                 if (empty($object)) {
  1209.                     $message sprintf('Key "%s" does not exist as the array is empty.'$arrayItem);
  1210.                 } else {
  1211.                     $message sprintf('Key "%s" for array with keys "%s" does not exist.'$arrayItemimplode(', 'array_keys($object)));
  1212.                 }
  1213.             } elseif (/* Template::ARRAY_CALL */ 'array' === $type) {
  1214.                 if (null === $object) {
  1215.                     $message sprintf('Impossible to access a key ("%s") on a null variable.'$item);
  1216.                 } else {
  1217.                     $message sprintf('Impossible to access a key ("%s") on a %s variable ("%s").'$item, \gettype($object), $object);
  1218.                 }
  1219.             } elseif (null === $object) {
  1220.                 $message sprintf('Impossible to access an attribute ("%s") on a null variable.'$item);
  1221.             } else {
  1222.                 $message sprintf('Impossible to access an attribute ("%s") on a %s variable ("%s").'$item, \gettype($object), $object);
  1223.             }
  1224.             throw new RuntimeError($message$lineno$source);
  1225.         }
  1226.     }
  1227.     if (!\is_object($object)) {
  1228.         if ($isDefinedTest) {
  1229.             return false;
  1230.         }
  1231.         if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1232.             return;
  1233.         }
  1234.         if (null === $object) {
  1235.             $message sprintf('Impossible to invoke a method ("%s") on a null variable.'$item);
  1236.         } elseif (\is_array($object)) {
  1237.             $message sprintf('Impossible to invoke a method ("%s") on an array.'$item);
  1238.         } else {
  1239.             $message sprintf('Impossible to invoke a method ("%s") on a %s variable ("%s").'$item, \gettype($object), $object);
  1240.         }
  1241.         throw new RuntimeError($message$lineno$source);
  1242.     }
  1243.     if ($object instanceof Template) {
  1244.         throw new RuntimeError('Accessing \Twig\Template attributes is forbidden.'$lineno$source);
  1245.     }
  1246.     // object property
  1247.     if (/* Template::METHOD_CALL */ 'method' !== $type) {
  1248.         if (isset($object->$item) || \array_key_exists((string) $item, (array) $object)) {
  1249.             if ($isDefinedTest) {
  1250.                 return true;
  1251.             }
  1252.             if ($sandboxed) {
  1253.                 $env->getExtension(SandboxExtension::class)->checkPropertyAllowed($object$item$lineno$source);
  1254.             }
  1255.             return $object->$item;
  1256.         }
  1257.     }
  1258.     static $cache = [];
  1259.     $class = \get_class($object);
  1260.     // object method
  1261.     // precedence: getXxx() > isXxx() > hasXxx()
  1262.     if (!isset($cache[$class])) {
  1263.         $methods get_class_methods($object);
  1264.         sort($methods);
  1265.         $lcMethods array_map(function ($value) { return strtr($value'ABCDEFGHIJKLMNOPQRSTUVWXYZ''abcdefghijklmnopqrstuvwxyz'); }, $methods);
  1266.         $classCache = [];
  1267.         foreach ($methods as $i => $method) {
  1268.             $classCache[$method] = $method;
  1269.             $classCache[$lcName $lcMethods[$i]] = $method;
  1270.             if ('g' === $lcName[0] && === strpos($lcName'get')) {
  1271.                 $name substr($method3);
  1272.                 $lcName substr($lcName3);
  1273.             } elseif ('i' === $lcName[0] && === strpos($lcName'is')) {
  1274.                 $name substr($method2);
  1275.                 $lcName substr($lcName2);
  1276.             } elseif ('h' === $lcName[0] && === strpos($lcName'has')) {
  1277.                 $name substr($method3);
  1278.                 $lcName substr($lcName3);
  1279.                 if (\in_array('is'.$lcName$lcMethods)) {
  1280.                     continue;
  1281.                 }
  1282.             } else {
  1283.                 continue;
  1284.             }
  1285.             // skip get() and is() methods (in which case, $name is empty)
  1286.             if ($name) {
  1287.                 if (!isset($classCache[$name])) {
  1288.                     $classCache[$name] = $method;
  1289.                 }
  1290.                 if (!isset($classCache[$lcName])) {
  1291.                     $classCache[$lcName] = $method;
  1292.                 }
  1293.             }
  1294.         }
  1295.         $cache[$class] = $classCache;
  1296.     }
  1297.     $call false;
  1298.     if (isset($cache[$class][$item])) {
  1299.         $method $cache[$class][$item];
  1300.     } elseif (isset($cache[$class][$lcItem strtr($item'ABCDEFGHIJKLMNOPQRSTUVWXYZ''abcdefghijklmnopqrstuvwxyz')])) {
  1301.         $method $cache[$class][$lcItem];
  1302.     } elseif (isset($cache[$class]['__call'])) {
  1303.         $method $item;
  1304.         $call true;
  1305.     } else {
  1306.         if ($isDefinedTest) {
  1307.             return false;
  1308.         }
  1309.         if ($ignoreStrictCheck || !$env->isStrictVariables()) {
  1310.             return;
  1311.         }
  1312.         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);
  1313.     }
  1314.     if ($isDefinedTest) {
  1315.         return true;
  1316.     }
  1317.     if ($sandboxed) {
  1318.         $env->getExtension(SandboxExtension::class)->checkMethodAllowed($object$method$lineno$source);
  1319.     }
  1320.     // Some objects throw exceptions when they have __call, and the method we try
  1321.     // to call is not supported. If ignoreStrictCheck is true, we should return null.
  1322.     try {
  1323.         $ret $object->$method(...$arguments);
  1324.     } catch (\BadMethodCallException $e) {
  1325.         if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) {
  1326.             return;
  1327.         }
  1328.         throw $e;
  1329.     }
  1330.     return $ret;
  1331. }
  1332. /**
  1333.  * Returns the values from a single column in the input array.
  1334.  *
  1335.  * <pre>
  1336.  *  {% set items = [{ 'fruit' : 'apple'}, {'fruit' : 'orange' }] %}
  1337.  *
  1338.  *  {% set fruits = items|column('fruit') %}
  1339.  *
  1340.  *  {# fruits now contains ['apple', 'orange'] #}
  1341.  * </pre>
  1342.  *
  1343.  * @param array|Traversable $array An array
  1344.  * @param mixed             $name  The column name
  1345.  * @param mixed             $index The column to use as the index/keys for the returned array
  1346.  *
  1347.  * @return array The array of values
  1348.  */
  1349. function twig_array_column($array$name$index null): array
  1350. {
  1351.     if ($array instanceof Traversable) {
  1352.         $array iterator_to_array($array);
  1353.     } elseif (!\is_array($array)) {
  1354.         throw new RuntimeError(sprintf('The column filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
  1355.     }
  1356.     return array_column($array$name$index);
  1357. }
  1358. function twig_array_filter(Environment $env$array$arrow)
  1359. {
  1360.     if (!twig_test_iterable($array)) {
  1361.         throw new RuntimeError(sprintf('The "filter" filter expects an array or "Traversable", got "%s".', \is_object($array) ? \get_class($array) : \gettype($array)));
  1362.     }
  1363.     if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
  1364.         throw new RuntimeError('The callable passed to "filter" filter must be a Closure in sandbox mode.');
  1365.     }
  1366.     if (\is_array($array)) {
  1367.         return array_filter($array$arrow, \ARRAY_FILTER_USE_BOTH);
  1368.     }
  1369.     // the IteratorIterator wrapping is needed as some internal PHP classes are \Traversable but do not implement \Iterator
  1370.     return new \CallbackFilterIterator(new \IteratorIterator($array), $arrow);
  1371. }
  1372. function twig_array_map(Environment $env$array$arrow)
  1373. {
  1374.     if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
  1375.         throw new RuntimeError('The callable passed to the "map" filter must be a Closure in sandbox mode.');
  1376.     }
  1377.     $r = [];
  1378.     foreach ($array as $k => $v) {
  1379.         $r[$k] = $arrow($v$k);
  1380.     }
  1381.     return $r;
  1382. }
  1383. function twig_array_reduce(Environment $env$array$arrow$initial null)
  1384. {
  1385.     if (!$arrow instanceof Closure && $env->hasExtension('\Twig\Extension\SandboxExtension') && $env->getExtension('\Twig\Extension\SandboxExtension')->isSandboxed()) {
  1386.         throw new RuntimeError('The callable passed to the "reduce" filter must be a Closure in sandbox mode.');
  1387.     }
  1388.     if (!\is_array($array)) {
  1389.         if (!$array instanceof \Traversable) {
  1390.             throw new RuntimeError(sprintf('The "reduce" filter only works with arrays or "Traversable", got "%s" as first argument.', \gettype($array)));
  1391.         }
  1392.         $array iterator_to_array($array);
  1393.     }
  1394.     return array_reduce($array$arrow$initial);
  1395. }
  1396. }