Skip to content

Commit 6773ab2

Browse files
committed
fix variables extraction
1 parent 0898ba9 commit 6773ab2

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

src/Helpers/TemplateManager.php

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use MailCarrier\Models\Template;
77
use Twig\Environment;
88
use Twig\Loader\ArrayLoader;
9+
use Twig\Node;
910
use Twig\Source;
1011

1112
class TemplateManager
@@ -31,6 +32,7 @@ public static function makeFromId(string $templateId, string $content): static
3132

3233
public function extractVariableNames(): array
3334
{
35+
$variables = [];
3436
$source = $this->template->layout?->content . $this->template->content;
3537

3638
$twig = new Environment(new ArrayLoader);
@@ -43,9 +45,9 @@ public function extractVariableNames(): array
4345
return [];
4446
}
4547

46-
preg_match_all("|Twig\\\Node\\\Expression\\\NameExpression\(name\: '(.*)'|mi", (string) $nodes, $matches);
48+
$this->extractVariables($nodes, $variables);
4749

48-
return array_values(array_unique($matches[1]));
50+
return array_values(array_unique($variables));
4951
}
5052

5153
protected function getLoader(): ArrayLoader
@@ -63,4 +65,17 @@ protected function getLoader(): ArrayLoader
6365
$layoutFileName => $this->template->layout?->content,
6466
]);
6567
}
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+
}
6681
}

0 commit comments

Comments
 (0)