Refactor Template class to lazy load the Twig Environment
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 <mauricio@fauth.dev>
This commit is contained in:
parent
f110beb5f3
commit
946fa9dd66
@ -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) {
|
||||
|
||||
@ -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'));
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user