Skip to content

Commit

Permalink
handle templates with errors when extracting variables
Browse files Browse the repository at this point in the history
  • Loading branch information
danilopolani committed Mar 19, 2024
1 parent 4332580 commit f27ecef
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/Helpers/TemplateManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,14 @@ public function extractVariableNames(): array
$source = $this->template->layout?->content . $this->template->content;

$twig = new Environment(new ArrayLoader());
$nodes = $twig->parse(
$twig->tokenize(new Source($source, ''))
)->getNode('body')->getNode('0');

try {
$nodes = $twig->parse(
$twig->tokenize(new Source($source, ''))
)->getNode('body')->getNode('0');
} catch (\Exception) {
return [];
}

preg_match_all("|Twig\\\Node\\\Expression\\\NameExpression\(name\: '(.*)'|mi", (string) $nodes, $matches);

Expand Down
14 changes: 14 additions & 0 deletions tests/Unit/TemplateManager/ExtractVariableNamesTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,17 @@

expect($output)->toBe(['headline', 'name', 'ctaUrl', 'isPremium', 'tierLevel']);
});

it('returns empty array for a template with errors', function () {
$template = new Template([
'content' => <<<'TWIG'
Hello {{ name }},
{% if isPremium|default(false) %%}
{{ tierLevel|title }}
TWIG,
]);

$output = TemplateManager::make($template)->extractVariableNames();

expect($output)->toBe([]);
});

0 comments on commit f27ecef

Please sign in to comment.