From 946fa9dd66d01524e91ee355fdcc541d12a08798 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maur=C3=ADcio=20Meneghini=20Fauth?= Date: Tue, 30 May 2023 17:55:30 -0300 Subject: [PATCH] Refactor Template class to lazy load the Twig Environment MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Loads the Twig Environment class only when rendering a template for the first time, not when constructing the Template object. Signed-off-by: MaurĂ­cio Meneghini Fauth --- libraries/classes/Template.php | 16 ++++++++-------- test/classes/TemplateTest.php | 17 +++++++++++++++++ 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/libraries/classes/Template.php b/libraries/classes/Template.php index 8f7547ed49..dd884ad95e 100644 --- a/libraries/classes/Template.php +++ b/libraries/classes/Template.php @@ -40,20 +40,16 @@ class Template /** * Twig environment */ - protected static Environment $twig; + protected static Environment|null $twig = null; public const TEMPLATES_FOLDER = ROOT_PATH . 'templates'; + private Config|null $config; + public function __construct(Config|null $config = null) { - if (isset(static::$twig)) { - return; - } - $config = $config ?? $GLOBALS['config'] ?? null; - $cacheDir = $config?->getTempDir('twig'); - - static::$twig = self::getTwigEnvironment($cacheDir); + $this->config = $config instanceof Config ? $config : null; } public static function getTwigEnvironment(string|null $cacheDir): Environment @@ -104,6 +100,10 @@ class Template */ private function load(string $templateName): TemplateWrapper { + if (static::$twig === null) { + static::$twig = self::getTwigEnvironment($this->config?->getTempDir('twig')); + } + try { $template = static::$twig->load($templateName . '.twig'); } catch (RuntimeException $e) { diff --git a/test/classes/TemplateTest.php b/test/classes/TemplateTest.php index 9516152783..10adab631c 100644 --- a/test/classes/TemplateTest.php +++ b/test/classes/TemplateTest.php @@ -4,8 +4,11 @@ declare(strict_types=1); namespace PhpMyAdmin\Tests; +use PhpMyAdmin\Config; use PhpMyAdmin\Template; use PhpMyAdmin\Twig\Extensions\Node\TransNode; +use PHPUnit\Framework\Attributes\PreserveGlobalState; +use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Twig\Error\LoaderError; /** @covers \PhpMyAdmin\Template */ @@ -161,4 +164,18 @@ class TemplateTest extends AbstractTestCase ['test/gettext/plural_notes', ['table_count' => 2], '2 tables'], ]; } + + #[RunInSeparateProcess] + #[PreserveGlobalState(false)] + public function testLoadingTwigEnvOnlyOnce(): void + { + $config = $this->createMock(Config::class); + $config->expects($this->once())->method('getTempDir')->with($this->equalTo('twig'))->willReturn(null); + + $template = new Template($config); + $this->assertSame('static content', $template->render('test/static')); + + $template2 = new Template($config); + $this->assertSame('static content', $template2->render('test/static')); + } }