Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: replace empty() by rector #1081

Merged
merged 4 commits into from
Apr 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 4 additions & 39 deletions phpstan-baseline.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 2,
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Actions/Email2FA.php',
];
$ignoreErrors[] = [
Expand Down Expand Up @@ -45,7 +45,7 @@
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 4,
'count' => 2,
'path' => __DIR__ . '/src/Authentication/Authenticators/AccessTokens.php',
];
$ignoreErrors[] = [
Expand Down Expand Up @@ -95,16 +95,6 @@
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 3,
'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php',
];
$ignoreErrors[] = [
'message' => '#^Only booleans are allowed in an elseif condition, string\\|null given\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php',
];
$ignoreErrors[] = [
'message' => '#^Only booleans are allowed in an if condition, CodeIgniter\\\\Shield\\\\Entities\\\\UserIdentity\\|null given\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Authenticators/Session.php',
];
Expand All @@ -130,29 +120,14 @@
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Passwords.php',
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Passwords/CompositionValidator.php',
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 5,
'count' => 4,
'path' => __DIR__ . '/src/Authentication/Passwords/NothingPersonalValidator.php',
];
$ignoreErrors[] = [
'message' => '#^Call to method CodeIgniter\\\\Shield\\\\Result\\:\\:isOK\\(\\) with incorrect case\\: isOk$#',
'count' => 2,
'path' => __DIR__ . '/src/Authentication/Passwords/ValidationRules.php',
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 1,
'path' => __DIR__ . '/src/Authentication/Passwords/ValidationRules.php',
];
$ignoreErrors[] = [
'message' => '#^Only booleans are allowed in &&, CodeIgniter\\\\Shield\\\\Entities\\\\User\\|null given on the right side\\.$#',
'count' => 1,
Expand Down Expand Up @@ -249,11 +224,6 @@
'count' => 1,
'path' => __DIR__ . '/src/Entities/Entity.php',
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 2,
'path' => __DIR__ . '/src/Entities/Group.php',
];
$ignoreErrors[] = [
'message' => '#^Call to function model with CodeIgniter\\\\Shield\\\\Models\\\\GroupModel\\:\\:class is discouraged\\.$#',
'count' => 2,
Expand All @@ -276,7 +246,7 @@
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 8,
'count' => 7,
'path' => __DIR__ . '/src/Entities/User.php',
];
$ignoreErrors[] = [
Expand Down Expand Up @@ -366,11 +336,6 @@
'count' => 8,
'path' => __DIR__ . '/tests/Authentication/Authenticators/SessionAuthenticatorTest.php',
];
$ignoreErrors[] = [
'message' => '#^Construct empty\\(\\) is not allowed\\. Use more strict comparison\\.$#',
'count' => 1,
'path' => __DIR__ . '/tests/Authentication/Filters/AbstractFilterTestCase.php',
];
$ignoreErrors[] = [
'message' => '#^Implicit array creation is not allowed \\- variable \\$users might not exist\\.$#',
'count' => 1,
Expand Down
25 changes: 25 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,22 +11,28 @@
* the LICENSE file that was distributed with this source code.
*/

use Rector\Caching\ValueObject\Storage\FileCacheStorage;
use Rector\CodeQuality\Rector\BooleanAnd\SimplifyEmptyArrayCheckRector;
use Rector\CodeQuality\Rector\Class_\CompleteDynamicPropertiesRector;
use Rector\CodeQuality\Rector\Empty_\SimplifyEmptyCheckOnEmptyArrayRector;
use Rector\CodeQuality\Rector\Expression\InlineIfToExplicitIfRector;
use Rector\CodeQuality\Rector\Foreach_\UnusedForeachValueToArrayKeysRector;
use Rector\CodeQuality\Rector\FuncCall\ChangeArrayPushToArrayAssignRector;
use Rector\CodeQuality\Rector\FuncCall\SimplifyRegexPatternRector;
use Rector\CodeQuality\Rector\FuncCall\SimplifyStrposLowerRector;
use Rector\CodeQuality\Rector\FuncCall\SingleInArrayToCompareRector;
use Rector\CodeQuality\Rector\FunctionLike\SimplifyUselessVariableRector;
use Rector\CodeQuality\Rector\If_\CombineIfRector;
use Rector\CodeQuality\Rector\If_\ExplicitBoolCompareRector;
use Rector\CodeQuality\Rector\If_\ShortenElseIfRector;
use Rector\CodeQuality\Rector\If_\SimplifyIfElseToTernaryRector;
use Rector\CodeQuality\Rector\If_\SimplifyIfReturnBoolRector;
use Rector\CodeQuality\Rector\Ternary\TernaryEmptyArrayArrayDimFetchToCoalesceRector;
use Rector\CodeQuality\Rector\Ternary\UnnecessaryTernaryExpressionRector;
use Rector\CodingStyle\Rector\ClassMethod\FuncGetArgsToVariadicParamRector;
use Rector\CodingStyle\Rector\ClassMethod\MakeInheritedMethodVisibilitySameAsParentRector;
use Rector\CodingStyle\Rector\FuncCall\CountArrayToEmptyArrayComparisonRector;
use Rector\CodingStyle\Rector\FuncCall\VersionCompareFuncCallToConstantRector;
use Rector\Config\RectorConfig;
use Rector\DeadCode\Rector\Cast\RecastingRemovalRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveUnusedPromotedPropertyRector;
Expand All @@ -38,12 +44,16 @@
use Rector\EarlyReturn\Rector\Return_\PreparedValueToEarlyReturnRector;
use Rector\Php55\Rector\String_\StringClassNameToClassConstantRector;
use Rector\Php73\Rector\FuncCall\JsonThrowOnErrorRector;
use Rector\Php73\Rector\FuncCall\StringifyStrNeedlesRector;
use Rector\PHPUnit\AnnotationsToAttributes\Rector\Class_\AnnotationWithValueToAttributeRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector;
use Rector\PHPUnit\Set\PHPUnitSetList;
use Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector;
use Rector\Set\ValueObject\LevelSetList;
use Rector\Set\ValueObject\SetList;
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
use Rector\Strict\Rector\If_\BooleanInIfConditionRuleFixerRector;
use Rector\TypeDeclaration\Rector\Empty_\EmptyOnNullableObjectToInstanceOfRector;
use Rector\ValueObject\PhpVersion;

return static function (RectorConfig $rectorConfig): void {
Expand All @@ -56,6 +66,12 @@

$rectorConfig->parallel();

// Github action cache
$rectorConfig->cacheClass(FileCacheStorage::class);
if (is_dir('/tmp')) {
$rectorConfig->cacheDirectory('/tmp/rector');
}

// The paths to refactor (can also be supplied with CLI arguments)
$rectorConfig->paths([
__DIR__ . '/src/',
Expand Down Expand Up @@ -89,6 +105,7 @@
__DIR__ . '/src/Views',

JsonThrowOnErrorRector::class,
StringifyStrNeedlesRector::class,
YieldDataProviderRector::class,

// Note: requires php 8
Expand Down Expand Up @@ -140,7 +157,15 @@
$rectorConfig->rule(FuncGetArgsToVariadicParamRector::class);
$rectorConfig->rule(MakeInheritedMethodVisibilitySameAsParentRector::class);
$rectorConfig->rule(SimplifyEmptyArrayCheckRector::class);
$rectorConfig->rule(SimplifyEmptyCheckOnEmptyArrayRector::class);
$rectorConfig->rule(TernaryEmptyArrayArrayDimFetchToCoalesceRector::class);
$rectorConfig->rule(EmptyOnNullableObjectToInstanceOfRector::class);
$rectorConfig->rule(DisallowedEmptyRuleFixerRector::class);
$rectorConfig->rule(StringClassNameToClassConstantRector::class);
$rectorConfig->rule(PrivatizeFinalClassPropertyRector::class);
$rectorConfig->rule(CompleteDynamicPropertiesRector::class);
$rectorConfig->rule(BooleanInIfConditionRuleFixerRector::class);
$rectorConfig->rule(SingleInArrayToCompareRector::class);
$rectorConfig->rule(VersionCompareFuncCallToConstantRector::class);
$rectorConfig->rule(ExplicitBoolCompareRector::class);
};
2 changes: 1 addition & 1 deletion src/Authentication/Actions/Email2FA.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public function handle(IncomingRequest $request)

$identity = $this->getIdentity($user);

if (empty($identity)) {
if (! $identity instanceof UserIdentity) {
return redirect()->route('auth-action-show')->with('error', lang('Auth.need2FA'));
}

Expand Down
4 changes: 2 additions & 2 deletions src/Authentication/Authenticators/AccessTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ public function check(array $credentials): Result
*/
public function loggedIn(): bool
{
if (! empty($this->user)) {
if ($this->user instanceof User) {
return true;
}

Expand Down Expand Up @@ -226,7 +226,7 @@ public function loginById($userId): void
{
$user = $this->provider->findById($userId);

if (empty($user)) {
if (! $user instanceof User) {
throw AuthenticationException::forInvalidUser();
}

Expand Down
11 changes: 7 additions & 4 deletions src/Authentication/Authenticators/Session.php
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,7 @@ public function checkAction(UserIdentity $identity, string $token): bool
throw new LogicException('Cannot get the User.');
}

if (empty($token) || $token !== $identity->secret) {
if ($token === '' || $token !== $identity->secret) {
return false;
}

Expand Down Expand Up @@ -485,7 +485,7 @@ private function setAuthAction(): bool

$identity = $this->userIdentityModel->getIdentityByType($this->user, $action->getType());

if ($identity) {
if ($identity instanceof UserIdentity) {
$this->userState = self::STATE_PENDING;

$this->setSessionKey('auth_action', $actionClass);
Expand Down Expand Up @@ -767,7 +767,7 @@ private function issueRememberMeToken(): void

// Reset so it doesn't mess up future calls.
$this->shouldRemember = false;
} elseif ($this->getRememberMeToken()) {
} elseif ($this->getRememberMeToken() !== null) {
$this->removeRememberCookie();

// @TODO delete the token record.
Expand Down Expand Up @@ -804,7 +804,7 @@ public function loginById($userId): void
{
$user = $this->provider->findById($userId);

if (empty($user)) {
if (! $user instanceof User) {
throw AuthenticationException::forInvalidUser();
}

Expand Down Expand Up @@ -935,6 +935,9 @@ private function calcExpires(): Time
return Time::createFromTimestamp($timestamp);
}

/**
* @param non-empty-string $rawToken
*/
private function setRememberMeCookie(string $rawToken): void
{
/** @var Response $response */
Expand Down
2 changes: 1 addition & 1 deletion src/Authentication/Passwords.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ public function check(string $password, ?User $user = null): Result

$password = trim($password);

if (empty($password)) {
if ($password === '') {
return new Result([
'success' => false,
'reason' => lang('Auth.errorPasswordEmpty'),
Expand Down
2 changes: 1 addition & 1 deletion src/Authentication/Passwords/CompositionValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ class CompositionValidator extends BaseValidator implements ValidatorInterface
*/
public function check(string $password, ?User $user = null): Result
{
if (empty($this->config->minimumPasswordLength)) {
if ($this->config->minimumPasswordLength === 0) {
throw AuthenticationException::forUnsetPasswordLength();
}

Expand Down
2 changes: 1 addition & 1 deletion src/Authentication/Passwords/NothingPersonalValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ protected function isNotPersonal(string $password, ?User $user): bool

// might be [email protected] and we want all the needles we can get
$emailParts = $this->strip_explode($localPart);
if (! empty($domain)) {
if ($domain !== null && $domain !== '') {
$emailParts[] = $domain;
}
$needles = [...$needles, ...$emailParts];
Expand Down
4 changes: 2 additions & 2 deletions src/Authentication/Passwords/ValidationRules.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,13 @@ public function strong_password(string $value, ?string &$error1 = null, array $d
$user = auth()->user();
} else {
/** @phpstan-ignore-next-line */
$user = empty($data) ? $this->buildUserFromRequest() : $this->buildUserFromData($data);
$user = $data === [] ? $this->buildUserFromRequest() : $this->buildUserFromData($data);
}

$result = $checker->check($value, $user);

if (! $result->isOk()) {
if (empty($data)) {
if ($data === []) {
$error1 = $result->reason();
} else {
$error2 = $result->reason();
Expand Down
2 changes: 1 addition & 1 deletion src/Authentication/Traits/HasAccessTokens.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public function accessTokens(): array
*/
public function getAccessToken(?string $rawToken): ?AccessToken
{
if (empty($rawToken)) {
if ($rawToken === null || $rawToken === '') {
return null;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Authorization/Traits/Authorizable.php
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ public function can(string ...$permissions): bool
return true;
}

if (! count($this->groupCache)) {
if (count($this->groupCache) === 0) {
return false;
}

Expand Down
4 changes: 2 additions & 2 deletions src/Entities/Group.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,14 +80,14 @@ public function can(string $permission): bool
$this->populatePermissions();

// Check exact match
if (! empty($this->permissions) && in_array($permission, $this->permissions, true)) {
if ($this->permissions !== null && $this->permissions !== [] && in_array($permission, $this->permissions, true)) {
return true;
}

// Check wildcard match
$check = substr($permission, 0, strpos($permission, '.')) . '.*';

return ! empty($this->permissions) && in_array($check, $this->permissions, true);
return $this->permissions !== null && $this->permissions !== [] && in_array($check, $this->permissions, true);
}

/**
Expand Down
2 changes: 1 addition & 1 deletion tests/Authentication/Filters/AbstractFilterTestCase.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ private function addRoutes(): void
{
$routes = service('routes');

$filterString = ! empty($this->routeFilter)
$filterString = isset($this->routeFilter) && ($this->routeFilter !== '')
? $this->routeFilter
: $this->alias;

Expand Down
Loading