Skip to content

Commit

Permalink
bug twigphp#3949 Simplify code when using ob_* functions (fabpot)
Browse files Browse the repository at this point in the history
This PR was merged into the 3.x branch.

Discussion
----------

Simplify code when using `ob_*` functions

And fixed an edge case (see the modified test).

Commits
-------

0b9e30e Simplify code
  • Loading branch information
fabpot committed Dec 20, 2023
2 parents 83dfc0f + 0b9e30e commit 7072a72
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 26 deletions.
11 changes: 10 additions & 1 deletion src/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -235,12 +235,21 @@ public function renderParentBlock($name, array $context, array $blocks = [])
*/
public function renderBlock($name, array $context, array $blocks = [], $useBlocks = true)
{
$level = ob_get_level();
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
$this->displayBlock($name, $context, $blocks, $useBlocks);
try {
$this->displayBlock($name, $context, $blocks, $useBlocks);
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}

throw $e;
}

return ob_get_clean();
}
Expand Down
19 changes: 1 addition & 18 deletions src/TemplateWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,24 +60,7 @@ public function getBlockNames(array $context = []): array

public function renderBlock(string $name, array $context = []): string
{
$context = $this->env->mergeGlobals($context);
$level = ob_get_level();
if ($this->env->isDebug()) {
ob_start();
} else {
ob_start(function () { return ''; });
}
try {
$this->template->displayBlock($name, $context);
} catch (\Throwable $e) {
while (ob_get_level() > $level) {
ob_end_clean();
}

throw $e;
}

return ob_get_clean();
return $this->template->renderBlock($name, $this->env->mergeGlobals($context));
}

public function displayBlock(string $name, array $context = [])
Expand Down
8 changes: 1 addition & 7 deletions tests/TemplateTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -130,13 +130,7 @@ public function testRenderBlockWithUndefinedBlock()

$twig = new Environment($this->createMock(LoaderInterface::class));
$template = new TemplateForTest($twig, 'index.twig');
try {
$template->renderBlock('unknown', []);
} catch (\Exception $e) {
ob_end_clean();

throw $e;
}
$template->renderBlock('unknown', []);
}

public function testDisplayBlockWithUndefinedBlock()
Expand Down

0 comments on commit 7072a72

Please sign in to comment.