Skip to content

Commit

Permalink
Fix memory leak in ExceptionWrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
mvorisek authored and sebastianbergmann committed Aug 23, 2022
1 parent 8885568 commit 44e8bb0
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/Framework/ExceptionWrapper.php
Expand Up @@ -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.
Expand All @@ -38,6 +40,11 @@ final class ExceptionWrapper extends Exception
*/
protected $previous;

/**
* @var null|WeakReference<Throwable>
*/
private $originalException;

public function __construct(Throwable $t)
{
// PDOException::getCode() is a string.
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 44e8bb0

Please sign in to comment.