Fix EscapeNodeVisitor::isSafeFor()

This commit is contained in:
Fabien Potencier
2024-11-23 08:35:07 +01:00
parent b7dfe60398
commit c402debcb8
5 changed files with 28 additions and 16 deletions
+19 -12
View File
@@ -37,11 +37,14 @@ final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
$this->safeVars = $safeVars;
}
/**
* @return array
*/
public function getSafe(Node $node)
{
$hash = spl_object_hash($node);
if (!isset($this->data[$hash])) {
return;
return [];
}
foreach ($this->data[$hash] as $bucket) {
@@ -55,6 +58,8 @@ final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
return $bucket['value'];
}
return [];
}
private function setSafe(Node $node, array $safe): void
@@ -107,11 +112,14 @@ final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
if ($filter) {
$safe = $filter->getSafe($node->getNode('arguments'));
if (null === $safe) {
trigger_deprecation('twig/twig', '3.16', 'The "%s::getSafe()" method should not return "null" anymore, return "[]" instead.', $filter::class);
$safe = [];
}
if (!$safe) {
$safe = $this->intersectSafe($this->getSafe($node->getNode('node')), $filter->getPreservesSafety());
}
$this->setSafe($node, $safe);
} else {
$this->setSafe($node, []);
}
} elseif ($node instanceof FunctionExpression) {
// function expression is safe when the function is safe
@@ -123,9 +131,12 @@ final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
}
if ($function) {
$this->setSafe($node, $function->getSafe($node->getNode('arguments')));
} else {
$this->setSafe($node, []);
$safe = $function->getSafe($node->getNode('arguments'));
if (null === $safe) {
trigger_deprecation('twig/twig', '3.16', 'The "%s::getSafe()" method should not return "null" anymore, return "[]" instead.', $function::class);
$safe = [];
}
$this->setSafe($node, $safe);
}
} elseif ($node instanceof MethodCallExpression || $node instanceof MacroReferenceExpression) {
// all macro calls are safe
@@ -134,19 +145,15 @@ final class SafeAnalysisNodeVisitor implements NodeVisitorInterface
$name = $node->getNode('node')->getAttribute('name');
if (\in_array($name, $this->safeVars)) {
$this->setSafe($node, ['all']);
} else {
$this->setSafe($node, []);
}
} else {
$this->setSafe($node, []);
}
return $node;
}
private function intersectSafe(?array $a = null, ?array $b = null): array
private function intersectSafe(array $a, array $b): array
{
if (null === $a || null === $b) {
if (!$a || !$b) {
return [];
}