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

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