Skip to content

Commit 44e8bb0

Browse files
mvoriseksebastianbergmann
authored andcommitted
Fix memory leak in ExceptionWrapper
1 parent 8885568 commit 44e8bb0

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/Framework/ExceptionWrapper.php

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,13 @@
99
*/
1010
namespace PHPUnit\Framework;
1111

12+
use const PHP_VERSION_ID;
1213
use function array_keys;
1314
use function get_class;
1415
use function spl_object_hash;
1516
use PHPUnit\Util\Filter;
1617
use Throwable;
18+
use WeakReference;
1719

1820
/**
1921
* Wraps Exceptions thrown by code under test.
@@ -38,6 +40,11 @@ final class ExceptionWrapper extends Exception
3840
*/
3941
protected $previous;
4042

43+
/**
44+
* @var null|WeakReference<Throwable>
45+
*/
46+
private $originalException;
47+
4148
public function __construct(Throwable $t)
4249
{
4350
// PDOException::getCode() is a string.
@@ -109,14 +116,23 @@ public function getOriginalException(): ?Throwable
109116
*/
110117
private function originalException(Throwable $exceptionToStore = null): ?Throwable
111118
{
112-
static $originalExceptions;
119+
// drop once PHP 7.3 support is removed
120+
if (PHP_VERSION_ID < 70400) {
121+
static $originalExceptions;
113122

114-
$instanceId = spl_object_hash($this);
123+
$instanceId = spl_object_hash($this);
124+
125+
if ($exceptionToStore) {
126+
$originalExceptions[$instanceId] = $exceptionToStore;
127+
}
128+
129+
return $originalExceptions[$instanceId] ?? null;
130+
}
115131

116132
if ($exceptionToStore) {
117-
$originalExceptions[$instanceId] = $exceptionToStore;
133+
$this->originalException = WeakReference::create($exceptionToStore);
118134
}
119135

120-
return $originalExceptions[$instanceId] ?? null;
136+
return $this->originalException !== null ? $this->originalException->get() : null;
121137
}
122138
}

0 commit comments

Comments
 (0)