Skip to content

Commit 6fc375f

Browse files
committed
Allow to disable exceptions in the destructor
1 parent 4f6c795 commit 6fc375f

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

src/View.php

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ class View
4848
*/
4949
protected array $viewsPaths = [];
5050
protected string $instanceName;
51+
protected bool $throwExceptionsInDestructor = true;
5152

5253
public function __construct(?string $baseDir = null, string $extension = '.php')
5354
{
@@ -59,7 +60,7 @@ public function __construct(?string $baseDir = null, string $extension = '.php')
5960

6061
public function __destruct()
6162
{
62-
if ($this->openBlocks) {
63+
if ($this->isThrowExceptionsInDestructor() && $this->openBlocks) {
6364
throw new LogicException(
6465
'Trying to destruct a View instance while the following blocks stayed open: '
6566
. \implode(', ', \array_map(static function ($name) {
@@ -69,6 +70,24 @@ public function __destruct()
6970
}
7071
}
7172

73+
public function isThrowExceptionsInDestructor() : bool
74+
{
75+
return $this->throwExceptionsInDestructor;
76+
}
77+
78+
/**
79+
* Enables/disables exceptions in the destructor.
80+
*
81+
* @param bool $active True to throw exceptions, false otherwise
82+
*
83+
* @return static
84+
*/
85+
public function setThrowExceptionsInDestructor(bool $active = true) : static
86+
{
87+
$this->throwExceptionsInDestructor = $active;
88+
return $this;
89+
}
90+
7291
public function setBaseDir(string $baseDir) : static
7392
{
7493
$real = \realpath($baseDir);

tests/ViewTest.php

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,17 @@ public function testDestructWhenBlockIsOpen() : void
283283
unset($this->view);
284284
}
285285

286+
public function testDestructWhenBlockIsOpenAndThrowIsDisabled() : void
287+
{
288+
$this->view->setThrowExceptionsInDestructor(false);
289+
$this->view->block('foo');
290+
\ob_end_clean();
291+
$this->view->block('bar');
292+
\ob_end_clean();
293+
unset($this->view);
294+
self::assertTrue(true);
295+
}
296+
286297
protected function setDebugCollector() : void
287298
{
288299
$collector = new ViewsCollector();

0 commit comments

Comments
 (0)