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

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