From edaf459c54546c61a7bc12ae3ab3b4fcc56c32b0 Mon Sep 17 00:00:00 2001 From: SonyPradana Date: Sat, 14 Sep 2024 09:37:33 +0700 Subject: [PATCH] feat: cache Templator when using `file_get_contents()` --- src/System/View/InteractWithCacheTrait.php | 20 +++++++++++++++++++ .../View/Templator/IncludeTemplator.php | 14 ++++++++++++- .../View/Templator/SectionTemplator.php | 14 ++++++++++++- 3 files changed, 46 insertions(+), 2 deletions(-) create mode 100644 src/System/View/InteractWithCacheTrait.php diff --git a/src/System/View/InteractWithCacheTrait.php b/src/System/View/InteractWithCacheTrait.php new file mode 100644 index 00000000..adf3cf99 --- /dev/null +++ b/src/System/View/InteractWithCacheTrait.php @@ -0,0 +1,20 @@ + + */ + private static array $cache = []; + public function maksDept(int $maks_dept): self { $this->maks_dept = $maks_dept; @@ -19,6 +29,8 @@ public function maksDept(int $maks_dept): self public function parse(string $template): string { + self::$cache = []; + return preg_replace_callback( '/{%\s*include\s*\(\s*[\'"]([^\'"]+)[\'"]\s*\)\s*%}/', function ($matches) { @@ -27,7 +39,7 @@ function ($matches) { } $templatePath = $this->finder->find($matches[1]); - $includedTemplate = file_get_contents($templatePath); + $includedTemplate = $this->getContents($templatePath); if ($this->maks_dept === 0) { return $includedTemplate; diff --git a/src/System/View/Templator/SectionTemplator.php b/src/System/View/Templator/SectionTemplator.php index 587239c8..2110fe2a 100644 --- a/src/System/View/Templator/SectionTemplator.php +++ b/src/System/View/Templator/SectionTemplator.php @@ -6,14 +6,26 @@ use System\Text\Str; use System\View\AbstractTemplatorParse; +use System\View\InteractWithCacheTrait; class SectionTemplator extends AbstractTemplatorParse { + use InteractWithCacheTrait; + /** @var array */ private $sections = []; + /** + * File get content cached. + * + * @var array + */ + private static array $cache = []; + public function parse(string $template): string { + self::$cache = []; + preg_match('/{%\s*extend\s*\(\s*[\'"]([^\'"]+)[\'"]\s*\)\s*%}/', $template, $matches_layout); if (!array_key_exists(1, $matches_layout)) { return $template; @@ -24,7 +36,7 @@ public function parse(string $template): string } $templatePath = $this->finder->find($matches_layout[1]); - $layout = file_get_contents($templatePath); + $layout = $this->getContents($templatePath); $template = preg_replace_callback( '/{%\s*section\s*\(\s*[\'"]([^\'"]+)[\'"]\s*,\s*[\'"]([^\'"]+)[\'"]\s*\)\s*%}/s',