Skip to content

Commit edc3712

Browse files
aymanrbclaude
andcommitted
Cache prepared template regex patterns to avoid redundant disk I/O
Each call to parseText() previously triggered a file_get_contents() + full regex compilation pass for every template in the directory. Add an in-memory cache (keyed by file path) on the TemplatesHelper instance so that subsequent parseText() calls on the same parser reuse the compiled patterns, cutting redundant I/O and regex compilation to zero. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
1 parent b459d0d commit edc3712

1 file changed

Lines changed: 14 additions & 2 deletions

File tree

src/Helper/TemplatesHelper.php

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@ class TemplatesHelper
2121

2222
private readonly \FilesystemIterator $directoryIterator;
2323

24+
/** @var array<string, string> */
25+
private array $templateCache = [];
26+
2427
public function __construct(string $templatesDir)
2528
{
2629
$this->directoryIterator = $this->createTemplatesDirIterator($templatesDir);
@@ -63,7 +66,7 @@ private function findTemplate(string $text): array
6366

6467
if ($matchPercentage > $maxMatch) {
6568
$maxMatch = $matchPercentage;
66-
$matchedTemplate = [$fileInfo->getPathname() => $this->prepareTemplate($templateContent)];
69+
$matchedTemplate = [$fileInfo->getPathname() => $this->getCachedPreparedTemplate($fileInfo->getPathname(), $templateContent)];
6770
}
6871
}
6972

@@ -84,14 +87,23 @@ private function getAllValidTemplates(): array
8487
continue;
8588
}
8689

87-
$templates[$fileInfo->getPathname()] = $this->prepareTemplate($templateContent);
90+
$templates[$fileInfo->getPathname()] = $this->getCachedPreparedTemplate($fileInfo->getPathname(), $templateContent);
8891
}
8992

9093
krsort($templates);
9194

9295
return $templates;
9396
}
9497

98+
private function getCachedPreparedTemplate(string $filePath, string $templateContent): string
99+
{
100+
if (!isset($this->templateCache[$filePath])) {
101+
$this->templateCache[$filePath] = $this->prepareTemplate($templateContent);
102+
}
103+
104+
return $this->templateCache[$filePath];
105+
}
106+
95107
private function validateVariableNames(string $templateText): void
96108
{
97109
preg_match_all('/\{%([^%:]+)(?::[^%]*)?\%\}/', $templateText, $matches);

0 commit comments

Comments
 (0)