Skip to content

Commit d72f144

Browse files
committed
fix: improve exception handling and code consistency
- Standardized `RuntimeException` usage by removing redundant namespace references. - Refactored `findAndLoginUser` for clarity using ternary assignment. - Used `readonly` property for `ignoreCollidingDSN` in `TransactionForcer`. - Optimized server params handling by introducing `getServerParams()`. - Improved configuration validation messages for clean and mail methods.
1 parent 182edcf commit d72f144

File tree

4 files changed

+43
-58
lines changed

4 files changed

+43
-58
lines changed

src/Codeception/Lib/Connector/Yii2.php

+10-16
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
use Codeception\Lib\Connector\Yii2\TestMailer;
1111
use Codeception\Util\Debug;
1212
use InvalidArgumentException;
13+
use RuntimeException;
1314
use Symfony\Component\BrowserKit\AbstractBrowser as Client;
1415
use Symfony\Component\BrowserKit\Cookie;
1516
use Symfony\Component\BrowserKit\CookieJar;
@@ -142,14 +143,14 @@ protected function getApplication(): \yii\base\Application
142143
if (! isset(Yii::$app)) {
143144
$this->startApp();
144145
}
145-
return Yii::$app ?? throw new \RuntimeException('Failed to create Yii2 application');
146+
return Yii::$app ?? throw new RuntimeException('Failed to create Yii2 application');
146147
}
147148

148149
private function getWebRequest(): YiiRequest
149150
{
150151
$request = $this->getApplication()->request;
151152
if (! $request instanceof YiiRequest) {
152-
throw new \RuntimeException('Request component is not of type ' . YiiRequest::class);
153+
throw new RuntimeException('Request component is not of type ' . YiiRequest::class);
153154
}
154155
return $request;
155156
}
@@ -172,8 +173,7 @@ public function resetApplication(bool $closeSession = true): void
172173
* Finds and logs in a user
173174
*
174175
* @internal
175-
* @throws ConfigurationException
176-
* @throws \RuntimeException
176+
* @throws ConfigurationException|RuntimeException
177177
*/
178178
public function findAndLoginUser(int|string|IdentityInterface $user): void
179179
{
@@ -183,15 +183,9 @@ public function findAndLoginUser(int|string|IdentityInterface $user): void
183183
throw new ConfigurationException('The user component is not configured');
184184
}
185185

186-
if ($user instanceof IdentityInterface) {
187-
$identity = $user;
188-
} else {
189-
// class name implementing IdentityInterface
190-
$identityClass = $userComponent->identityClass;
191-
$identity = $identityClass::findIdentity($user);
192-
if ($identity === null) {
193-
throw new \RuntimeException('User not found');
194-
}
186+
$identity = $user instanceof IdentityInterface ? $user : ($userComponent->identityClass)::findIdentity($user);
187+
if ($identity === null) {
188+
throw new RuntimeException('User not found');
195189
}
196190
$userComponent->login($identity);
197191
}
@@ -273,7 +267,7 @@ function ($matches) use (&$parameters): string {
273267
);
274268
}
275269
if ($template === null) {
276-
throw new \RuntimeException("Failed to parse domain regex");
270+
throw new RuntimeException("Failed to parse domain regex");
277271
}
278272
$template = preg_quote($template);
279273
$template = strtr($template, $parameters);
@@ -411,9 +405,9 @@ public function doRequest(object $request): Response
411405

412406
$content = ob_get_clean();
413407
if (empty($content) && ! empty($yiiResponse->content) && ! isset($yiiResponse->stream)) {
414-
throw new \RuntimeException('No content was sent from Yii application');
408+
throw new RuntimeException('No content was sent from Yii application');
415409
} elseif ($content === false) {
416-
throw new \RuntimeException('Failed to get output buffer');
410+
throw new RuntimeException('Failed to get output buffer');
417411
}
418412

419413
return new Response($content, $yiiResponse->statusCode, $yiiResponse->getHeaders()->toArray());

src/Codeception/Lib/Connector/Yii2/Logger.php

+5-4
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,17 @@
55
namespace Codeception\Lib\Connector\Yii2;
66

77
use Codeception\Util\Debug;
8+
use SplQueue;
89
use yii\base\Exception as YiiException;
910
use yii\helpers\VarDumper;
1011
use yii\log\Logger as YiiLogger;
1112

1213
final class Logger extends YiiLogger
1314
{
1415
/**
15-
* @var \SplQueue<string>
16+
* @var SplQueue<string>
1617
*/
17-
private \SplQueue $logQueue;
18+
private SplQueue $logQueue;
1819

1920
/**
2021
* @param array<string, mixed> $config
@@ -24,7 +25,7 @@ public function __construct(
2425
array $config = []
2526
) {
2627
parent::__construct($config);
27-
$this->logQueue = new \SplQueue();
28+
$this->logQueue = new SplQueue();
2829
}
2930

3031
public function init(): void
@@ -69,7 +70,7 @@ public function log($message, $level, $category = 'application'): void
6970
public function getAndClearLog(): string
7071
{
7172
$logs = iterator_to_array($this->logQueue);
72-
$this->logQueue = new \SplQueue();
73+
$this->logQueue = new SplQueue();
7374
return implode(PHP_EOL, $logs) . PHP_EOL;
7475
}
7576
}

src/Codeception/Lib/Connector/Yii2/TransactionForcer.php

+7-10
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ final class TransactionForcer extends ConnectionWatcher
2929
private array $transactions = [];
3030

3131
public function __construct(
32-
private bool $ignoreCollidingDSN
32+
private readonly bool $ignoreCollidingDSN
3333
) {
3434
parent::__construct();
3535
}
@@ -45,12 +45,12 @@ protected function connectionOpened(Connection $connection): void
4545
$key = md5(
4646
json_encode(
4747
[
48-
'dsn' => $connection->dsn,
49-
'user' => $connection->username,
50-
'pass' => $connection->password,
51-
'attributes' => $connection->attributes,
52-
'emulatePrepare' => $connection->emulatePrepare,
53-
'charset' => $connection->charset,
48+
'dsn' => $connection->dsn,
49+
'user' => $connection->username,
50+
'pass' => $connection->password,
51+
'attributes' => $connection->attributes,
52+
'emulatePrepare' => $connection->emulatePrepare,
53+
'charset' => $connection->charset,
5454
],
5555
JSON_THROW_ON_ERROR
5656
)
@@ -87,9 +87,6 @@ protected function connectionOpened(Connection $connection): void
8787

8888
public function rollbackAll(): void
8989
{
90-
/**
91-
* @var Transaction $transaction
92-
*/
9390
foreach ($this->transactions as $transaction) {
9491
if ($transaction->db->isActive) {
9592
$transaction->rollBack();

src/Codeception/Module/Yii2.php

+21-28
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
use Codeception\Lib\Interfaces\ActiveRecord;
1616
use Codeception\Lib\Interfaces\PartedModule;
1717
use Codeception\TestInterface;
18+
use Exception;
1819
use PHPUnit\Framework\Assert;
1920
use ReflectionClass;
2021
use RuntimeException;
@@ -276,7 +277,9 @@ public function _initialize(): void
276277

277278
$this->defineConstants();
278279
$this->server = $_SERVER;
279-
$this->initServerGlobal();
280+
// Adds the required server params. Note this is done separately from the request cycle since someone might call
281+
// `Url::to` before doing a request, which would instantiate the request component with incorrect server params.
282+
$_SERVER = [...$_SERVER, $this->getServerParams()];
280283
}
281284

282285
/**
@@ -294,26 +297,27 @@ protected function onReconfigure(): void
294297
}
295298

296299
/**
297-
* Adds the required server params.
298-
* Note this is done separately from the request cycle since someone might call
299-
* `Url::to` before doing a request, which would instantiate the request component with incorrect server params.
300+
* @return array{
301+
* SCRIPT_FILENAME: string,
302+
* SCRIPT_NAME: string,
303+
* SERVER_NAME: string,
304+
* SERVER_PORT: string|int,
305+
* HTTPS: bool
306+
* }
300307
*/
301-
private function initServerGlobal(): void
308+
private function getServerParams(): array
302309
{
303310
$entryUrl = $this->config['entryUrl'];
304311
$parsedUrl = parse_url($entryUrl);
305312
$entryFile = $this->config['entryScript'] ?: basename($entryUrl);
306313
$entryScript = $this->config['entryScript'] ?: ($parsedUrl['path'] ?? '');
307-
$_SERVER = array_merge(
308-
$_SERVER,
309-
[
314+
return [
310315
'SCRIPT_FILENAME' => $entryFile,
311316
'SCRIPT_NAME' => $entryScript,
312317
'SERVER_NAME' => $parsedUrl['host'] ?? '',
313318
'SERVER_PORT' => $parsedUrl['port'] ?? '80',
314319
'HTTPS' => isset($parsedUrl['scheme']) && $parsedUrl['scheme'] === 'https',
315-
]
316-
);
320+
];
317321
}
318322

319323
/**
@@ -335,23 +339,24 @@ protected function validateConfig(): void
335339
"The application config file does not exist: " . $pathToConfig,
336340
);
337341
}
338-
$validMethods = implode(", ", Yii2Connector::CLEAN_METHODS);
342+
$validCleanMethods = implode(", ", Yii2Connector::CLEAN_METHODS);
339343
if (! in_array($this->config['responseCleanMethod'], Yii2Connector::CLEAN_METHODS, true)) {
340344
throw new ModuleConfigException(
341345
self::class,
342-
"The response clean method must be one of: " . $validMethods,
346+
"The response clean method must be one of: " . $validCleanMethods,
343347
);
344348
}
349+
$validMailMethods = implode(", ", Yii2Connector::MAIL_METHODS);
345350
if (! in_array($this->config['mailMethod'], Yii2Connector::MAIL_METHODS, true)) {
346351
throw new ModuleConfigException(
347352
self::class,
348-
"The mail method must be one of: " . $validMethods
353+
"The mail method must be one of: " . $validMailMethods
349354
);
350355
}
351356
if (! in_array($this->config['requestCleanMethod'], Yii2Connector::CLEAN_METHODS, true)) {
352357
throw new ModuleConfigException(
353358
self::class,
354-
"The request clean method must be one of: " . $validMethods,
359+
"The request clean method must be one of: " . $validCleanMethods,
355360
);
356361
}
357362
}
@@ -377,19 +382,7 @@ private function configureClient(array $settings): void
377382
*/
378383
protected function recreateClient(): void
379384
{
380-
$entryUrl = $this->config['entryUrl'];
381-
$parsedUrl = parse_url($entryUrl);
382-
$entryFile = $this->config['entryScript'] ?: basename($entryUrl);
383-
$entryScript = $this->config['entryScript'] ?: ($parsedUrl['path'] ?? '');
384-
$this->client = new Yii2Connector(
385-
[
386-
'SCRIPT_FILENAME' => $entryFile,
387-
'SCRIPT_NAME' => $entryScript,
388-
'SERVER_NAME' => $parsedUrl['host'] ?? '',
389-
'SERVER_PORT' => $parsedUrl['port'] ?? '80',
390-
'HTTPS' => isset($parsedUrl['scheme']) && $parsedUrl['scheme'] === 'https',
391-
]
392-
);
385+
$this->client = new Yii2Connector($this->getServerParams());
393386
$this->validateConfig();
394387
$this->configureClient($this->config);
395388
}
@@ -463,7 +456,7 @@ public function _after(TestInterface $test): void
463456
}
464457

465458
/**
466-
* @param \Exception $fail
459+
* @param Exception $fail
467460
*/
468461
public function _failed(TestInterface $test, $fail): void
469462
{

0 commit comments

Comments
 (0)