$node->getAttribute('parent'), the previous
* node can be accessed through $node->getAttribute('previous')
,
* and the next node can be accessed through $node->getAttribute('next')
.
*/
final class NodeConnectingVisitor extends NodeVisitorAbstract {
/**
* @var Node[]
*/
private array $stack = [];
/**
* @var ?Node
*/
private $previous;
public function beforeTraverse(array $nodes) {
$this->stack = [];
$this->previous = null;
}
public function enterNode(Node $node) {
if (!empty($this->stack)) {
$node->setAttribute('parent', $this->stack[count($this->stack) - 1]);
}
if ($this->previous !== null && $this->previous->getAttribute('parent') === $node->getAttribute('parent')) {
$node->setAttribute('previous', $this->previous);
$this->previous->setAttribute('next', $node);
}
$this->stack[] = $node;
}
public function leaveNode(Node $node) {
$this->previous = $node;
array_pop($this->stack);
}
}