Skip to content

Commit

Permalink
chore: use easy-coding-standard
Browse files Browse the repository at this point in the history
  • Loading branch information
SamMousa committed Feb 25, 2025
1 parent ceb78d2 commit ac7d74a
Show file tree
Hide file tree
Showing 40 changed files with 222 additions and 158 deletions.
3 changes: 1 addition & 2 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,11 @@
"yiisoft/yii2": "dev-master",
"yiisoft/yii2-app-advanced": "dev-master",
"codeception/verify": "^3.0",
"codemix/yii2-localeurls": "^1.7",
"codeception/module-asserts": ">= 3.0",
"codeception/module-filesystem": "> 3.0",
"phpstan/phpstan": "^2",
"rector/rector": "^2",
"friendsofphp/php-cs-fixer": "^3.70"
"symplify/easy-coding-standard": "^12.5"
},
"autoload":{
"classmap": ["src/"]
Expand Down
10 changes: 8 additions & 2 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
#includes:
# - phpstan-baseline.neon
parameters:
exceptions:
check:
missingCheckedExceptionInThrows: false
reportUncheckedExceptionDeadCatch: false
reportUnmatchedIgnoredErrors: true
editorUrl: "phpstorm://open?file=%%file%%&line=%%line%%"
dynamicConstantNames:
- CONSOLE
- YII_DEBUG
level: 9
paths:
- src
checkMaybeUndefinedVariables: true
treatPhpDocTypesAsCertain: false
ignoreErrors:
# All Yii setters accept `null` but their phpdoc is incorrect.
- message: '~^Parameter #1 \$(.+) of method yii\\web\\Request::set(.+)\(\) expects (.+), null given.$~'
path: 'src/'
# - message: '~^Parameter #1 \$(.+) of method yii\\web\\Request::set(.+)\(\) expects (.+), null given.$~'
# path: 'src/'
# If you want to ignore missing generics errors in the future, you can add:
# - identifier: missingType.generics
stubFiles:
Expand Down
82 changes: 46 additions & 36 deletions src/Codeception/Lib/Connector/Yii2.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\History;
use Symfony\Component\BrowserKit\Request as BrowserkitRequest;
use yii\web\Request as YiiRequest;
use Symfony\Component\BrowserKit\Response;
use Yii;
use yii\base\Component;
Expand All @@ -24,18 +23,17 @@
use yii\base\Security;
use yii\base\UserException;
use yii\mail\BaseMessage;
use yii\mail\MessageInterface;
use yii\web\Application;
use yii\web\ErrorHandler;
use yii\web\IdentityInterface;
use yii\web\Request;
use yii\web\Request as YiiRequest;
use yii\web\Response as YiiResponse;
use yii\web\User;

/**
* @extends Client<BrowserkitRequest, Response>
*/
class Yii2 extends Client
final class Yii2 extends Client
{
use Shared\PhpSuperGlobalsConverter;

Expand All @@ -45,18 +43,22 @@ class Yii2 extends Client
self::CLEAN_FORCE_RECREATE,
self::CLEAN_MANUAL,
];

/**
* Clean the response object by recreating it.
* This might lose behaviors / event handlers / other changes that are done in the application bootstrap phase.
*/
public const CLEAN_RECREATE = 'recreate';

/**
* Same as recreate but will not warn when behaviors / event handlers are lost.
*/
public const CLEAN_FORCE_RECREATE = 'force_recreate';

/**
* Clean the response object by resetting specific properties via its' `clear()` method.
* This will keep behaviors / event handlers, but could inadvertently leave some changes intact.
*
* @see \yii\web\Response::clear()
*/
public const CLEAN_CLEAR = 'clear';
Expand All @@ -67,7 +69,6 @@ class Yii2 extends Client
*/
public const CLEAN_MANUAL = 'manual';


/**
* @var string application config file
*/
Expand All @@ -91,6 +92,7 @@ class Yii2 extends Client
/**
* This option is there primarily for backwards compatibility.
* It means you cannot make any modification to application state inside your app, since they will get discarded.
*
* @var bool whether to recreate the whole application before each request
*/
public $recreateApplication = false;
Expand All @@ -106,7 +108,6 @@ class Yii2 extends Client
*/
public string|null $applicationClass = null;


/**
* @var list<BaseMessage>
*/
Expand All @@ -117,7 +118,7 @@ class Yii2 extends Client
*/
protected function getApplication(): \yii\base\Application
{
if (!isset(Yii::$app)) {
if (! isset(Yii::$app)) {
$this->startApp();
}
return Yii::$app ?? throw new \RuntimeException('Failed to create Yii2 application');
Expand All @@ -126,7 +127,7 @@ protected function getApplication(): \yii\base\Application
private function getWebRequest(): YiiRequest
{
$request = $this->getApplication()->request;
if (!$request instanceof YiiRequest) {
if (! $request instanceof YiiRequest) {
throw new \RuntimeException('Request component is not of type ' . YiiRequest::class);
}
return $request;
Expand All @@ -148,15 +149,16 @@ public function resetApplication(bool $closeSession = true): void

/**
* Finds and logs in a user
*
* @internal
* @throws ConfigurationException
* @throws \RuntimeException
* @throws ConfigurationException
* @throws \RuntimeException
*/
public function findAndLoginUser(int|string|IdentityInterface $user): void
{
$app = $this->getApplication();
$userComponent = $app->get('user');
if (!$userComponent instanceof User) {
if (! $userComponent instanceof User) {
throw new ConfigurationException('The user component is not configured');
}

Expand All @@ -175,22 +177,22 @@ public function findAndLoginUser(int|string|IdentityInterface $user): void

/**
* @internal
* @param string $name The name of the cookie
* @param string $value The value of the cookie
* @return string The value to send to the browser
* @param string $name The name of the cookie
* @param string $value The value of the cookie
* @return string The value to send to the browser
*/
public function hashCookieData(string $name, string $value): string
{
$request = $this->getWebRequest();
if (!$request->enableCookieValidation) {
if (! $request->enableCookieValidation) {
return $value;
}
return $this->getApplication()->security->hashData(serialize([$name, $value]), $request->cookieValidationKey);
}

/**
* @internal
* @return non-empty-list<string> List of regex patterns for recognized domain names
* @return non-empty-list<string> List of regex patterns for recognized domain names
*/
public function getInternalDomains(): array
{
Expand All @@ -199,7 +201,9 @@ public function getInternalDomains(): array
$domains = [$this->getDomainRegex($urlManager->hostInfo)];
if ($urlManager->enablePrettyUrl) {
foreach ($urlManager->rules as $rule) {
/** @var \yii\web\UrlRule $rule */
/**
* @var \yii\web\UrlRule $rule
*/
if ($rule->host !== null) {
$domains[] = $this->getDomainRegex($rule->host);
}
Expand All @@ -210,7 +214,7 @@ public function getInternalDomains(): array

/**
* @internal
* @return list<BaseMessage> List of sent emails
* @return list<BaseMessage> List of sent emails
*/
public function getEmails(): array
{
Expand All @@ -219,6 +223,7 @@ public function getEmails(): array

/**
* Deletes all stored emails.
*
* @internal
*/
public function clearEmails(): void
Expand All @@ -233,7 +238,7 @@ public function getComponent(string $name): object|null
{
$app = $this->getApplication();
$result = $app->get($name, false);
if (!isset($result)) {
if (! isset($result)) {
throw new ConfigurationException("Component $name is not available in current application");
}
return $result;
Expand Down Expand Up @@ -269,6 +274,7 @@ function ($matches) use (&$parameters): string {

/**
* Gets the name of the CSRF param.
*
* @internal
*/
public function getCsrfParamName(): string
Expand All @@ -279,8 +285,8 @@ public function getCsrfParamName(): string
public function startApp(?\yii\log\Logger $logger = null): void
{
codecept_debug('Starting application');
$config = require($this->configFile);
if (!isset($config['class'])) {
$config = include $this->configFile;
if (! isset($config['class'])) {
$config['class'] = $this->applicationClass ?? \yii\web\Application::class;
}

Expand All @@ -291,7 +297,7 @@ public function startApp(?\yii\log\Logger $logger = null): void

$config = $this->mockMailer($config);
$app = Yii::createObject($config);
if (!$app instanceof \yii\base\Application) {
if (! $app instanceof \yii\base\Application) {
throw new ModuleConfigException($this, "Failed to initialize Yii2 app");
}
\Yii::$app = $app;
Expand Down Expand Up @@ -338,7 +344,7 @@ public function doRequest(object $request): Response
$this->beforeRequest();

$app = $this->getApplication();
if (!$app instanceof Application) {
if (! $app instanceof Application) {
throw new ConfigurationException("Application is not a web application");
}

Expand Down Expand Up @@ -372,7 +378,7 @@ public function doRequest(object $request): Response
// to expect error response codes in tests.
$app->errorHandler->discardExistingOutput = false;
$app->errorHandler->handleException($e);
} elseif (!$e instanceof ExitException) {
} elseif (! $e instanceof ExitException) {
// for exceptions not related to Http, we pass them to Codeception
throw $e;
}
Expand All @@ -386,7 +392,7 @@ public function doRequest(object $request): Response
}

$content = ob_get_clean();
if (empty($content) && !empty($yiiResponse->content) && !isset($yiiResponse->stream)) {
if (empty($content) && ! empty($yiiResponse->content) && ! isset($yiiResponse->stream)) {
throw new \RuntimeException('No content was sent from Yii application');
} elseif ($content === false) {
throw new \RuntimeException('Failed to get output buffer');
Expand All @@ -397,6 +403,7 @@ public function doRequest(object $request): Response

/**
* Encodes the cookies and adds them to the headers.
*
* @throws \yii\base\InvalidConfigException
*/
protected function encodeCookies(
Expand All @@ -409,7 +416,9 @@ protected function encodeCookies(
}

foreach ($response->getCookies() as $cookie) {
/** @var \yii\web\Cookie $cookie */
/**
* @var \yii\web\Cookie $cookie
*/
$value = $cookie->value;
// Expire = 1 means we're removing the cookie
if ($cookie->expire !== 1 && isset($validationKey)) {
Expand All @@ -434,7 +443,8 @@ protected function encodeCookies(

/**
* Replace mailer with in memory mailer
* @param array<string, mixed> $config Original configuration
*
* @param array<string, mixed> $config Original configuration
* @return array<string, mixed> New configuration
*/
protected function mockMailer(array $config): array
Expand All @@ -460,7 +470,7 @@ protected function mockMailer(array $config): array
];

if (isset($config['components'])) {
if (!is_array($config['components'])) {
if (! is_array($config['components'])) {
throw new ModuleConfigException(
$this,
"Yii2 config does not contain components key is not of type array",
Expand Down Expand Up @@ -491,13 +501,13 @@ public function restart(): void
* Return an assoc array with the client context: cookieJar, history.
*
* @internal
* @return array{ cookieJar: CookieJar, history: History }
* @return array{ cookieJar: CookieJar, history: History }
*/
public function getContext(): array
{
return [
'cookieJar' => $this->cookieJar,
'history' => $this->history,
'history' => $this->history,
];
}

Expand All @@ -514,6 +524,7 @@ public function setContext(array $context): void

/**
* This functions closes the session of the application, if the application exists and has a session.
*
* @internal
*/
public function closeSession(): void
Expand All @@ -532,11 +543,10 @@ protected function resetResponse(Application $app): void
{
$method = $this->responseCleanMethod;
// First check the current response object.
if (
($app->response->hasEventHandlers(YiiResponse::EVENT_BEFORE_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_PREPARE)
|| count($app->response->getBehaviors()) > 0)
if (($app->response->hasEventHandlers(YiiResponse::EVENT_BEFORE_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_PREPARE)
|| count($app->response->getBehaviors()) > 0)
&& $method === self::CLEAN_RECREATE
) {
Debug::debug(
Expand Down Expand Up @@ -608,7 +618,7 @@ protected function beforeRequest(): void

$application = $this->getApplication();

if (!$application instanceof Application) {
if (! $application instanceof Application) {
throw new ConfigurationException('Application must be an instance of web application when doing requests');
}
$this->resetResponse($application);
Expand Down
10 changes: 6 additions & 4 deletions src/Codeception/Lib/Connector/Yii2/ConnectionWatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,16 @@
/**
* Class ConnectionWatcher
* This class will watch for new database connection and store a reference to the connection object.
*
* @package Codeception\Lib\Connector\Yii2
*/
class ConnectionWatcher
final class ConnectionWatcher
{
private Closure $handler;

/** @var Connection[] */
/**
* @var Connection[]
*/
private array $connections = [];

public function __construct()
Expand Down Expand Up @@ -59,8 +62,7 @@ public function closeAll(): void
}

/**
* @param string|array<mixed>|JsonSerializable $message
* @return void
* @param string|array<mixed>|JsonSerializable $message
*/
protected function debug(string|array|JsonSerializable $message): void
{
Expand Down
Loading

0 comments on commit ac7d74a

Please sign in to comment.