Skip to content

Commit b459d0d

Browse files
aymanrbclaude
andcommitted
Validate prepared regex pattern before returning from prepareTemplate()
User-provided regex patterns in template variables (e.g. {%id:[0-9+%}) could silently produce broken PCRE and return empty results with no indication of the root cause. After building the final pattern, run a dummy preg_match() and throw InvalidTemplateSyntaxException with the PCRE error message when the pattern is invalid, enabling fast failure instead of silent data loss. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent ae758b5 commit b459d0d

2 files changed

Lines changed: 19 additions & 1 deletion

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 InvalidTemplateSyntaxException extends UnstructuredTextParserException
8+
{
9+
}

src/Helper/TemplatesHelper.php

Lines changed: 10 additions & 1 deletion
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\InvalidTemplateSyntaxException;
89
use aymanrb\UnstructuredTextParser\Exception\InvalidTemplateVariableNameException;
910

1011
class TemplatesHelper
@@ -133,10 +134,18 @@ static function (array $matches): string {
133134
$templateText
134135
) ?? $templateText;
135136

136-
return preg_replace(
137+
$preparedPattern = preg_replace(
137138
self::REGEX_GENERIC_VARIABLE,
138139
self::REPLACE_GENERIC_VARIABLE,
139140
$templateText
140141
) ?? $templateText;
142+
143+
if (@preg_match('/' . $preparedPattern . '/s', '') === false) {
144+
throw new InvalidTemplateSyntaxException(
145+
sprintf('Template produced an invalid regex pattern: %s', preg_last_error_msg())
146+
);
147+
}
148+
149+
return $preparedPattern;
141150
}
142151
}

0 commit comments

Comments
 (0)