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

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