vendor/twig/twig/src/TwigMacro.php line 87

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;
  11. use Twig\Error\RuntimeError;
  12. use Twig\Node\Expression\TempNameExpression;
  13. /**
  14. * Represents a compiled macro: its body compiled into a closure and the
  15. * signature declared in the template.
  16. *
  17. * @author Fabien Potencier <fabien@symfony.com>
  18. *
  19. * @internal This class is an implementation detail of the per-template macro
  20. * registry: compiled templates instantiate it, but it is not part of
  21. * the public API, neither on 3.x nor in 4.0.
  22. */
  23. final class TwigMacro
  24. {
  25. /**
  26. * @var array<string, int>
  27. */
  28. private array $argumentIndexes = [];
  29. /**
  30. * @var array<string, true>
  31. */
  32. private array $requiredNames = [];
  33. /**
  34. * Twig argument names that do not match their compiled closure parameter name
  35. * (reserved names get prefixed by the compiler). Only needed by callLegacy()'s
  36. * native binding; to be removed in 4.0 together with it.
  37. *
  38. * @var array<string, string>
  39. */
  40. private array $renamedArguments = [];
  41. private int $requiredCount = 0;
  42. /**
  43. * @param \Closure(mixed...): (string|Markup) $body The compiled macro body, invoked with the bound arguments in definition order
  44. * @param array<string, bool> $arguments The declared argument names mapped to whether they have a default value, in definition order
  45. */
  46. public function __construct(
  47. private string $name,
  48. private \Closure $body,
  49. private array $arguments = [],
  50. private bool $variadic = false,
  51. ) {
  52. $i = 0;
  53. foreach ($arguments as $argName => $hasDefault) {
  54. $this->argumentIndexes[$argName] = $i;
  55. if (\in_array($argName, TempNameExpression::RESERVED_NAMES, true)) {
  56. $this->renamedArguments[$argName] = TempNameExpression::RESERVED_NAME_PREFIX.$argName;
  57. }
  58. if (!$hasDefault) {
  59. $this->requiredCount = $i + 1;
  60. $this->requiredNames[$argName] = true;
  61. }
  62. ++$i;
  63. }
  64. }
  65. /**
  66. * Invokes the macro the way Twig 3.x always has (lenient argument handling),
  67. * while reporting the cases that will become errors in Twig 4.0.
  68. *
  69. * In 4.0, this becomes the strict call() method: the scan below already detects
  70. * every deprecated case, so triggerLegacyDeprecations() turns into upfront
  71. * throws and the rest stays as is.
  72. *
  73. * @param array<int|string, mixed> $arguments Positional arguments keyed by their integer position
  74. * and named arguments keyed by their name
  75. * @param Source $source The source of the template making the call, used to enrich errors
  76. * @param int $lineno The line of the call in that template, used to enrich errors
  77. */
  78. public function callLegacy(array $arguments, Source $source, int $lineno): string|Markup
  79. {
  80. // Spreading the arguments as-is is equivalent to resolving them: PHP binds
  81. // them natively, maps the named ones onto their parameter, fills the
  82. // defaults, and collects the extra ones into the variadic bucket. Only the
  83. // cases where PHP would report its own error (with closure-centric wording)
  84. // are detected upfront and turned into Twig errors.
  85. if (array_is_list($arguments)) {
  86. $count = \count($arguments);
  87. if ($count < $this->requiredCount || (!$this->variadic && $count > \count($this->arguments))) {
  88. $this->triggerLegacyDeprecations($arguments, $count, $source, $lineno);
  89. }
  90. return ($this->body)(...$arguments);
  91. }
  92. // Every declared argument is named: none can be missing, unknown, duplicated, or misordered.
  93. if (\count($arguments) === \count($this->arguments) && !array_diff_key($arguments, $this->argumentIndexes)) {
  94. return ($this->body)(...$this->renameArguments($arguments));
  95. }
  96. $positionalCount = 0;
  97. $namedRequired = 0;
  98. $sawNamed = false;
  99. $misordered = false;
  100. $duplicate = null;
  101. $hasUnknownNamed = false;
  102. foreach ($arguments as $key => $value) {
  103. if (\is_int($key)) {
  104. $misordered = $misordered || $sawNamed;
  105. ++$positionalCount;
  106. } else {
  107. $sawNamed = true;
  108. if (null === $i = $this->argumentIndexes[$key] ?? null) {
  109. $hasUnknownNamed = true;
  110. } else {
  111. if (null === $duplicate && $i < $positionalCount) {
  112. $duplicate = $key;
  113. }
  114. if (isset($this->requiredNames[$key])) {
  115. ++$namedRequired;
  116. }
  117. }
  118. }
  119. }
  120. if ($misordered) {
  121. throw new RuntimeError(\sprintf('Positional arguments cannot be used after named arguments for macro "%s".', $this->name), $lineno, $source);
  122. }
  123. if (null !== $duplicate) {
  124. throw new RuntimeError(\sprintf('Argument "%s" is defined twice for macro "%s".', $duplicate, $this->name), $lineno, $source);
  125. }
  126. // For a fully named call, the coverage of the required arguments is exact; a
  127. // mixed call falls back to the precise (and slower) per-argument check.
  128. $mayMissRequired = 0 === $positionalCount
  129. ? $namedRequired < \count($this->requiredNames)
  130. : $positionalCount < $this->requiredCount;
  131. if ($mayMissRequired || (!$this->variadic && ($hasUnknownNamed || $positionalCount > \count($this->arguments)))) {
  132. $this->triggerLegacyDeprecations($arguments, $positionalCount, $source, $lineno);
  133. }
  134. return ($this->body)(...$this->renameArguments($arguments));
  135. }
  136. /**
  137. * @param array<int|string, mixed> $arguments
  138. *
  139. * @return array<int|string, mixed>
  140. */
  141. private function renameArguments(array $arguments): array
  142. {
  143. foreach ($this->renamedArguments as $name => $parameterName) {
  144. if (\array_key_exists($name, $arguments)) {
  145. $arguments[$parameterName] = $arguments[$name];
  146. unset($arguments[$name]);
  147. }
  148. }
  149. return $arguments;
  150. }
  151. /**
  152. * To be removed in 4.0 (these deprecated cases become hard errors).
  153. *
  154. * @param array<int|string, mixed> $arguments The full argument array; string keys are the named arguments
  155. */
  156. private function triggerLegacyDeprecations(array $arguments, int $positionalCount, Source $source, int $lineno): void
  157. {
  158. if ($positionalCount < $this->requiredCount) {
  159. foreach ($this->requiredNames as $argName => $required) {
  160. if ($this->argumentIndexes[$argName] < $positionalCount || \array_key_exists($argName, $arguments)) {
  161. continue;
  162. }
  163. trigger_deprecation('twig/twig', '3.29', 'Not passing a value for the "%s" argument of macro "%s" is deprecated and the argument will be required in Twig 4.0; give it a default value in the macro definition or pass a value when calling it (in "%s" at line %d).', $argName, $this->name, $source->getName(), $lineno);
  164. }
  165. }
  166. if ($this->variadic) {
  167. return;
  168. }
  169. if ($positionalCount > \count($this->arguments)) {
  170. trigger_deprecation('twig/twig', '3.29', 'Passing more arguments than the macro "%s" accepts is deprecated and will throw in Twig 4.0; declare a variadic argument ("...name") in the macro definition to accept extra arguments (in "%s" at line %d).', $this->name, $source->getName(), $lineno);
  171. }
  172. foreach ($arguments as $name => $value) {
  173. if (\is_string($name) && !isset($this->argumentIndexes[$name])) {
  174. trigger_deprecation('twig/twig', '3.29', 'Passing the unknown named argument "%s" to the macro "%s" is deprecated and will throw in Twig 4.0; declare a variadic argument ("...name") in the macro definition to accept it (in "%s" at line %d).', $name, $this->name, $source->getName(), $lineno);
  175. }
  176. }
  177. }
  178. }