Skip to content

Commit ee4ee98

Browse files
authored
refactor: enable instanceof and strictBooleans rector set (#9339)
* refactor: enable instanceof and strictBooleans rector set * refactor: bump to rector 2.0.4 * refactor: clean condition check * refactor: revert ThirdParty change * refactor: re-run phpstan baseline * refactor: fix never empty array on Image * refactor: avoid repetitive call pg_last_error() * refactor: pg_last_error() always returns string * refactor: use return empty string on pg_last_error() got empty "0" * refactor: various compare !== 1 on preg_match() * refactor: use falsy check on getenv() * refactor: more !== 1 compare on preg_match() * refactor: use empty string check on guessExtension * refactor: run cs fix * refactor: more !== 1 compare on preg_match() * use direct result of pg_last_error() * refactor: use str_contains() over strpos on Forge * refactor: fix unused variable * refactor: check empty string on ResponseTrait * refactor: more preg_match() and empty string only check * refactor: compare to 0 on preg_match_all() * refactor: re-run rector * refactor: preg_match_all() likely less to return false
1 parent 8cff099 commit ee4ee98

37 files changed

+63
-99
lines changed

app/Views/errors/cli/error_exception.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252

5353
$args = implode(', ', array_map(static fn ($value) => match (true) {
5454
is_object($value) => 'Object(' . $value::class . ')',
55-
is_array($value) => count($value) ? '[...]' : '[]',
55+
is_array($value) => $value !== [] ? '[...]' : '[]',
5656
$value === null => 'null', // return the lowercased version
5757
default => var_export($value, true),
5858
}, array_values($error['args'] ?? [])));

composer.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@
2828
"phpunit/phpcov": "^9.0.2 || ^10.0",
2929
"phpunit/phpunit": "^10.5.16 || ^11.2",
3030
"predis/predis": "^1.1 || ^2.0",
31-
"rector/rector": "2.0.3",
31+
"rector/rector": "2.0.4",
3232
"shipmonk/phpstan-baseline-per-identifier": "^2.0"
3333
},
3434
"replace": {

rector.php

+2-6
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,6 @@
3838
use Rector\Php80\Rector\Class_\ClassPropertyAssignToConstructorPromotionRector;
3939
use Rector\Php81\Rector\FuncCall\NullToStrictStringFuncCallArgRector;
4040
use Rector\PHPUnit\CodeQuality\Rector\Class_\YieldDataProviderRector;
41-
use Rector\PHPUnit\Set\PHPUnitSetList;
4241
use Rector\Privatization\Rector\Property\PrivatizeFinalClassPropertyRector;
4342
use Rector\Strict\Rector\Empty_\DisallowedEmptyRuleFixerRector;
4443
use Rector\Strict\Rector\If_\BooleanInIfConditionRuleFixerRector;
@@ -56,11 +55,8 @@
5655

5756
return RectorConfig::configure()
5857
->withPhpSets(php81: true)
59-
->withPreparedSets(deadCode: true)
60-
->withSets([
61-
PHPUnitSetList::PHPUNIT_CODE_QUALITY,
62-
PHPUnitSetList::PHPUNIT_100,
63-
])
58+
->withPreparedSets(deadCode: true, instanceOf: true, strictBooleans: true, phpunitCodeQuality: true)
59+
->withComposerBased(phpunit: true)
6460
->withParallel(120, 8, 10)
6561
->withCache(
6662
// Github action cache or local

system/CLI/CLI.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -348,7 +348,7 @@ public static function promptByMultipleKeys(string $text, array $options): array
348348
// return the prompt again if $input contain(s) non-numeric character, except a comma.
349349
// And if max from $options less than max from input,
350350
// it means user tried to access null value in $options
351-
if (! $pattern || $maxOptions < $maxInput) {
351+
if ($pattern === 0 || $maxOptions < $maxInput) {
352352
static::error('Please select correctly.');
353353
CLI::newLine();
354354

system/Cache/Handlers/FileHandler.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ protected function deleteFiles(string $path, bool $delDir = false, bool $htdocs
308308
if ($filename !== '.' && $filename !== '..') {
309309
if (is_dir($path . DIRECTORY_SEPARATOR . $filename) && $filename[0] !== '.') {
310310
$this->deleteFiles($path . DIRECTORY_SEPARATOR . $filename, $delDir, $htdocs, $_level + 1);
311-
} elseif (! $htdocs || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
311+
} elseif (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) {
312312
@unlink($path . DIRECTORY_SEPARATOR . $filename);
313313
}
314314
}

system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -221,7 +221,7 @@ private function getRouteForDefaultController(
221221
if ($classShortname === $defaultController) {
222222
$pattern = '#' . preg_quote(lcfirst($defaultController), '#') . '\z#';
223223
$routeWithoutController = rtrim(preg_replace($pattern, '', $uriByClass), '/');
224-
$routeWithoutController = $routeWithoutController ?: '/';
224+
$routeWithoutController = $routeWithoutController !== '' && $routeWithoutController !== '0' ? $routeWithoutController : '/';
225225

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

system/Commands/Utilities/Routes/ControllerMethodReader.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ private function getRouteWithoutController(
161161

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

166166
return [[
167167
'route' => $routeWithoutController,

system/Config/DotEnv.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ public function parse(): ?array
9494
*/
9595
protected function setVariable(string $name, string $value = '')
9696
{
97-
if (! getenv($name, true)) {
97+
if (getenv($name, true) === false) {
9898
putenv("{$name}={$value}");
9999
}
100100

system/Config/Services.php

+4-4
Original file line numberDiff line numberDiff line change
@@ -345,7 +345,7 @@ public static function image(?string $handler = null, ?Images $config = null, bo
345345
$config ??= config(Images::class);
346346
assert($config instanceof Images);
347347

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

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

387387
// Use '?:' for empty string check
388-
$locale = $locale ?: $requestLocale;
388+
$locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : $requestLocale;
389389

390390
return new Language($locale);
391391
}
@@ -484,7 +484,7 @@ public static function parser(?string $viewPath = null, ?ViewConfig $config = nu
484484
return static::getSharedInstance('parser', $viewPath, $config);
485485
}
486486

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

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

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

509509
return new View($config, $viewPath, AppServices::get('locator'), CI_DEBUG, AppServices::get('logger'));

system/Cookie/Cookie.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -482,7 +482,7 @@ public function withNeverExpiring()
482482
*/
483483
public function withPath(?string $path)
484484
{
485-
$path = $path ?: self::$defaults['path'];
485+
$path = $path !== null && $path !== '' && $path !== '0' ? $path : self::$defaults['path'];
486486
$this->validatePrefix($this->prefix, $this->secure, $path, $this->domain);
487487

488488
$cookie = clone $this;

system/Database/BaseBuilder.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -1736,7 +1736,7 @@ public function countAllResults(bool $reset = true)
17361736
// Restore the LIMIT setting
17371737
$this->QBLimit = $limit;
17381738

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

17411741
if (empty($row)) {
17421742
return 0;
@@ -3167,11 +3167,11 @@ protected function compileWhereHaving(string $qbKey): string
31673167
$op = $this->getOperator($condition);
31683168
if (
31693169
$op === false
3170-
|| ! preg_match(
3170+
|| preg_match(
31713171
'/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(?<!\)))?(\)?)$/i',
31723172
$condition,
31733173
$matches
3174-
)
3174+
) !== 1
31753175
) {
31763176
continue;
31773177
}

system/Database/BaseConnection.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -610,7 +610,7 @@ abstract protected function execute(string $sql);
610610
*/
611611
public function query(string $sql, $binds = null, bool $setEscapeFlags = true, string $queryClass = '')
612612
{
613-
$queryClass = $queryClass ?: $this->queryClass;
613+
$queryClass = $queryClass !== '' && $queryClass !== '0' ? $queryClass : $this->queryClass;
614614

615615
if (empty($this->connID)) {
616616
$this->initialize();

system/Database/Database.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ protected function parseDSN(array $params): array
9696
{
9797
$dsn = parse_url($params['DSN']);
9898

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

system/Database/MigrationRunner.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -450,7 +450,7 @@ protected function migrationFromFile(string $path, string $namespace)
450450

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

453-
if (! preg_match($this->regex, $filename)) {
453+
if (preg_match($this->regex, $filename) !== 1) {
454454
return false;
455455
}
456456

system/Database/MySQLi/Forge.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -116,11 +116,11 @@ protected function _createTableAttributes(array $attributes): string
116116
}
117117
}
118118

119-
if ($this->db->charset !== '' && ! strpos($sql, 'CHARACTER SET') && ! strpos($sql, 'CHARSET')) {
119+
if ($this->db->charset !== '' && ! str_contains($sql, 'CHARACTER SET') && ! str_contains($sql, 'CHARSET')) {
120120
$sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset);
121121
}
122122

123-
if ($this->db->DBCollat !== '' && ! strpos($sql, 'COLLATE')) {
123+
if ($this->db->DBCollat !== '' && ! str_contains($sql, 'COLLATE')) {
124124
$sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat);
125125
}
126126

system/Database/Postgre/Connection.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,7 @@ public function error(): array
463463
{
464464
return [
465465
'code' => '',
466-
'message' => pg_last_error($this->connID) ?: '',
466+
'message' => pg_last_error($this->connID),
467467
];
468468
}
469469

system/Email/Email.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ public function setFrom($from, $name = '', $returnPath = null)
495495

496496
if ($name !== '') {
497497
// only use Q encoding if there are characters that would require it
498-
if (! preg_match('/[\200-\377]/', $name)) {
498+
if (preg_match('/[\200-\377]/', $name) !== 1) {
499499
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
500500
} else {
501501
$name = $this->prepQEncoding($name);
@@ -532,7 +532,7 @@ public function setReplyTo($replyto, $name = '')
532532
$this->tmpArchive['replyName'] = $name;
533533

534534
// only use Q encoding if there are characters that would require it
535-
if (! preg_match('/[\200-\377]/', $name)) {
535+
if (preg_match('/[\200-\377]/', $name) !== 1) {
536536
$name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"';
537537
} else {
538538
$name = $this->prepQEncoding($name);

system/HTTP/Files/UploadedFile.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,9 @@ public function getTempName(): string
302302
*/
303303
public function getExtension(): string
304304
{
305-
return $this->guessExtension() ?: $this->getClientExtension();
305+
$guessExtension = $this->guessExtension();
306+
307+
return $guessExtension !== '' ? $guessExtension : $this->getClientExtension();
306308
}
307309

308310
/**

system/HTTP/ResponseTrait.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ public function getCookieStore()
569569
*/
570570
public function hasCookie(string $name, ?string $value = null, string $prefix = ''): bool
571571
{
572-
$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
572+
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
573573

574574
return $this->cookieStore->has($name, $prefix, $value);
575575
}
@@ -589,7 +589,7 @@ public function getCookie(?string $name = null, string $prefix = '')
589589
}
590590

591591
try {
592-
$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
592+
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
593593

594594
return $this->cookieStore->get($name, $prefix);
595595
} catch (CookieException $e) {
@@ -610,7 +610,7 @@ public function deleteCookie(string $name = '', string $domain = '', string $pat
610610
return $this;
611611
}
612612

613-
$prefix = $prefix ?: Cookie::setDefaults()['prefix']; // to retain BC
613+
$prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC
614614

615615
$prefixed = $prefix . $name;
616616
$store = $this->cookieStore;

system/HTTP/SiteURI.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ public function siteUrl($relativePath = '', ?string $scheme = null, ?App $config
421421
$relativePath = $this->stringifyRelativePath($relativePath);
422422

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

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

system/Helpers/filesystem_helper.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ function delete_files(string $path, bool $delDir = false, bool $htdocs = false,
166166
continue;
167167
}
168168

169-
if (! $htdocs || ! preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename)) {
169+
if (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) {
170170
$isDir = $object->isDir();
171171
if ($isDir && $delDir) {
172172
rmdir($object->getPathname());

system/Helpers/form_helper.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ function form_open(string $action = '', $attributes = [], array $hidden = []): s
6262
// Add CSRF field if enabled, but leave it out for GET requests and requests to external websites
6363
$before = service('filters')->getFilters()['before'];
6464

65-
if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && ! stripos($form, 'method="get"')) {
65+
if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && str_contains($action, base_url()) && stripos($form, 'method="get"') === false) {
6666
$form .= csrf_field($csrfId ?? null);
6767
}
6868

system/Helpers/html_helper.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ function img($src = '', bool $indexPage = false, $attributes = ''): string
112112
$img = '<img';
113113

114114
// Check for a relative URI
115-
if (! preg_match('#^([a-z]+:)?//#i', $src['src']) && ! str_starts_with($src['src'], 'data:')) {
115+
if (preg_match('#^([a-z]+:)?//#i', $src['src']) !== 1 && ! str_starts_with($src['src'], 'data:')) {
116116
if ($indexPage) {
117117
$img .= ' src="' . site_url($src['src']) . '"';
118118
} else {
@@ -206,7 +206,7 @@ function script_tag($src = '', bool $indexPage = false): string
206206
}
207207

208208
foreach ($src as $k => $v) {
209-
if ($k === 'src' && ! preg_match('#^([a-z]+:)?//#i', $v)) {
209+
if ($k === 'src' && preg_match('#^([a-z]+:)?//#i', $v) !== 1) {
210210
if ($indexPage) {
211211
$script .= 'src="' . site_url($v) . '" ';
212212
} else {
@@ -252,7 +252,7 @@ function link_tag(
252252
$href = $href['href'] ?? '';
253253
}
254254

255-
if (! preg_match('#^([a-z]+:)?//#i', $href)) {
255+
if (preg_match('#^([a-z]+:)?//#i', $href) !== 1) {
256256
$attributes['href'] = $indexPage ? site_url($href) : slash_item('baseURL') . $href;
257257
} else {
258258
$attributes['href'] = $href;

system/I18n/TimeTrait.php

+3-3
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ trait TimeTrait
7373
*/
7474
public function __construct(?string $time = null, $timezone = null, ?string $locale = null)
7575
{
76-
$this->locale = $locale ?: Locale::getDefault();
76+
$this->locale = $locale !== null && $locale !== '' && $locale !== '0' ? $locale : Locale::getDefault();
7777

7878
$time ??= '';
7979

@@ -958,7 +958,7 @@ public function sameAs($testTime, ?string $timezone = null): bool
958958
if ($testTime instanceof DateTimeInterface) {
959959
$testTime = $testTime->format('Y-m-d H:i:s');
960960
} elseif (is_string($testTime)) {
961-
$timezone = $timezone ?: $this->timezone;
961+
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
962962
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
963963
$testTime = new DateTime($testTime, $timezone);
964964
$testTime = $testTime->format('Y-m-d H:i:s');
@@ -1108,7 +1108,7 @@ public function getUTCObject($time, ?string $timezone = null)
11081108
if ($time instanceof self) {
11091109
$time = $time->toDateTime();
11101110
} elseif (is_string($time)) {
1111-
$timezone = $timezone ?: $this->timezone;
1111+
$timezone = $timezone !== null && $timezone !== '' && $timezone !== '0' ? $timezone : $this->timezone;
11121112
$timezone = $timezone instanceof DateTimeZone ? $timezone : new DateTimeZone($timezone);
11131113
$time = new DateTime($time, $timezone);
11141114
}

system/Images/Image.php

+2-1
Original file line numberDiff line numberDiff line change
@@ -102,8 +102,9 @@ public function copy(string $targetPath, ?string $targetName = null, int $perms
102102
public function getProperties(bool $return = false)
103103
{
104104
$path = $this->getPathname();
105+
$vals = getimagesize($path);
105106

106-
if (! $vals = getimagesize($path)) {
107+
if ($vals === false) {
107108
throw ImageException::forFileNotSupported();
108109
}
109110

system/Router/RouteCollection.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -1329,7 +1329,7 @@ protected function fillRouteParams(string $from, ?array $params = null): string
13291329
$patterns = $matches[0];
13301330

13311331
foreach ($patterns as $index => $pattern) {
1332-
if (! preg_match('#^' . $pattern . '$#u', $params[$index])) {
1332+
if (preg_match('#^' . $pattern . '$#u', $params[$index]) !== 1) {
13331333
throw RouterException::forInvalidParameterType();
13341334
}
13351335

@@ -1391,7 +1391,7 @@ protected function buildReverseRoute(string $from, array $params): string
13911391
// or maybe $placeholder is not a placeholder, but a regex.
13921392
$pattern = $this->placeholders[$placeholderName] ?? $placeholder;
13931393

1394-
if (! preg_match('#^' . $pattern . '$#u', (string) $params[$index])) {
1394+
if (preg_match('#^' . $pattern . '$#u', (string) $params[$index]) !== 1) {
13951395
throw RouterException::forInvalidParameterType();
13961396
}
13971397

system/Session/Handlers/FileHandler.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ public function gc($max_lifetime)
290290

291291
while (($file = readdir($directory)) !== false) {
292292
// If the filename doesn't match this pattern, it's either not a session file or is not ours
293-
if (! preg_match($pattern, $file)
293+
if (preg_match($pattern, $file) !== 1
294294
|| ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file)
295295
|| ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false
296296
|| $mtime > $ts

system/Session/Handlers/MemcachedHandler.php

+2-2
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,12 @@ public function open($path, $name): bool
9393
}
9494

9595
if (
96-
! preg_match_all(
96+
preg_match_all(
9797
'#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#',
9898
$this->savePath,
9999
$matches,
100100
PREG_SET_ORDER
101-
)
101+
) === 0
102102
) {
103103
$this->memcached = null;
104104
$this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);

0 commit comments

Comments
 (0)