Skip to content

Commit ae758b5

Browse files
aymanrbclaude
andcommitted
Validate PCRE named capture group names in template variables
Template variables like {%my-var%} or {%123abc%} produce invalid PCRE named capture groups, causing silent regex failures and empty results. Validate each variable name against /^[a-zA-Z_][a-zA-Z0-9_]*$/ in TemplatesHelper::prepareTemplate() and throw InvalidTemplateVariableNameException with a clear message on violation. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent 3a8a43b commit ae758b5

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
<?php
2+
3+
declare(strict_types = 1);
4+
5+
namespace aymanrb\UnstructuredTextParser\Exception;
6+
7+
class InvalidTemplateVariableNameException extends UnstructuredTextParserException
8+
{
9+
}

src/Helper/TemplatesHelper.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
namespace aymanrb\UnstructuredTextParser\Helper;
66

77
use aymanrb\UnstructuredTextParser\Exception\InvalidTemplatesDirectoryException;
8+
use aymanrb\UnstructuredTextParser\Exception\InvalidTemplateVariableNameException;
89

910
class TemplatesHelper
1011
{
@@ -90,8 +91,26 @@ private function getAllValidTemplates(): array
9091
return $templates;
9192
}
9293

94+
private function validateVariableNames(string $templateText): void
95+
{
96+
preg_match_all('/\{%([^%:]+)(?::[^%]*)?\%\}/', $templateText, $matches);
97+
98+
foreach ($matches[1] as $variableName) {
99+
if (!preg_match('/^[a-zA-Z_][a-zA-Z0-9_]*$/', $variableName)) {
100+
throw new InvalidTemplateVariableNameException(
101+
sprintf(
102+
'Invalid template variable name "%s": must start with a letter or underscore and contain only alphanumeric characters and underscores.',
103+
$variableName
104+
)
105+
);
106+
}
107+
}
108+
}
109+
93110
private function prepareTemplate(string $templateText): string
94111
{
112+
$this->validateVariableNames($templateText);
113+
95114
$templateText = preg_quote($templateText, '/');
96115

97116
$templateText = preg_replace(

0 commit comments

Comments
 (0)