Skip to content

Commit 1e2114c

Browse files
Merge pull request #18468 from MauricioFauth/template-twig-env
Refactor Template class to lazy load the Twig Environment
2 parents f110beb + 946fa9d commit 1e2114c

2 files changed

Lines changed: 25 additions & 8 deletions

File tree

libraries/classes/Template.php

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -40,20 +40,16 @@ class Template
4040
/**
4141
* Twig environment
4242
*/
43-
protected static Environment $twig;
43+
protected static Environment|null $twig = null;
4444

4545
public const TEMPLATES_FOLDER = ROOT_PATH . 'templates';
4646

47+
private Config|null $config;
48+
4749
public function __construct(Config|null $config = null)
4850
{
49-
if (isset(static::$twig)) {
50-
return;
51-
}
52-
5351
$config = $config ?? $GLOBALS['config'] ?? null;
54-
$cacheDir = $config?->getTempDir('twig');
55-
56-
static::$twig = self::getTwigEnvironment($cacheDir);
52+
$this->config = $config instanceof Config ? $config : null;
5753
}
5854

5955
public static function getTwigEnvironment(string|null $cacheDir): Environment
@@ -104,6 +100,10 @@ public static function getTwigEnvironment(string|null $cacheDir): Environment
104100
*/
105101
private function load(string $templateName): TemplateWrapper
106102
{
103+
if (static::$twig === null) {
104+
static::$twig = self::getTwigEnvironment($this->config?->getTempDir('twig'));
105+
}
106+
107107
try {
108108
$template = static::$twig->load($templateName . '.twig');
109109
} catch (RuntimeException $e) {

test/classes/TemplateTest.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,11 @@
44

55
namespace PhpMyAdmin\Tests;
66

7+
use PhpMyAdmin\Config;
78
use PhpMyAdmin\Template;
89
use PhpMyAdmin\Twig\Extensions\Node\TransNode;
10+
use PHPUnit\Framework\Attributes\PreserveGlobalState;
11+
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
912
use Twig\Error\LoaderError;
1013

1114
/** @covers \PhpMyAdmin\Template */
@@ -161,4 +164,18 @@ public static function providerTestRenderGettext(): array
161164
['test/gettext/plural_notes', ['table_count' => 2], '2 tables'],
162165
];
163166
}
167+
168+
#[RunInSeparateProcess]
169+
#[PreserveGlobalState(false)]
170+
public function testLoadingTwigEnvOnlyOnce(): void
171+
{
172+
$config = $this->createMock(Config::class);
173+
$config->expects($this->once())->method('getTempDir')->with($this->equalTo('twig'))->willReturn(null);
174+
175+
$template = new Template($config);
176+
$this->assertSame('static content', $template->render('test/static'));
177+
178+
$template2 = new Template($config);
179+
$this->assertSame('static content', $template2->render('test/static'));
180+
}
164181
}

0 commit comments

Comments
 (0)