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

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