Repository navigation
Expand file tree
/
Copy pathNodeWalker.php
More file actions
69 lines (58 loc) · 2.07 KB
/
Copy pathNodeWalker.php
File metadata and controls
69 lines (58 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?php
declare(strict_types=1);
/*
* This file is part of the PHPRegex package.
*
* (c) Younes ENNAJI <younes.ennaji.pro@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPRegex\Parser;
use PHPRegex\Parser\Node\NodeInterface;
/**
* Walks a tree depth first, in the order its nodes stand in the pattern,
* without a visitor for each kind of node: a callback on the way in, with
* the node's ancestors, and one on the way out.
*
* The walk keeps its own stack, so a pattern nested as deep as the parser
* allows does not exhaust PHP's.
*
* The public way to walk a tree is a visitor, and to look for nodes,
* NodeFinder.
*
* @internal
*/
final class NodeWalker
{
/**
* @param \Closure(NodeInterface, list<NodeInterface>):((TraversalAction|null)) $enter called before the node's children
* @param \Closure(NodeInterface, list<NodeInterface>):((TraversalAction|null))|null $leave called after them
*/
public static function walk(NodeInterface $root, \Closure $enter, ?\Closure $leave = null): void
{
/** @var list<array{NodeInterface, list<NodeInterface>, bool}> $stack a node, its ancestors, and whether it was entered */
$stack = [[$root, [], false]];
while ([] !== $stack) {
[$node, $ancestors, $entered] = array_pop($stack);
if ($entered) {
if (null !== $leave && TraversalAction::Stop === $leave($node, $ancestors)) {
return;
}
continue;
}
$action = $enter($node, $ancestors);
if (TraversalAction::Stop === $action) {
return;
}
$stack[] = [$node, $ancestors, true];
if (TraversalAction::SkipChildren === $action) {
continue;
}
$path = [...$ancestors, $node];
foreach (array_reverse($node->getChildren()) as $child) {
$stack[] = [$child, $path, false];
}
}
}
}