cacheDir)) { mkdir($this->cacheDir); } if (!is_dir($this->tplDir)) { mkdir($this->tplDir); } $this->engine = new Engine($this->tplDir, true, $this->cacheDir); } protected function tearDown(): void { if (is_dir($this->cacheDir)) { array_map('unlink', glob("$this->cacheDir/*.*")); rmdir($this->cacheDir); } if (is_dir($this->tplDir)) { array_map('unlink', glob("$this->tplDir/*.*")); rmdir($this->tplDir); } } protected function execute(): void { $this->itRendersComment(); $this->itRendersSimpleVariables(); $this->itHandlesFiltersWithArguments(); $this->itExecutesLogicBlocks(); $this->itMapsErrorsToOriginalTemplateLine(); $this->itHandlesComplexLogicAndNotOperator(); $this->itHandlesForeachWithObjectsAndArrays(); $this->itHandlesComplexNestedLogic(); $this->itHandlesNestedForeachAndIf(); $this->itHandlesIsNotEmptySyntax(); $this->itHandlesNativeArraySyntax(); } public function itRendersComment() { $tpl = "{# {% include 'flash_bag.html.twig' %}#}\n{# {% include 'flash_bag.html.twig' %}#}"; file_put_contents($this->tplDir . '/comment.html', $tpl); $output = $this->engine->render('comment.html', []); $this->assertEquals('', trim($output)); } /** @test */ public function itRendersSimpleVariables() { $tpl = "Hello {{ user.name }}!"; file_put_contents($this->tplDir . '/test.html', $tpl); $output = $this->engine->render('test.html', ['user' => (object)['name' => 'Michel']]); $this->assertEquals("Hello Michel!", trim($output)); } /** @test */ public function itHandlesFiltersWithArguments() { $tpl = "Total: {{ price | round(2) }} €"; file_put_contents($this->tplDir . '/filter.html', $tpl); $output = $this->engine->render('filter.html', ['price' => 12.556]); $this->assertEquals("Total: 12.56 €", trim($output)); } /** @test */ public function itExecutesLogicBlocks() { $tpl = "{% if show %}YES{% else %}NO{% endif %}"; file_put_contents($this->tplDir . '/logic.html', $tpl); $this->assertEquals("YES", trim($this->engine->render('logic.html', ['show' => true]))); $this->assertEquals("NO", trim($this->engine->render('logic.html', ['show' => false]))); } /** @test */ public function itMapsErrorsToOriginalTemplateLine() { $tpl = "Line 1\nLine 2\n{{ undefined_var.property }}"; file_put_contents($this->tplDir . '/error.html', $tpl); try { $this->engine->render('error.html', []); $this->fail("L'exception aurait dû être lancée."); } catch (ErrorException $e) { // Vérification du mapping de ligne magique /*L:3;F:...*/ $this->assertEquals(3, $e->getLine()); $this->assertStringContains($e->getFile(), 'error.html'); } } /** @test */ public function itHandlesComplexLogicAndNotOperator() { $tpl = "{% if not user.is_active %}Inactif{% endif %}"; file_put_contents($this->tplDir . '/not.html', $tpl); $output = $this->engine->render('not.html', ['user' => (object)['is_active' => false]]); $this->assertEquals("Inactif", trim($output)); } /** @test */ public function itHandlesForeachWithObjectsAndArrays() { $tpl = "