88
99class TemplatesHelper
1010{
11+ private const REGEX_GENERIC_VARIABLE = '/ \\\{%(.*)% \\\}/U ' ; //{%Var%}
12+ private const REGEX_VARIABLE_WITH_PATTERN = '/ \\\{%([^%]+):(.*)% \\\}/U ' ; //{%Var:Pattern%}
13+ private const REGEX_PREPARED_VARIABLE_WITH_PATTERN = '/(\(\?[^)]*)./ ' ; //(?<Var\>Pattern)
14+ private const REGEX_ORPHAN_BACKSLASH = '/(?<! \\\\) \\\\(?! \\\\)/ ' ;
15+ private const STR_SEARCH_TRIPLE_BACKSLASHES = '\\\\\\' ;
16+
17+ private const REPLACE_GENERIC_VARIABLE = '(?<$1>.*) ' ; //(?<Var>.*)
18+ private const REPLACE_VARIABLE_WITH_PATTERN = '(?<$1>$2) ' ; //(?<Var>Pattern)
19+
1120 private \FilesystemIterator $ directoryIterator ;
1221
1322 public function __construct (string $ templatesDir )
@@ -76,19 +85,26 @@ private function prepareTemplate(string $templateText): string
7685 {
7786 $ templateText = preg_quote ($ templateText , '/ ' );
7887
79- // replace all {%Var:Pattern%} in the template with (?<Var>Pattern) regex vars
80- $ templateText = preg_replace ('/ \\\{%([^%]+):(.*)% \\\}/U ' , '(?<$1>$2) ' , $ templateText );
88+ $ templateText = preg_replace (
89+ self ::REGEX_VARIABLE_WITH_PATTERN ,
90+ self ::REPLACE_VARIABLE_WITH_PATTERN ,
91+ $ templateText
92+ );
8193
82- // remove the regex escaped characters of the provided patterns
8394 $ templateText = preg_replace_callback (
84- ' /(\(\?[^)]*)./ ' ,
95+ self :: REGEX_PREPARED_VARIABLE_WITH_PATTERN ,
8596 function ($ matches ) {
86- return str_replace ('\\' , '' , $ matches [0 ]);
97+ $ variableWithPattern = preg_replace (self ::REGEX_ORPHAN_BACKSLASH , '' , $ matches [0 ]);
98+
99+ return str_replace (self ::STR_SEARCH_TRIPLE_BACKSLASHES , '\\' , $ variableWithPattern );
87100 },
88101 $ templateText
89102 );
90103
91- // replace all {%Var%} in the template with (?<Var>.*) regex vars
92- return preg_replace ('/ \\\{%(.*)% \\\}/U ' , '(?<$1>.*) ' , $ templateText );
104+ return preg_replace (
105+ self ::REGEX_GENERIC_VARIABLE ,
106+ self ::REPLACE_GENERIC_VARIABLE ,
107+ $ templateText
108+ );
93109 }
94110}
0 commit comments