Update Node::__toString() to include the node tag if set

This commit is contained in:
Fabien Potencier
2024-08-24 17:25:12 +02:00
parent 4b99692e2a
commit 157d36ae43
3 changed files with 40 additions and 10 deletions
+1
View File
@@ -1,5 +1,6 @@
# 3.12.0 (2024-XX-XX)
* Update `Node::__toString()` to include the node tag if set
* Add support for integers in methods of `Twig\Node\Node` that take a Node name
* Deprecate not passing a `BodyNode` instance as the body of a `ModuleNode` or `MacroNode` constructor
* Deprecate returning "null" from "TokenParserInterface::parse()".
+13 -8
View File
@@ -59,6 +59,12 @@ class Node implements \Countable, \IteratorAggregate
public function __toString()
{
$repr = static::class;
if ($this->tag) {
$repr .= \sprintf("\n tag: %s", $this->tag);
}
$attributes = [];
foreach ($this->attributes as $name => $value) {
if (\is_callable($value)) {
@@ -71,25 +77,24 @@ class Node implements \Countable, \IteratorAggregate
$attributes[] = \sprintf('%s: %s', $name, $v);
}
$repr = [static::class.'('.implode(', ', $attributes)];
if ($attributes) {
$repr .= \sprintf("\n attributes:\n %s", implode("\n ", $attributes));
}
if (\count($this->nodes)) {
$repr .= \sprintf("\n nodes:");
foreach ($this->nodes as $name => $node) {
$len = \strlen($name) + 4;
$len = \strlen($name) + 6;
$noderepr = [];
foreach (explode("\n", (string) $node) as $line) {
$noderepr[] = str_repeat(' ', $len).$line;
}
$repr[] = \sprintf(' %s: %s', $name, ltrim(implode("\n", $noderepr)));
$repr .= \sprintf("\n %s: %s", $name, ltrim(implode("\n", $noderepr)));
}
$repr[] = ')';
} else {
$repr[0] .= ')';
}
return implode("\n", $repr);
return $repr;
}
/**
+26 -2
View File
@@ -28,7 +28,13 @@ class NodeTest extends TestCase
// callable is not a supported type for a Node attribute, but Drupal uses some apparently
$node = new Node([], ['value' => function () { return '1'; }], 1);
$this->assertEquals('Twig\Node\Node(value: \Closure)', (string) $node);
$this->assertEquals(<<<EOF
Twig\Node\Node
attributes:
value: \Closure
EOF
, (string) $node
);
}
public function testToStringWithTwigCallables()
@@ -39,7 +45,25 @@ class NodeTest extends TestCase
'test' => new TwigTest('a_test'),
], 1);
$this->assertEquals('Twig\Node\Node(function: Twig\TwigFunction(a_function), filter: Twig\TwigFilter(a_filter), test: Twig\TwigTest(a_test))', (string) $node);
$this->assertEquals(<<<EOF
Twig\Node\Node
attributes:
function: Twig\TwigFunction(a_function)
filter: Twig\TwigFilter(a_filter)
test: Twig\TwigTest(a_test)
EOF
, (string) $node);
}
public function testToStringWithTag()
{
$node = new Node([], [], 1, 'tag');
$this->assertEquals(<<<EOF
Twig\Node\Node
tag: tag
EOF
, (string) $node);
}
public function testAttributeDeprecationIgnore()