6
6
use MailCarrier \Models \Template ;
7
7
use Twig \Environment ;
8
8
use Twig \Loader \ArrayLoader ;
9
+ use Twig \Node ;
9
10
use Twig \Source ;
10
11
11
12
class TemplateManager
@@ -31,6 +32,7 @@ public static function makeFromId(string $templateId, string $content): static
31
32
32
33
public function extractVariableNames (): array
33
34
{
35
+ $ variables = [];
34
36
$ source = $ this ->template ->layout ?->content . $ this ->template ->content ;
35
37
36
38
$ twig = new Environment (new ArrayLoader );
@@ -43,9 +45,9 @@ public function extractVariableNames(): array
43
45
return [];
44
46
}
45
47
46
- preg_match_all ( " |Twig \\ \Node \\ \Expression \\ \NameExpression\(name\: '(.*)'|mi " , ( string ) $ nodes , $ matches );
48
+ $ this -> extractVariables ( $ nodes , $ variables );
47
49
48
- return array_values (array_unique ($ matches [ 1 ] ));
50
+ return array_values (array_unique ($ variables ));
49
51
}
50
52
51
53
protected function getLoader (): ArrayLoader
@@ -63,4 +65,17 @@ protected function getLoader(): ArrayLoader
63
65
$ layoutFileName => $ this ->template ->layout ?->content,
64
66
]);
65
67
}
68
+
69
+ protected function extractVariables (Node \Node $ node , array &$ variables ): void
70
+ {
71
+ if ($ node instanceof Node \Expression \Variable \ContextVariable) {
72
+ $ variables [] = $ node ->getAttribute ('name ' );
73
+ }
74
+
75
+ foreach ($ node as $ child ) {
76
+ if ($ child instanceof Node \Node) {
77
+ $ this ->extractVariables ($ child , $ variables );
78
+ }
79
+ }
80
+ }
66
81
}
0 commit comments