diff --git a/src/Codeception/Lib/Connector/Yii2/ConnectionWatcher.php b/src/Codeception/Lib/Connector/Yii2/ConnectionWatcher.php index e3be083..58188e7 100644 --- a/src/Codeception/Lib/Connector/Yii2/ConnectionWatcher.php +++ b/src/Codeception/Lib/Connector/Yii2/ConnectionWatcher.php @@ -19,7 +19,7 @@ class ConnectionWatcher private readonly Closure $handler; /** - * @var list + * @var list<\WeakReference> */ private array $connections = []; @@ -35,7 +35,7 @@ public function __construct() protected function connectionOpened(Connection $connection): void { $this->debug('Connection opened!'); - $this->connections[] = $connection; + $this->connections[] = \WeakReference::create($connection); } public function start(): void @@ -54,9 +54,12 @@ public function closeAll(): void { $count = count($this->connections); $this->debug("closing all ($count) connections"); - foreach ($this->connections as $connection) { - $connection->close(); + foreach ($this->connections as $ref) { + if (null !== $connection = $ref->get()) { + $connection->close(); + } } + $this->connections = []; } /** diff --git a/src/Codeception/Module/Yii2.php b/src/Codeception/Module/Yii2.php index 30f3372..025b3f8 100644 --- a/src/Codeception/Module/Yii2.php +++ b/src/Codeception/Module/Yii2.php @@ -14,6 +14,7 @@ use Codeception\Lib\Framework; use Codeception\Lib\Interfaces\ActiveRecord; use Codeception\Lib\Interfaces\PartedModule; +use Codeception\Lib\ModuleContainer; use Codeception\TestInterface; use Exception; use PHPUnit\Framework\Assert; @@ -247,7 +248,7 @@ final class Yii2 extends Framework implements ActiveRecord, PartedModule /** * Helper to force database transaction */ - private TransactionForcer $transactionForcer; + private null|TransactionForcer $transactionForcer; /** * @var array The contents of upon initialization of this object. @@ -269,6 +270,14 @@ private function getClient(): Yii2Connector return $this->client; } + public function __construct(ModuleContainer $moduleContainer, ?array $config = null) + { + parent::__construct($moduleContainer, $config); + $this->connectionWatcher = new ConnectionWatcher(); + $this->connectionWatcher->start(); + } + + public function _initialize(): void { if ($this->config['transaction'] === null) { @@ -393,9 +402,6 @@ public function _before(TestInterface $test): void $this->yiiLogger = new Yii2Connector\Logger(); $this->getClient()->startApp($this->yiiLogger); - $this->connectionWatcher = new ConnectionWatcher(); - $this->connectionWatcher->start(); - // load fixtures before db transaction if ($test instanceof \Codeception\Test\Cest) { $this->loadFixtures($test->getTestInstance()); @@ -447,9 +453,7 @@ public function _after(TestInterface $test): void $this->getClient()->resetApplication(); if (isset($this->connectionWatcher)) { - $this->connectionWatcher->stop(); $this->connectionWatcher->closeAll(); - unset($this->connectionWatcher); } parent::_after($test);