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

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