diff --git a/CHANGELOG b/CHANGELOG index c428793db..fa700246e 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -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()". diff --git a/src/Node/Node.php b/src/Node/Node.php index b23906056..3683dc383 100644 --- a/src/Node/Node.php +++ b/src/Node/Node.php @@ -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; } /** diff --git a/tests/Node/NodeTest.php b/tests/Node/NodeTest.php index 94c9197b5..5a3003230 100644 --- a/tests/Node/NodeTest.php +++ b/tests/Node/NodeTest.php @@ -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(<< 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(<<assertEquals(<<