Simplify sandbox code

This commit is contained in:
Fabien Potencier
2024-04-30 13:40:56 +02:00
parent 775a445e37
commit 469d52d1b8
2 changed files with 15 additions and 17 deletions
+8 -13
View File
@@ -24,11 +24,16 @@ class CheckSecurityNode extends Node
private $usedTags;
private $usedFunctions;
/**
* @param array<string, int> $usedFilters
* @param array<string, int> $usedTags
* @param array<string, int> $usedFunctions
*/
public function __construct(array $usedFilters, array $usedTags, array $usedFunctions)
{
$this->usedFilters = $this->collect($usedFilters);
$this->usedTags = $this->collect($usedTags);
$this->usedFunctions = $this->collect($usedFunctions);
$this->usedFilters = $usedFilters;
$this->usedTags = $usedTags;
$this->usedFunctions = $usedFunctions;
parent::__construct();
}
@@ -77,14 +82,4 @@ class CheckSecurityNode extends Node
->write("}\n")
;
}
private function collect(array $used)
{
$collected = [];
foreach ($used as $name => $node) {
$collected[$name] = $node instanceof Node ? $node->getTemplateLine() : null;
}
return $collected;
}
}
+7 -4
View File
@@ -34,8 +34,11 @@ use Twig\Node\SetNode;
final class SandboxNodeVisitor implements NodeVisitorInterface
{
private $inAModule = false;
/** @var array<string, int> */
private $tags;
/** @var array<string, int> */
private $filters;
/** @var array<string, int> */
private $functions;
private $needsToStringWrap = false;
@@ -51,22 +54,22 @@ final class SandboxNodeVisitor implements NodeVisitorInterface
} elseif ($this->inAModule) {
// look for tags
if ($node->getNodeTag() && !isset($this->tags[$node->getNodeTag()])) {
$this->tags[$node->getNodeTag()] = $node;
$this->tags[$node->getNodeTag()] = $node->getTemplateLine();
}
// look for filters
if ($node instanceof FilterExpression && !isset($this->filters[$node->getNode('filter')->getAttribute('value')])) {
$this->filters[$node->getNode('filter')->getAttribute('value')] = $node;
$this->filters[$node->getNode('filter')->getAttribute('value')] = $node->getTemplateLine();
}
// look for functions
if ($node instanceof FunctionExpression && !isset($this->functions[$node->getAttribute('name')])) {
$this->functions[$node->getAttribute('name')] = $node;
$this->functions[$node->getAttribute('name')] = $node->getTemplateLine();
}
// the .. operator is equivalent to the range() function
if ($node instanceof RangeBinary && !isset($this->functions['range'])) {
$this->functions['range'] = $node;
$this->functions['range'] = $node->getTemplateLine();
}
if ($node instanceof PrintNode) {