From 44e8bb024557c99bbf331b946a489d8b842b0dd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Michael=20Vo=C5=99=C3=AD=C5=A1ek?= Date: Fri, 8 Jul 2022 03:41:26 +0200 Subject: [PATCH] Fix memory leak in ExceptionWrapper --- src/Framework/ExceptionWrapper.php | 24 ++++++++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) diff --git a/src/Framework/ExceptionWrapper.php b/src/Framework/ExceptionWrapper.php index d1ff4abc6ae..00d40353a34 100644 --- a/src/Framework/ExceptionWrapper.php +++ b/src/Framework/ExceptionWrapper.php @@ -9,11 +9,13 @@ */ namespace PHPUnit\Framework; +use const PHP_VERSION_ID; use function array_keys; use function get_class; use function spl_object_hash; use PHPUnit\Util\Filter; use Throwable; +use WeakReference; /** * Wraps Exceptions thrown by code under test. @@ -38,6 +40,11 @@ final class ExceptionWrapper extends Exception */ protected $previous; + /** + * @var null|WeakReference + */ + private $originalException; + public function __construct(Throwable $t) { // PDOException::getCode() is a string. @@ -109,14 +116,23 @@ public function getOriginalException(): ?Throwable */ private function originalException(Throwable $exceptionToStore = null): ?Throwable { - static $originalExceptions; + // drop once PHP 7.3 support is removed + if (PHP_VERSION_ID < 70400) { + static $originalExceptions; - $instanceId = spl_object_hash($this); + $instanceId = spl_object_hash($this); + + if ($exceptionToStore) { + $originalExceptions[$instanceId] = $exceptionToStore; + } + + return $originalExceptions[$instanceId] ?? null; + } if ($exceptionToStore) { - $originalExceptions[$instanceId] = $exceptionToStore; + $this->originalException = WeakReference::create($exceptionToStore); } - return $originalExceptions[$instanceId] ?? null; + return $this->originalException !== null ? $this->originalException->get() : null; } }