diff --git a/flight/template/View.php b/flight/template/View.php index c43a35f6..15e4fc87 100644 --- a/flight/template/View.php +++ b/flight/template/View.php @@ -20,6 +20,8 @@ class View /** File extension. */ public string $extension = '.php'; + public bool $preserveVars = true; + /** * View variables. * @@ -114,12 +116,16 @@ public function render(string $file, ?array $data = null): void throw new \Exception("Template file not found: {$normalized_path}."); } - if (\is_array($data)) { - $this->vars = \array_merge($this->vars, $data); - } - \extract($this->vars); + if (\is_array($data) === true) { + \extract($data); + + if ($this->preserveVars === true) { + $this->vars = \array_merge($this->vars, $data); + } + } + include $this->template; } diff --git a/tests/FlightTest.php b/tests/FlightTest.php index d84336be..5d196d6f 100644 --- a/tests/FlightTest.php +++ b/tests/FlightTest.php @@ -22,6 +22,7 @@ protected function setUp(): void $_REQUEST = []; Flight::init(); Flight::setEngine(new Engine()); + Flight::set('flight.views.path', __DIR__ . '/views'); } protected function tearDown(): void @@ -354,4 +355,43 @@ public function after() $this->expectOutputString('Thisisaroutewithhtml'); } + + /** @dataProvider \tests\ViewTest::renderDataProvider */ + public function testDoesNotPreserveVarsWhenFlagIsDisabled( + string $output, + array $renderParams, + string $regexp + ): void + { + Flight::view()->preserveVars = false; + + $this->expectOutputString($output); + Flight::render(...$renderParams); + + set_error_handler(function (int $code, string $message) use ($regexp): void { + $this->assertMatchesRegularExpression($regexp, $message); + }); + + Flight::render($renderParams[0]); + + restore_error_handler(); + } + + public function testKeepThePreviousStateOfOneViewComponentByDefault(): void + { + $this->expectOutputString(<<Hi +