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; } }