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

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