Skip to content

Commit

Permalink
refactor: enable instanceof and strictBooleans rector set
Browse files Browse the repository at this point in the history
  • Loading branch information
samsonasik committed Dec 27, 2024
1 parent cc1b8f2 commit d842179
Show file tree
Hide file tree
Showing 43 changed files with 102 additions and 138 deletions.
2 changes: 1 addition & 1 deletion app/Views/errors/cli/error_exception.php
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@

$args = implode(', ', array_map(static fn ($value) => match (true) {
is_object($value) => 'Object(' . $value::class . ')',
is_array($value) => count($value) ? '[...]' : '[]',
is_array($value) => $value !== [] ? '[...]' : '[]',
$value === null => 'null', // return the lowercased version
default => var_export($value, true),
}, array_values($error['args'] ?? [])));
Expand Down
8 changes: 2 additions & 6 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector;
use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector;
use Rector\PHPUnit\Set\PHPUnitSetList;
use Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector;
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
use Rector\Strict\Rector\If_\BooleanInIfConditionRuleFixerRector;
Expand All @@ -56,11 +55,8 @@

return RectorConfig::configure()
->withPhpSets(php81: true)
->withPreparedSets(deadCode: true)
->withSets([
PHPUnitSetList::PHPUNIT_CODE_QUALITY,
PHPUnitSetList::PHPUNIT_100,
])
->withPreparedSets(deadCode: true, instanceOf: true, strictBooleans: true, phpunitCodeQuality: true)
->withComposerBased(phpunit: true)
->withParallel(120, 8, 10)
->withCache(
// Github action cache or local
Expand Down
4 changes: 2 additions & 2 deletions system/CLI/CLI.php
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ public static function prompt(string $field, $options = null, $validation = null
}

if (! is_array($validation)) {
$validation = $validation ? explode('|', $validation) : [];
$validation = $validation !== null && $validation !== '' && $validation !== '0' ? explode('|', $validation) : [];
}

if (is_string($options)) {
Expand Down Expand Up @@ -348,7 +348,7 @@ public static function promptByMultipleKeys(string $text, array $options): array
// return the prompt again if $input contain(s) non-numeric character, except a comma.
// And if max from $options less than max from input,
// it means user tried to access null value in $options
if (! $pattern || $maxOptions < $maxInput) {
if ($pattern === 0 || $pattern === false || $maxOptions < $maxInput) {
static::error('Please select correctly.');
CLI::newLine();

Expand Down
2 changes: 1 addition & 1 deletion system/Cache/Handlers/FileHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,7 +308,7 @@ protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs
if ($filename !== '.' && $filename !== '..') {
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
} elseif (! $htdocs || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
} elseif (! $htdocs || in_array(preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename), [0, false], true)) {
@unlink($path . DIRECTORY_SEPARATOR . $filename);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ private function getRouteForDefaultController(
if ($classShortname === $defaultController) {
$pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#';
$routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/');
$routeWithoutController = $routeWithoutController ?: '/';
$routeWithoutController = $routeWithoutController !== '' && $routeWithoutController !== '0' ? $routeWithoutController : '/';

[$params, $routeParams] = $this->getParameters($method);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ private function getRouteWithoutController(

$pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#';
$routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/');
$routeWithoutController = $routeWithoutController ?: '/';
$routeWithoutController = $routeWithoutController !== '' && $routeWithoutController !== '0' ? $routeWithoutController : '/';

return [[
'route' => $routeWithoutController,
Expand Down
2 changes: 1 addition & 1 deletion system/Config/DotEnv.php
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ public function parse(): ?array
*/
protected function setVariable(string $name, string $value = '')
{
if (! getenv($name, true)) {
if (in_array(getenv($name, true), ['', '0'], true) || getenv($name, true) === [] || getenv($name, true) === false) {
putenv("{$name}={$value}");
}

Expand Down
8 changes: 4 additions & 4 deletions system/Config/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ public static function image(?string $handler = null, ?Images $config = null, bo
$config ??= config(Images::class);
assert($config instanceof Images);

$handler = $handler ?: $config->defaultHandler;
$handler = $handler !== null && $handler !== '' && $handler !== '0' ? $handler : $config->defaultHandler;
$class = $config->handlers[$handler];

return new $class($config);
Expand Down Expand Up @@ -385,7 +385,7 @@ public static function language(?string $locale = null, bool $getShared = true)
}

// Use '?:' for empty string check
$locale = $locale ?: $requestLocale;
$locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : $requestLocale;

return new Language($locale);
}
Expand Down Expand Up @@ -484,7 +484,7 @@ public static function parser(?string $viewPath = null, ?ViewConfig $config = nu
return static::getSharedInstance('parser', $viewPath, $config);
}

$viewPath = $viewPath ?: (new Paths())->viewDirectory;
$viewPath = $viewPath !== null && $viewPath !== '' && $viewPath !== '0' ? $viewPath : (new Paths())->viewDirectory;
$config ??= config(ViewConfig::class);

return new Parser($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger'));
Expand All @@ -503,7 +503,7 @@ public static function renderer(?string $viewPath = null, ?ViewConfig $config =
return static::getSharedInstance('renderer', $viewPath, $config);
}

$viewPath = $viewPath ?: (new Paths())->viewDirectory;
$viewPath = $viewPath !== null && $viewPath !== '' && $viewPath !== '0' ? $viewPath : (new Paths())->viewDirectory;
$config ??= config(ViewConfig::class);

return new View($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger'));
Expand Down
2 changes: 1 addition & 1 deletion system/Cookie/Cookie.php
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,7 @@ public function withNeverExpiring()
*/
public function withPath(?string $path)
{
$path = $path ?: self::$defaults['path'];
$path = $path !== null && $path !== '' && $path !== '0' ? $path : self::$defaults['path'];
$this->validatePrefix($this->prefix, $this->secure, $path, $this->domain);

$cookie = clone $this;
Expand Down
6 changes: 3 additions & 3 deletions system/Database/BaseBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1736,7 +1736,7 @@ public function countAllResults(bool $reset = true)
// Restore the LIMIT setting
$this->QBLimit = $limit;

$row = ! $result instanceof ResultInterface ? null : $result->getRow();
$row = $result instanceof ResultInterface ? $result->getRow() : null;

if (empty($row)) {
return 0;
Expand Down Expand Up @@ -3167,11 +3167,11 @@ protected function compileWhereHaving(string $qbKey): string
$op = $this->getOperator($condition);
if (
$op === false
|| ! preg_match(
|| in_array(preg_match(
'/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(?<!\)))?(\)?)$/i',
$condition,
$matches
)
), [0, false], true)
) {
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion system/Database/BaseConnection.php
Original file line number Diff line number Diff line change
Expand Up @@ -610,7 +610,7 @@ abstract protected function execute(string $sql);
*/
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = '')
{
$queryClass = $queryClass ?: $this->queryClass;
$queryClass = $queryClass !== '' && $queryClass !== '0' ? $queryClass : $this->queryClass;

if (empty($this->connID)) {
$this->initialize();
Expand Down
2 changes: 1 addition & 1 deletion system/Database/Database.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ protected function parseDSN(array $params): array
{
$dsn = parse_url($params['DSN']);

if (! $dsn) {
if ($dsn === 0 || ($dsn === '' || $dsn === '0') || $dsn === [] || $dsn === false || $dsn === null) {
throw new InvalidArgumentException('Your DSN connection string is invalid.');
}

Expand Down
8 changes: 4 additions & 4 deletions system/Database/MigrationRunner.php
Original file line number Diff line number Diff line change
Expand Up @@ -450,7 +450,7 @@ protected function migrationFromFile(string $path, string $namespace)

$filename = basename($path, '.php');

if (! preg_match($this->regex, $filename)) {
if (in_array(preg_match($this->regex, $filename), [0, false], true)) {
return false;
}

Expand Down Expand Up @@ -524,7 +524,7 @@ protected function getMigrationNumber(string $migration): string
{
preg_match($this->regex, $migration, $matches);

return count($matches) ? $matches[1] : '0';
return $matches !== [] ? $matches[1] : '0';
}

/**
Expand All @@ -539,7 +539,7 @@ protected function getMigrationName(string $migration): string
{
preg_match($this->regex, $migration, $matches);

return count($matches) ? $matches[2] : '';
return $matches !== [] ? $matches[2] : '';
}

/**
Expand Down Expand Up @@ -725,7 +725,7 @@ public function getBatchStart(int $batch): string
->get()
->getResultObject();

return count($migration) ? $migration[0]->version : '0';
return count($migration) !== 0 ? $migration[0]->version : '0';
}

/**
Expand Down
4 changes: 2 additions & 2 deletions system/Database/MySQLi/Forge.php
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,11 @@ protected function _createTableAttributes(array $attributes): string
}
}

if ($this->db->charset !== '' && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) {
if ($this->db->charset !== '' && in_array(strpos($sql, 'CHARACTER SET'), [0, false], true) && in_array(strpos($sql, 'CHARSET'), [0, false], true)) {
$sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset);
}

if ($this->db->DBCollat !== '' && ! strpos($sql, 'COLLATE')) {
if ($this->db->DBCollat !== '' && in_array(strpos($sql, 'COLLATE'), [0, false], true)) {
$sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat);
}

Expand Down
2 changes: 1 addition & 1 deletion system/Database/Postgre/Connection.php
Original file line number Diff line number Diff line change
Expand Up @@ -463,7 +463,7 @@ public function error(): array
{
return [
'code' => '',
'message' => pg_last_error($this->connID) ?: '',
'message' => ! in_array(pg_last_error($this->connID), ['', '0'], true) ? pg_last_error($this->connID) : '',
];
}

Expand Down
4 changes: 2 additions & 2 deletions system/Email/Email.php
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ public function setFrom($from, $name = '', $returnPath = null)

if ($name !== '') {
// only use Q encoding if there are characters that would require it
if (! preg_match('/[\200-\377]/', $name)) {
if (in_array(preg_match('/[\200-\377]/', $name), [0, false], true)) {
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
} else {
$name = $this->prepQEncoding($name);
Expand Down Expand Up @@ -532,7 +532,7 @@ public function setReplyTo($replyto, $name = '')
$this->tmpArchive['replyName'] = $name;

// only use Q encoding if there are characters that would require it
if (! preg_match('/[\200-\377]/', $name)) {
if (in_array(preg_match('/[\200-\377]/', $name), [0, false], true)) {
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
} else {
$name = $this->prepQEncoding($name);
Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/Files/UploadedFile.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ public function getTempName(): string
*/
public function getExtension(): string
{
return $this->guessExtension() ?: $this->getClientExtension();
return ! in_array($this->guessExtension(), ['', '0'], true) ? $this->guessExtension() : $this->getClientExtension();
}

/**
Expand Down
6 changes: 3 additions & 3 deletions system/HTTP/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -566,7 +566,7 @@ public function getCookieStore()
*/
public function hasCookie(string $name, ?string $value = null, string $prefix = ''): bool
{
$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
$prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC

return $this->cookieStore->has($name, $prefix, $value);
}
Expand All @@ -586,7 +586,7 @@ public function getCookie(?string $name = null, string $prefix = '')
}

try {
$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
$prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC

return $this->cookieStore->get($name, $prefix);
} catch (CookieException $e) {
Expand All @@ -607,7 +607,7 @@ public function deleteCookie(string $name = '', string $domain = '', string $pat
return $this;
}

$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
$prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC

$prefixed = $prefix . $name;
$store = $this->cookieStore;
Expand Down
2 changes: 1 addition & 1 deletion system/HTTP/SiteURI.php
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,7 @@ public function siteUrl($relativePath = '', ?string $scheme = null, ?App $config
$relativePath = $this->stringifyRelativePath($relativePath);

// Check current host.
$host = ! $config instanceof App ? $this->getHost() : null;
$host = $config instanceof App ? null : $this->getHost();

$config ??= config(App::class);

Expand Down
2 changes: 1 addition & 1 deletion system/Helpers/filesystem_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ function delete_files(string $path, bool $delDir = false, bool $htdocs = false,
continue;
}

if (! $htdocs || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
if (! $htdocs || in_array(preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename), [0, false], true)) {
$isDir = $object->isDir();
if ($isDir && $delDir) {
rmdir($object->getPathname());
Expand Down
4 changes: 2 additions & 2 deletions system/Helpers/form_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s
// Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
$before = service('filters')->getFilters()['before'];

if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && ! stripos($form, 'method="get"')) {
if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && in_array(stripos($form, 'method="get"'), [0, false], true)) {
$form .= csrf_field($csrfId ?? null);
}

Expand Down Expand Up @@ -788,7 +788,7 @@ function parse_form_attributes($attributes, array $default): string
if (! is_bool($val)) {
if ($key === 'value') {
$val = esc($val);
} elseif ($key === 'name' && ! strlen($default['name'])) {
} elseif ($key === 'name' && (string) $default['name'] === '') {
continue;
}
$att .= $key . '="' . $val . '"' . ($key === array_key_last($default) ? '' : ' ');
Expand Down
6 changes: 3 additions & 3 deletions system/Helpers/html_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ function img($src = '', bool $indexPage = false, $attributes = ''): string
$img = '<img';

// Check for a relative URI
if (! preg_match('#^([a-z]+:)?//#i', $src['src']) && ! str_starts_with($src['src'], 'data:')) {
if (in_array(preg_match('#^([a-z]+:)?//#i', $src['src']), [0, false], true) && ! str_starts_with($src['src'], 'data:')) {
if ($indexPage) {
$img .= ' src="' . site_url($src['src']) . '"';
} else {
Expand Down Expand Up @@ -206,7 +206,7 @@ function script_tag($src = '', bool $indexPage = false): string
}

foreach ($src as $k => $v) {
if ($k === 'src' && ! preg_match('#^([a-z]+:)?//#i', $v)) {
if ($k === 'src' && in_array(preg_match('#^([a-z]+:)?//#i', $v), [0, false], true)) {
if ($indexPage) {
$script .= 'src="' . site_url($v) . '" ';
} else {
Expand Down Expand Up @@ -252,7 +252,7 @@ function link_tag(
$href = $href['href'] ?? '';
}

if (! preg_match('#^([a-z]+:)?//#i', $href)) {
if (in_array(preg_match('#^([a-z]+:)?//#i', $href), [0, false], true)) {
$attributes['href'] = $indexPage ? site_url($href) : slash_item('baseURL') . $href;
} else {
$attributes['href'] = $href;
Expand Down
2 changes: 1 addition & 1 deletion system/Helpers/text_helper.php
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ function excerpt(string $text, ?string $phrase = null, int $radius = 100, string
$count = ++$count + strlen($s);
}

$ellPre = $phrase ? $ellipsis : '';
$ellPre = $phrase !== null && $phrase !== '' && $phrase !== '0' ? $ellipsis : '';

return str_replace(' ', ' ', $ellPre . $prev . $phrase . $post . $ellipsis);
}
Expand Down
6 changes: 3 additions & 3 deletions system/I18n/TimeTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ trait TimeTrait
*/
public function __construct(?string $time = null, $timezone = null, ?string $locale = null)
{
$this->locale = $locale ?: Locale::getDefault();
$this->locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : Locale::getDefault();

$time ??= '';

Expand Down Expand Up @@ -958,7 +958,7 @@ public function sameAs($testTime, ?string $timezone = null): bool
if ($testTime instanceof DateTimeInterface) {
$testTime = $testTime->format('Y-m-d H:i:s');
} elseif (is_string($testTime)) {
$timezone = $timezone ?: $this->timezone;
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
$testTime = new DateTime($testTime, $timezone);
$testTime = $testTime->format('Y-m-d H:i:s');
Expand Down Expand Up @@ -1108,7 +1108,7 @@ public function getUTCObject($time, ?string $timezone = null)
if ($time instanceof self) {
$time = $time->toDateTime();
} elseif (is_string($time)) {
$timezone = $timezone ?: $this->timezone;
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
$time = new DateTime($time, $timezone);
}
Expand Down
2 changes: 1 addition & 1 deletion system/Images/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public function getProperties(bool $return = false)
{
$path = $this->getPathname();

if (! $vals = getimagesize($path)) {
if ($vals = getimagesize($path) === [] || $vals = getimagesize($path) === false) {
throw ImageException::forFileNotSupported();
}

Expand Down
Loading

0 comments on commit d842179

Please sign in to comment.