-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTypoScriptStatementsIterator.php
More file actions
100 lines (84 loc) · 2.76 KB
/
Copy pathTypoScriptStatementsIterator.php
File metadata and controls
100 lines (84 loc) · 2.76 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
declare(strict_types=1);
namespace a9f\FractorTypoScript;
use a9f\Fractor\Application\ValueObject\File;
use a9f\FractorTypoScript\Contract\TypoScriptNodeVisitor;
use Helmich\TypoScriptParser\Parser\AST\ConditionalStatement;
use Helmich\TypoScriptParser\Parser\AST\NestedAssignment;
use Helmich\TypoScriptParser\Parser\AST\Statement;
use Webmozart\Assert\Assert;
final readonly class TypoScriptStatementsIterator
{
/**
* @var int
*/
public const REMOVE_NODE = 3;
/**
* @var array<TypoScriptNodeVisitor>
*/
private iterable $visitors;
/**
* @param list<TypoScriptNodeVisitor> $visitors
*/
public function __construct(iterable $visitors)
{
$visitors = iterator_to_array($visitors);
Assert::allIsInstanceOf($visitors, TypoScriptNodeVisitor::class);
$this->visitors = $visitors;
}
/**
* @param list<Statement> $statements
* @return list<Statement>
*/
public function traverseDocument(File $file, array $statements): array
{
foreach ($this->visitors as $visitor) {
$visitor->beforeTraversal($file, $statements);
}
$resultingStatements = $this->processStatementList($statements);
foreach ($this->visitors as $visitor) {
$visitor->afterTraversal($statements);
}
return $resultingStatements;
}
/**
* @param list<Statement> $statements
* @return list<Statement>
*/
private function processStatementList(array $statements): array
{
$resultingStatements = [];
foreach ($statements as $statement) {
$result = $this->traverseNode($statement);
if ($result instanceof Statement) {
$resultingStatements[] = [$result];
}
}
return array_merge(...$resultingStatements);
}
private function traverseNode(Statement $node): int|Statement|null
{
$lastCalledVisitor = null;
$result = $node;
foreach ($this->visitors as $visitor) {
$result = $visitor->enterNode($node);
if (is_int($result)) {
$lastCalledVisitor = $visitor;
break;
}
}
if ($node instanceof ConditionalStatement) {
$node->ifStatements = $this->processStatementList($node->ifStatements);
$node->elseStatements = $this->processStatementList($node->elseStatements);
} elseif ($node instanceof NestedAssignment) {
$node->statements = $this->processStatementList($node->statements);
}
foreach ($this->visitors as $visitor) {
if ($lastCalledVisitor === $visitor) {
break;
}
$visitor->leaveNode($node);
}
return $result;
}
}