From f27ecef5c1ca724cd4eff236d57dba322fae5391 Mon Sep 17 00:00:00 2001 From: danilopolani Date: Tue, 19 Mar 2024 10:11:48 +0100 Subject: [PATCH] handle templates with errors when extracting variables --- src/Helpers/TemplateManager.php | 11 ++++++++--- .../TemplateManager/ExtractVariableNamesTest.php | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/Helpers/TemplateManager.php b/src/Helpers/TemplateManager.php index 66468f6..d348bb9 100644 --- a/src/Helpers/TemplateManager.php +++ b/src/Helpers/TemplateManager.php @@ -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); diff --git a/tests/Unit/TemplateManager/ExtractVariableNamesTest.php b/tests/Unit/TemplateManager/ExtractVariableNamesTest.php index 38fa7e6..aa53a0a 100644 --- a/tests/Unit/TemplateManager/ExtractVariableNamesTest.php +++ b/tests/Unit/TemplateManager/ExtractVariableNamesTest.php @@ -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([]); +});