From 8a75daa150f490d926565cf159185d03f8b1a0b6 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 08:54:33 +0700 Subject: [PATCH 01/23] refactor: enable instanceof and strictBooleans rector set --- app/Views/errors/cli/error_exception.php | 2 +- rector.php | 8 +--- system/Cache/Handlers/FileHandler.php | 2 +- .../ControllerMethodReader.php | 2 +- .../Routes/ControllerMethodReader.php | 2 +- system/Config/DotEnv.php | 2 +- system/Config/Services.php | 8 ++-- system/Cookie/Cookie.php | 2 +- system/Database/BaseBuilder.php | 6 +-- system/Database/BaseConnection.php | 2 +- system/Database/Database.php | 2 +- system/Database/MySQLi/Forge.php | 4 +- system/Database/Postgre/Connection.php | 2 +- system/Email/Email.php | 4 +- system/HTTP/Files/UploadedFile.php | 2 +- system/HTTP/ResponseTrait.php | 6 +-- system/HTTP/SiteURI.php | 2 +- system/Helpers/filesystem_helper.php | 2 +- system/Helpers/html_helper.php | 6 +-- system/I18n/TimeTrait.php | 6 +-- system/Images/Image.php | 2 +- system/Session/Handlers/FileHandler.php | 2 +- system/Session/Handlers/MemcachedHandler.php | 4 +- system/Session/Session.php | 2 +- system/Test/CIUnitTestCase.php | 2 +- system/Typography/Typography.php | 2 +- system/Validation/Rules.php | 4 +- system/Validation/StrictRules/Rules.php | 4 +- system/Validation/Validation.php | 2 +- system/View/Parser.php | 4 +- .../identical.alwaysFalse.neon | 8 ++++ utils/phpstan-baseline/loader.neon | 2 + .../offsetAccess.nonOffsetAccessible.neon | 23 ++++++++++ .../ternary.shortNotAllowed.neon | 45 +++---------------- ...nderscoreToCamelCaseVariableNameRector.php | 2 +- 35 files changed, 87 insertions(+), 93 deletions(-) create mode 100644 utils/phpstan-baseline/identical.alwaysFalse.neon create mode 100644 utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon diff --git a/app/Views/errors/cli/error_exception.php b/app/Views/errors/cli/error_exception.php index 9f47d25141d2..2bf1459d4094 100644 --- a/app/Views/errors/cli/error_exception.php +++ b/app/Views/errors/cli/error_exception.php @@ -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'] ?? []))); diff --git a/rector.php b/rector.php index e7c98746eb86..ee8621691862 100644 --- a/rector.php +++ b/rector.php @@ -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; @@ -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 diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index fd0630a9982c..ea7c00e382e2 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -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); } } diff --git a/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php b/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php index e08a16ff7a60..2755a389ffc3 100644 --- a/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php +++ b/system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php @@ -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); diff --git a/system/Commands/Utilities/Routes/ControllerMethodReader.php b/system/Commands/Utilities/Routes/ControllerMethodReader.php index c443b669465a..b40a832b4f48 100644 --- a/system/Commands/Utilities/Routes/ControllerMethodReader.php +++ b/system/Commands/Utilities/Routes/ControllerMethodReader.php @@ -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, diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index db7152fd09d5..9c120afec523 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -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}"); } diff --git a/system/Config/Services.php b/system/Config/Services.php index 61026de4292c..aa8c180a3388 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -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); @@ -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); } @@ -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')); @@ -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')); diff --git a/system/Cookie/Cookie.php b/system/Cookie/Cookie.php index 01b10db19b65..d75cce26ac09 100644 --- a/system/Cookie/Cookie.php +++ b/system/Cookie/Cookie.php @@ -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; diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index e52baa39f570..2b947ce952e2 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -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; @@ -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*(.*(?queryClass; + $queryClass = $queryClass !== '' && $queryClass !== '0' ? $queryClass : $this->queryClass; if (empty($this->connID)) { $this->initialize(); diff --git a/system/Database/Database.php b/system/Database/Database.php index 23b6cd0f8d16..3d4840f2e595 100644 --- a/system/Database/Database.php +++ b/system/Database/Database.php @@ -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.'); } diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index 3bde0c518daf..54c073389fd3 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -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); } diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 2826ab1bf53c..8d2edc94296c 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -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) : '', ]; } diff --git a/system/Email/Email.php b/system/Email/Email.php index 51f610f6556c..3e4584390928 100644 --- a/system/Email/Email.php +++ b/system/Email/Email.php @@ -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); @@ -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); diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index 78643aa7166e..0626aeb5581f 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -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(); } /** diff --git a/system/HTTP/ResponseTrait.php b/system/HTTP/ResponseTrait.php index 97ef4927d35c..02ecfb40263d 100644 --- a/system/HTTP/ResponseTrait.php +++ b/system/HTTP/ResponseTrait.php @@ -569,7 +569,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); } @@ -589,7 +589,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) { @@ -610,7 +610,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; diff --git a/system/HTTP/SiteURI.php b/system/HTTP/SiteURI.php index 91b14bc05456..2be70a7773ef 100644 --- a/system/HTTP/SiteURI.php +++ b/system/HTTP/SiteURI.php @@ -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); diff --git a/system/Helpers/filesystem_helper.php b/system/Helpers/filesystem_helper.php index 4b0b49be6464..fded9f64ef20 100644 --- a/system/Helpers/filesystem_helper.php +++ b/system/Helpers/filesystem_helper.php @@ -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()); diff --git a/system/Helpers/html_helper.php b/system/Helpers/html_helper.php index 30733acd5175..736960606457 100644 --- a/system/Helpers/html_helper.php +++ b/system/Helpers/html_helper.php @@ -112,7 +112,7 @@ function img($src = '', bool $indexPage = false, $attributes = ''): string $img = ' $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 { @@ -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; diff --git a/system/I18n/TimeTrait.php b/system/I18n/TimeTrait.php index fefb2fc544a3..354b7542e755 100644 --- a/system/I18n/TimeTrait.php +++ b/system/I18n/TimeTrait.php @@ -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 ??= ''; @@ -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'); @@ -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); } diff --git a/system/Images/Image.php b/system/Images/Image.php index ec6d4b8fa5c0..1f857b00f780 100644 --- a/system/Images/Image.php +++ b/system/Images/Image.php @@ -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(); } diff --git a/system/Session/Handlers/FileHandler.php b/system/Session/Handlers/FileHandler.php index 4dbec779526a..e0e52442569f 100644 --- a/system/Session/Handlers/FileHandler.php +++ b/system/Session/Handlers/FileHandler.php @@ -290,7 +290,7 @@ public function gc($max_lifetime) while (($file = readdir($directory)) !== false) { // If the filename doesn't match this pattern, it's either not a session file or is not ours - if (! preg_match($pattern, $file) + if (in_array(preg_match($pattern, $file), [0, false], true) || ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file) || ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false || $mtime > $ts diff --git a/system/Session/Handlers/MemcachedHandler.php b/system/Session/Handlers/MemcachedHandler.php index 83a5d334ed85..193ec533539e 100644 --- a/system/Session/Handlers/MemcachedHandler.php +++ b/system/Session/Handlers/MemcachedHandler.php @@ -93,12 +93,12 @@ public function open($path, $name): bool } if ( - ! preg_match_all( + in_array(preg_match_all( '#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER - ) + ), [0, false], true) ) { $this->memcached = null; $this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath); diff --git a/system/Session/Session.php b/system/Session/Session.php index 60e4dbef4101..ca26c44df420 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -234,7 +234,7 @@ public function start() // Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers if (isset($_COOKIE[$this->config->cookieName]) - && (! is_string($_COOKIE[$this->config->cookieName]) || ! preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName])) + && (! is_string($_COOKIE[$this->config->cookieName]) || in_array(preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]), [0, false], true)) ) { unset($_COOKIE[$this->config->cookieName]); } diff --git a/system/Test/CIUnitTestCase.php b/system/Test/CIUnitTestCase.php index 9e82ddb4f6dd..c515b7e3d3c2 100644 --- a/system/Test/CIUnitTestCase.php +++ b/system/Test/CIUnitTestCase.php @@ -374,7 +374,7 @@ public function assertLogContains(string $level, string $logMessage, string $mes { $this->assertTrue( TestLogger::didLog($level, $logMessage, false), - $message ?: sprintf( + $message !== '' && $message !== '0' ? $message : sprintf( 'Failed asserting that logs have a record of message containing "%s" with level "%s".', $logMessage, $level diff --git a/system/Typography/Typography.php b/system/Typography/Typography.php index c8ca5131171c..be2d0b36c7da 100644 --- a/system/Typography/Typography.php +++ b/system/Typography/Typography.php @@ -171,7 +171,7 @@ public function autoTypography(string $str, bool $reduceLinebreaks = false): str } // No opening block level tag? Add it if needed. - if (! preg_match('/^\s*<(?:' . $this->blockElements . ')/i', $str)) { + if (in_array(preg_match('/^\s*<(?:' . $this->blockElements . ')/i', $str), [0, false], true)) { $str = preg_replace('/^(.*?)<(' . $this->blockElements . ')/i', '

$1

<$2', $str); } diff --git a/system/Validation/Rules.php b/system/Validation/Rules.php index 715e2e51c7e1..7ee680d90698 100644 --- a/system/Validation/Rules.php +++ b/system/Validation/Rules.php @@ -140,7 +140,7 @@ public function is_not_unique($str, string $field, array $data): bool if ( $whereField !== null && $whereField !== '' && $whereValue !== null && $whereValue !== '' - && ! preg_match('/^\{(\w+)\}$/', $whereValue) + && in_array(preg_match('/^\{(\w+)\}$/', $whereValue), [0, false], true) ) { $row = $row->where($whereField, $whereValue); } @@ -198,7 +198,7 @@ public function is_unique($str, string $field, array $data): bool if ( $ignoreField !== null && $ignoreField !== '' && $ignoreValue !== null && $ignoreValue !== '' - && ! preg_match('/^\{(\w+)\}$/', $ignoreValue) + && in_array(preg_match('/^\{(\w+)\}$/', $ignoreValue), [0, false], true) ) { $row = $row->where("{$ignoreField} !=", $ignoreValue); } diff --git a/system/Validation/StrictRules/Rules.php b/system/Validation/StrictRules/Rules.php index ec02a4e0a0ac..3bc130bd93e4 100644 --- a/system/Validation/StrictRules/Rules.php +++ b/system/Validation/StrictRules/Rules.php @@ -164,7 +164,7 @@ public function is_not_unique($str, string $field, array $data): bool if ( $whereField !== null && $whereField !== '' && $whereValue !== null && $whereValue !== '' - && ! preg_match('/^\{(\w+)\}$/', $whereValue) + && in_array(preg_match('/^\{(\w+)\}$/', $whereValue), [0, false], true) ) { $row = $row->where($whereField, $whereValue); } @@ -224,7 +224,7 @@ public function is_unique($str, string $field, array $data): bool if ( $ignoreField !== null && $ignoreField !== '' && $ignoreValue !== null && $ignoreValue !== '' - && ! preg_match('/^\{(\w+)\}$/', $ignoreValue) + && in_array(preg_match('/^\{(\w+)\}$/', $ignoreValue), [0, false], true) ) { $row = $row->where("{$ignoreField} !=", $ignoreValue); } diff --git a/system/Validation/Validation.php b/system/Validation/Validation.php index a942a32bceea..c00329d670bb 100644 --- a/system/Validation/Validation.php +++ b/system/Validation/Validation.php @@ -181,7 +181,7 @@ public function run(?array $data = null, ?string $group = null, $dbGroup = null) ); // if keys not found - $values = $values ?: [$field => null]; + $values = $values !== [] ? $values : [$field => null]; } else { $values = dot_array_search($field, $data); } diff --git a/system/View/Parser.php b/system/View/Parser.php index 8a26cf825d3f..80af795bceb8 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -613,7 +613,7 @@ public function shouldAddEscaping(string $key) $escape = false; } // If no `esc` filter is found, then we'll need to add one. - elseif (! preg_match('/\s+esc/u', $key)) { + elseif (in_array(preg_match('/\s+esc/u', $key), [0, false], true)) { $escape = 'html'; } @@ -691,7 +691,7 @@ protected function parsePlugins(string $template) * $matches[1] = all parameters string in opening tag * $matches[2] = content between the tags to send to the plugin. */ - if (! preg_match_all($pattern, $template, $matches, PREG_SET_ORDER)) { + if (in_array(preg_match_all($pattern, $template, $matches, PREG_SET_ORDER), [0, false], true)) { continue; } diff --git a/utils/phpstan-baseline/identical.alwaysFalse.neon b/utils/phpstan-baseline/identical.alwaysFalse.neon new file mode 100644 index 000000000000..a048001eed03 --- /dev/null +++ b/utils/phpstan-baseline/identical.alwaysFalse.neon @@ -0,0 +1,8 @@ +# total 1 error + +parameters: + ignoreErrors: + - + message: '#^Strict comparison using \=\=\= between array\{0\: int\<0, max\>, 1\: int\<0, max\>, 2\: int, 3\: string, mime\: string, channels\?\: int, bits\?\: int\}\|false and array\{\} will always evaluate to false\.$#' + count: 1 + path: ../../system/Images/Image.php diff --git a/utils/phpstan-baseline/loader.neon b/utils/phpstan-baseline/loader.neon index 789d5ef7e1ef..c799a156aa5d 100644 --- a/utils/phpstan-baseline/loader.neon +++ b/utils/phpstan-baseline/loader.neon @@ -22,6 +22,7 @@ includes: - generator.returnType.neon - generator.valueType.neon - greaterOrEqual.invalid.neon + - identical.alwaysFalse.neon - if.condNotBoolean.neon - isset.offset.neon - isset.property.neon @@ -40,6 +41,7 @@ includes: - nullCoalesce.expr.neon - nullCoalesce.property.neon - nullCoalesce.variable.neon + - offsetAccess.nonOffsetAccessible.neon - offsetAccess.notFound.neon - parameterByRef.unusedType.neon - property.defaultValue.neon diff --git a/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon b/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon new file mode 100644 index 000000000000..9aa901319837 --- /dev/null +++ b/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon @@ -0,0 +1,23 @@ +# total 4 errors + +parameters: + ignoreErrors: + - + message: '#^Cannot access offset 0 on false\.$#' + count: 2 + path: ../../system/Images/Image.php + + - + message: '#^Cannot access offset 1 on false\.$#' + count: 2 + path: ../../system/Images/Image.php + + - + message: '#^Cannot access offset 2 on false\.$#' + count: 3 + path: ../../system/Images/Image.php + + - + message: '#^Cannot access offset 3 on false\.$#' + count: 2 + path: ../../system/Images/Image.php diff --git a/utils/phpstan-baseline/ternary.shortNotAllowed.neon b/utils/phpstan-baseline/ternary.shortNotAllowed.neon index 15e447d499c0..a3dfc431cd94 100644 --- a/utils/phpstan-baseline/ternary.shortNotAllowed.neon +++ b/utils/phpstan-baseline/ternary.shortNotAllowed.neon @@ -1,4 +1,4 @@ -# total 34 errors +# total 27 errors parameters: ignoreErrors: @@ -17,16 +17,6 @@ parameters: count: 1 path: ../../system/Commands/Utilities/Namespaces.php - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/Commands/Utilities/Routes/AutoRouterImproved/ControllerMethodReader.php - - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/Commands/Utilities/Routes/ControllerMethodReader.php - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' count: 2 @@ -35,23 +25,8 @@ parameters: - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' count: 4 - path: ../../system/Config/Services.php - - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 5 path: ../../system/Cookie/Cookie.php - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/Database/BaseConnection.php - - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/Database/Postgre/Connection.php - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' count: 1 @@ -79,12 +54,7 @@ parameters: - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/HTTP/Files/UploadedFile.php - - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 5 + count: 2 path: ../../system/HTTP/Response.php - @@ -94,12 +64,12 @@ parameters: - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 4 + count: 1 path: ../../system/I18n/Time.php - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 4 + count: 1 path: ../../system/I18n/TimeLegacy.php - @@ -117,11 +87,6 @@ parameters: count: 1 path: ../../system/Session/Session.php - - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 1 - path: ../../system/Test/CIUnitTestCase.php - - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' count: 2 @@ -129,7 +94,7 @@ parameters: - message: '#^Short ternary operator is not allowed\. Use null coalesce operator if applicable or consider using long ternary\.$#' - count: 2 + count: 1 path: ../../system/Validation/Validation.php - diff --git a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php index 1e1469c7f615..381a7dfb3a1c 100644 --- a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php +++ b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php @@ -178,7 +178,7 @@ private function updateDocblock(string $variableName, string $camelCaseName, ?Fu return; } - if (! preg_match(sprintf(self::PARAM_NAME_REGEX, $variableName), $docCommentText)) { + if (in_array(preg_match(sprintf(self::PARAM_NAME_REGEX, $variableName), $docCommentText), [0, false], true)) { return; } From b9a0f96937a26f8d9aab6c2b00edde329bf0e0b1 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:01:30 +0700 Subject: [PATCH 02/23] refactor: bump to rector 2.0.4 --- composer.json | 2 +- system/ThirdParty/Escaper/Escaper.php | 31 ++++++++++++--------------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/composer.json b/composer.json index 879a42267043..ec9f29ec2d1b 100644 --- a/composer.json +++ b/composer.json @@ -28,7 +28,7 @@ "phpunit/phpcov": "^9.0.2 || ^10.0", "phpunit/phpunit": "^10.5.16 || ^11.2", "predis/predis": "^1.1 || ^2.0", - "rector/rector": "2.0.3", + "rector/rector": "2.0.4", "shipmonk/phpstan-baseline-per-identifier": "^2.0" }, "replace": { diff --git a/system/ThirdParty/Escaper/Escaper.php b/system/ThirdParty/Escaper/Escaper.php index c4964cb55e4a..1e5bc7f9fad9 100644 --- a/system/ThirdParty/Escaper/Escaper.php +++ b/system/ThirdParty/Escaper/Escaper.php @@ -25,6 +25,8 @@ /** * Context specific methods for use in secure output escaping + * + * @final */ class Escaper { @@ -49,7 +51,7 @@ class Escaper * Current encoding for escaping. If not UTF-8, we convert strings from this encoding * pre-escaping and back to this encoding post-escaping. * - * @var string + * @var non-empty-string */ protected $encoding = 'utf-8'; @@ -88,7 +90,7 @@ class Escaper /** * List of all encoding supported by this class * - * @var array + * @var list */ protected $supportedEncodings = [ 'iso-8859-1', @@ -131,6 +133,7 @@ class Escaper * Constructor: Single parameter allows setting of global encoding for use by * the current object. * + * @param non-empty-string|null $encoding * @throws Exception\InvalidArgumentException */ public function __construct(?string $encoding = null) @@ -159,25 +162,19 @@ public function __construct(?string $encoding = null) // set matcher callbacks $this->htmlAttrMatcher = /** @param array $matches */ - function (array $matches): string { - return $this->htmlAttrMatcher($matches); - }; + fn(array $matches): string => $this->htmlAttrMatcher($matches); $this->jsMatcher = /** @param array $matches */ - function (array $matches): string { - return $this->jsMatcher($matches); - }; + fn(array $matches): string => $this->jsMatcher($matches); $this->cssMatcher = /** @param array $matches */ - function (array $matches): string { - return $this->cssMatcher($matches); - }; + fn(array $matches): string => $this->cssMatcher($matches); } /** * Return the encoding that all output/input is expected to be encoded in. * - * @return string + * @return non-empty-string */ public function getEncoding() { @@ -188,7 +185,7 @@ public function getEncoding() * Escape a string for the HTML Body context where there are very few characters * of special meaning. Internally this will use htmlspecialchars(). * - * @return string + * @return ($string is non-empty-string ? non-empty-string : string) */ public function escapeHtml(string $string) { @@ -200,7 +197,7 @@ public function escapeHtml(string $string) * to escape that are not covered by htmlspecialchars() to cover cases where an attribute * might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE). * - * @return string + * @return ($string is non-empty-string ? non-empty-string : string) */ public function escapeHtmlAttr(string $string) { @@ -222,7 +219,7 @@ public function escapeHtmlAttr(string $string) * Backslash escaping is not used as it still leaves the escaped character as-is and so * is not useful in a HTML context. * - * @return string + * @return ($string is non-empty-string ? non-empty-string : string) */ public function escapeJs(string $string) { @@ -240,7 +237,7 @@ public function escapeJs(string $string) * an entire URI - only a subcomponent being inserted. The function is a simple proxy * to rawurlencode() which now implements RFC 3986 since PHP 5.3 completely. * - * @return string + * @return ($string is non-empty-string ? non-empty-string : string) */ public function escapeUrl(string $string) { @@ -251,7 +248,7 @@ public function escapeUrl(string $string) * Escape a string for the CSS context. CSS escaping can be applied to any string being * inserted into CSS and escapes everything except alphanumerics. * - * @return string + * @return ($string is non-empty-string ? non-empty-string : string) */ public function escapeCss(string $string) { From cc99bc38f915203698714553171371f95d78202c Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:06:31 +0700 Subject: [PATCH 03/23] refactor: clean condition check --- system/Config/DotEnv.php | 2 +- system/Database/Database.php | 2 +- system/Images/Image.php | 3 ++- 3 files changed, 4 insertions(+), 3 deletions(-) diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index 9c120afec523..9e890a88b051 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -94,7 +94,7 @@ public function parse(): ?array */ protected function setVariable(string $name, string $value = '') { - if (in_array(getenv($name, true), ['', '0'], true) || getenv($name, true) === [] || getenv($name, true) === false) { + if (in_array(getenv($name, true), ['', '0', [], false], true)) { putenv("{$name}={$value}"); } diff --git a/system/Database/Database.php b/system/Database/Database.php index 3d4840f2e595..e09dcdd27481 100644 --- a/system/Database/Database.php +++ b/system/Database/Database.php @@ -96,7 +96,7 @@ protected function parseDSN(array $params): array { $dsn = parse_url($params['DSN']); - if ($dsn === 0 || ($dsn === '' || $dsn === '0') || $dsn === [] || $dsn === false || $dsn === null) { + if ($dsn === 0 || $dsn === '' || $dsn === '0' || $dsn === [] || $dsn === false || $dsn === null) { throw new InvalidArgumentException('Your DSN connection string is invalid.'); } diff --git a/system/Images/Image.php b/system/Images/Image.php index 1f857b00f780..ab9aa51a6ec7 100644 --- a/system/Images/Image.php +++ b/system/Images/Image.php @@ -102,8 +102,9 @@ public function copy(string $targetPath, ?string $targetName = null, int $perms public function getProperties(bool $return = false) { $path = $this->getPathname(); + $vals = getimagesize($path); - if ($vals = getimagesize($path) === [] || $vals = getimagesize($path) === false) { + if ($vals === [] || $vals === false) { throw ImageException::forFileNotSupported(); } From 8955e908eb7f6731fde7dba0fe70cd84dfcb3baf Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:08:56 +0700 Subject: [PATCH 04/23] refactor: revert ThirdParty change --- system/ThirdParty/Escaper/Escaper.php | 31 +++++++++++++++------------ 1 file changed, 17 insertions(+), 14 deletions(-) diff --git a/system/ThirdParty/Escaper/Escaper.php b/system/ThirdParty/Escaper/Escaper.php index 1e5bc7f9fad9..c4964cb55e4a 100644 --- a/system/ThirdParty/Escaper/Escaper.php +++ b/system/ThirdParty/Escaper/Escaper.php @@ -25,8 +25,6 @@ /** * Context specific methods for use in secure output escaping - * - * @final */ class Escaper { @@ -51,7 +49,7 @@ class Escaper * Current encoding for escaping. If not UTF-8, we convert strings from this encoding * pre-escaping and back to this encoding post-escaping. * - * @var non-empty-string + * @var string */ protected $encoding = 'utf-8'; @@ -90,7 +88,7 @@ class Escaper /** * List of all encoding supported by this class * - * @var list + * @var array */ protected $supportedEncodings = [ 'iso-8859-1', @@ -133,7 +131,6 @@ class Escaper * Constructor: Single parameter allows setting of global encoding for use by * the current object. * - * @param non-empty-string|null $encoding * @throws Exception\InvalidArgumentException */ public function __construct(?string $encoding = null) @@ -162,19 +159,25 @@ public function __construct(?string $encoding = null) // set matcher callbacks $this->htmlAttrMatcher = /** @param array $matches */ - fn(array $matches): string => $this->htmlAttrMatcher($matches); + function (array $matches): string { + return $this->htmlAttrMatcher($matches); + }; $this->jsMatcher = /** @param array $matches */ - fn(array $matches): string => $this->jsMatcher($matches); + function (array $matches): string { + return $this->jsMatcher($matches); + }; $this->cssMatcher = /** @param array $matches */ - fn(array $matches): string => $this->cssMatcher($matches); + function (array $matches): string { + return $this->cssMatcher($matches); + }; } /** * Return the encoding that all output/input is expected to be encoded in. * - * @return non-empty-string + * @return string */ public function getEncoding() { @@ -185,7 +188,7 @@ public function getEncoding() * Escape a string for the HTML Body context where there are very few characters * of special meaning. Internally this will use htmlspecialchars(). * - * @return ($string is non-empty-string ? non-empty-string : string) + * @return string */ public function escapeHtml(string $string) { @@ -197,7 +200,7 @@ public function escapeHtml(string $string) * to escape that are not covered by htmlspecialchars() to cover cases where an attribute * might be unquoted or quoted illegally (e.g. backticks are valid quotes for IE). * - * @return ($string is non-empty-string ? non-empty-string : string) + * @return string */ public function escapeHtmlAttr(string $string) { @@ -219,7 +222,7 @@ public function escapeHtmlAttr(string $string) * Backslash escaping is not used as it still leaves the escaped character as-is and so * is not useful in a HTML context. * - * @return ($string is non-empty-string ? non-empty-string : string) + * @return string */ public function escapeJs(string $string) { @@ -237,7 +240,7 @@ public function escapeJs(string $string) * an entire URI - only a subcomponent being inserted. The function is a simple proxy * to rawurlencode() which now implements RFC 3986 since PHP 5.3 completely. * - * @return ($string is non-empty-string ? non-empty-string : string) + * @return string */ public function escapeUrl(string $string) { @@ -248,7 +251,7 @@ public function escapeUrl(string $string) * Escape a string for the CSS context. CSS escaping can be applied to any string being * inserted into CSS and escapes everything except alphanumerics. * - * @return ($string is non-empty-string ? non-empty-string : string) + * @return string */ public function escapeCss(string $string) { From 09b9b0c1ceb5f5b23400f7d83211d6bec3aee665 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:12:55 +0700 Subject: [PATCH 05/23] refactor: re-run phpstan baseline --- utils/phpstan-baseline/loader.neon | 1 - .../offsetAccess.nonOffsetAccessible.neon | 23 ------------------- 2 files changed, 24 deletions(-) delete mode 100644 utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon diff --git a/utils/phpstan-baseline/loader.neon b/utils/phpstan-baseline/loader.neon index c799a156aa5d..17a374d67df1 100644 --- a/utils/phpstan-baseline/loader.neon +++ b/utils/phpstan-baseline/loader.neon @@ -41,7 +41,6 @@ includes: - nullCoalesce.expr.neon - nullCoalesce.property.neon - nullCoalesce.variable.neon - - offsetAccess.nonOffsetAccessible.neon - offsetAccess.notFound.neon - parameterByRef.unusedType.neon - property.defaultValue.neon diff --git a/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon b/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon deleted file mode 100644 index 9aa901319837..000000000000 --- a/utils/phpstan-baseline/offsetAccess.nonOffsetAccessible.neon +++ /dev/null @@ -1,23 +0,0 @@ -# total 4 errors - -parameters: - ignoreErrors: - - - message: '#^Cannot access offset 0 on false\.$#' - count: 2 - path: ../../system/Images/Image.php - - - - message: '#^Cannot access offset 1 on false\.$#' - count: 2 - path: ../../system/Images/Image.php - - - - message: '#^Cannot access offset 2 on false\.$#' - count: 3 - path: ../../system/Images/Image.php - - - - message: '#^Cannot access offset 3 on false\.$#' - count: 2 - path: ../../system/Images/Image.php From 01d7705eed1cf41f89f6c49b5743bc7ed3c7ee93 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:17:16 +0700 Subject: [PATCH 06/23] refactor: fix never empty array on Image --- system/Images/Image.php | 2 +- utils/phpstan-baseline/identical.alwaysFalse.neon | 8 -------- utils/phpstan-baseline/loader.neon | 1 - 3 files changed, 1 insertion(+), 10 deletions(-) delete mode 100644 utils/phpstan-baseline/identical.alwaysFalse.neon diff --git a/system/Images/Image.php b/system/Images/Image.php index ab9aa51a6ec7..55754e339535 100644 --- a/system/Images/Image.php +++ b/system/Images/Image.php @@ -104,7 +104,7 @@ public function getProperties(bool $return = false) $path = $this->getPathname(); $vals = getimagesize($path); - if ($vals === [] || $vals === false) { + if ($vals === false) { throw ImageException::forFileNotSupported(); } diff --git a/utils/phpstan-baseline/identical.alwaysFalse.neon b/utils/phpstan-baseline/identical.alwaysFalse.neon deleted file mode 100644 index a048001eed03..000000000000 --- a/utils/phpstan-baseline/identical.alwaysFalse.neon +++ /dev/null @@ -1,8 +0,0 @@ -# total 1 error - -parameters: - ignoreErrors: - - - message: '#^Strict comparison using \=\=\= between array\{0\: int\<0, max\>, 1\: int\<0, max\>, 2\: int, 3\: string, mime\: string, channels\?\: int, bits\?\: int\}\|false and array\{\} will always evaluate to false\.$#' - count: 1 - path: ../../system/Images/Image.php diff --git a/utils/phpstan-baseline/loader.neon b/utils/phpstan-baseline/loader.neon index 17a374d67df1..789d5ef7e1ef 100644 --- a/utils/phpstan-baseline/loader.neon +++ b/utils/phpstan-baseline/loader.neon @@ -22,7 +22,6 @@ includes: - generator.returnType.neon - generator.valueType.neon - greaterOrEqual.invalid.neon - - identical.alwaysFalse.neon - if.condNotBoolean.neon - isset.offset.neon - isset.property.neon From d9b68d1434cd136bff20e6d18dc7bc212de553cf Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:34:04 +0700 Subject: [PATCH 07/23] refactor: avoid repetitive call pg_last_error() --- system/Database/Postgre/Connection.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 8d2edc94296c..70f3ff461689 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -461,9 +461,10 @@ protected function _enableForeignKeyChecks() */ public function error(): array { + $lastError = pg_last_error($this->connID); return [ 'code' => '', - 'message' => ! in_array(pg_last_error($this->connID), ['', '0'], true) ? pg_last_error($this->connID) : '', + 'message' => ! in_array($lastError, ['', '0'], true) ? $lastError : '', ]; } From e1264b519a7dc3370f78f35ce58a4dcd7da8aa7f Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:39:44 +0700 Subject: [PATCH 08/23] refactor: pg_last_error() always returns string --- system/Database/Postgre/Connection.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 70f3ff461689..4ce2b0763536 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -461,10 +461,9 @@ protected function _enableForeignKeyChecks() */ public function error(): array { - $lastError = pg_last_error($this->connID); return [ 'code' => '', - 'message' => ! in_array($lastError, ['', '0'], true) ? $lastError : '', + 'message' => pg_last_error($this->connID), ]; } From 44f8271bc0c34771258ea518080099ae0b0c07d6 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 09:58:46 +0700 Subject: [PATCH 09/23] refactor: use return empty string on pg_last_error() got empty "0" --- system/Database/Postgre/Connection.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 4ce2b0763536..2dc1a7c717e9 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -461,9 +461,11 @@ protected function _enableForeignKeyChecks() */ public function error(): array { + $lastError = pg_last_error($this->connID); + return [ 'code' => '', - 'message' => pg_last_error($this->connID), + 'message' => ! in_array($lastError, ['', '0'], true) ? $lastError : '', ]; } From 202be977dd74fedebde69febc88d5fa7131ebadb Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:06:01 +0700 Subject: [PATCH 10/23] refactor: various compare !== 1 on preg_match() --- system/Cache/Handlers/FileHandler.php | 2 +- system/Database/BaseBuilder.php | 4 ++-- system/Helpers/filesystem_helper.php | 2 +- system/Validation/Rules.php | 4 ++-- system/Validation/StrictRules/Rules.php | 4 ++-- utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/system/Cache/Handlers/FileHandler.php b/system/Cache/Handlers/FileHandler.php index ea7c00e382e2..525616a71068 100644 --- a/system/Cache/Handlers/FileHandler.php +++ b/system/Cache/Handlers/FileHandler.php @@ -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 || in_array(preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename), [0, false], true)) { + } elseif (! $htdocs || preg_match('/^(\.htaccess|index\.(html|htm|php)|web\.config)$/i', $filename) !== 1) { @unlink($path . DIRECTORY_SEPARATOR . $filename); } } diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index 2b947ce952e2..e738a331d608 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -3167,11 +3167,11 @@ protected function compileWhereHaving(string $qbKey): string $op = $this->getOperator($condition); if ( $op === false - || in_array(preg_match( + || preg_match( '/^(\(?)(.*)(' . preg_quote($op, '/') . ')\s*(.*(?isDir(); if ($isDir && $delDir) { rmdir($object->getPathname()); diff --git a/system/Validation/Rules.php b/system/Validation/Rules.php index 7ee680d90698..7f2f0bd941ec 100644 --- a/system/Validation/Rules.php +++ b/system/Validation/Rules.php @@ -140,7 +140,7 @@ public function is_not_unique($str, string $field, array $data): bool if ( $whereField !== null && $whereField !== '' && $whereValue !== null && $whereValue !== '' - && in_array(preg_match('/^\{(\w+)\}$/', $whereValue), [0, false], true) + && preg_match('/^\{(\w+)\}$/', $whereValue) !== 1 ) { $row = $row->where($whereField, $whereValue); } @@ -198,7 +198,7 @@ public function is_unique($str, string $field, array $data): bool if ( $ignoreField !== null && $ignoreField !== '' && $ignoreValue !== null && $ignoreValue !== '' - && in_array(preg_match('/^\{(\w+)\}$/', $ignoreValue), [0, false], true) + && preg_match('/^\{(\w+)\}$/', $ignoreValue) !== 1 ) { $row = $row->where("{$ignoreField} !=", $ignoreValue); } diff --git a/system/Validation/StrictRules/Rules.php b/system/Validation/StrictRules/Rules.php index 3bc130bd93e4..c9b98c479875 100644 --- a/system/Validation/StrictRules/Rules.php +++ b/system/Validation/StrictRules/Rules.php @@ -164,7 +164,7 @@ public function is_not_unique($str, string $field, array $data): bool if ( $whereField !== null && $whereField !== '' && $whereValue !== null && $whereValue !== '' - && in_array(preg_match('/^\{(\w+)\}$/', $whereValue), [0, false], true) + && preg_match('/^\{(\w+)\}$/', $whereValue) !== 1 ) { $row = $row->where($whereField, $whereValue); } @@ -224,7 +224,7 @@ public function is_unique($str, string $field, array $data): bool if ( $ignoreField !== null && $ignoreField !== '' && $ignoreValue !== null && $ignoreValue !== '' - && in_array(preg_match('/^\{(\w+)\}$/', $ignoreValue), [0, false], true) + && preg_match('/^\{(\w+)\}$/', $ignoreValue) !== 1 ) { $row = $row->where("{$ignoreField} !=", $ignoreValue); } diff --git a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php index 381a7dfb3a1c..93817c45bbd5 100644 --- a/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php +++ b/utils/src/Rector/UnderscoreToCamelCaseVariableNameRector.php @@ -178,7 +178,7 @@ private function updateDocblock(string $variableName, string $camelCaseName, ?Fu return; } - if (in_array(preg_match(sprintf(self::PARAM_NAME_REGEX, $variableName), $docCommentText), [0, false], true)) { + if (preg_match(sprintf(self::PARAM_NAME_REGEX, $variableName), $docCommentText) !== 1) { return; } From 87b4248ba2e9f3263aa58a77fb7523371b1e36b1 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:29:15 +0700 Subject: [PATCH 11/23] refactor: use falsy check on getenv() --- system/Config/DotEnv.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index 9e890a88b051..d4a7d9e87389 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -94,7 +94,7 @@ public function parse(): ?array */ protected function setVariable(string $name, string $value = '') { - if (in_array(getenv($name, true), ['', '0', [], false], true)) { + if (getenv($name, true) === false) { putenv("{$name}={$value}"); } From dab1a72ef29db3291aa2a5d3edddcb6f5cfb9bfd Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:33:09 +0700 Subject: [PATCH 12/23] refactor: more !== 1 compare on preg_match() --- system/Email/Email.php | 4 ++-- system/Helpers/html_helper.php | 6 +++--- system/Session/Handlers/FileHandler.php | 2 +- system/Session/Session.php | 2 +- system/Typography/Typography.php | 2 +- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/system/Email/Email.php b/system/Email/Email.php index 3e4584390928..5d420cc2e99c 100644 --- a/system/Email/Email.php +++ b/system/Email/Email.php @@ -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 (in_array(preg_match('/[\200-\377]/', $name), [0, false], true)) { + if (preg_match('/[\200-\377]/', $name) !== 1) { $name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"'; } else { $name = $this->prepQEncoding($name); @@ -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 (in_array(preg_match('/[\200-\377]/', $name), [0, false], true)) { + if (preg_match('/[\200-\377]/', $name) !== 1) { $name = '"' . addcslashes($name, "\0..\37\177'\"\\") . '"'; } else { $name = $this->prepQEncoding($name); diff --git a/system/Helpers/html_helper.php b/system/Helpers/html_helper.php index 736960606457..3eb55a6d5150 100644 --- a/system/Helpers/html_helper.php +++ b/system/Helpers/html_helper.php @@ -112,7 +112,7 @@ function img($src = '', bool $indexPage = false, $attributes = ''): string $img = ' $v) { - if ($k === 'src' && in_array(preg_match('#^([a-z]+:)?//#i', $v), [0, false], true)) { + if ($k === 'src' && preg_match('#^([a-z]+:)?//#i', $v) !== 1) { if ($indexPage) { $script .= 'src="' . site_url($v) . '" '; } else { @@ -252,7 +252,7 @@ function link_tag( $href = $href['href'] ?? ''; } - if (in_array(preg_match('#^([a-z]+:)?//#i', $href), [0, false], true)) { + if (preg_match('#^([a-z]+:)?//#i', $href) !== 1) { $attributes['href'] = $indexPage ? site_url($href) : slash_item('baseURL') . $href; } else { $attributes['href'] = $href; diff --git a/system/Session/Handlers/FileHandler.php b/system/Session/Handlers/FileHandler.php index e0e52442569f..6931ab1c581f 100644 --- a/system/Session/Handlers/FileHandler.php +++ b/system/Session/Handlers/FileHandler.php @@ -290,7 +290,7 @@ public function gc($max_lifetime) while (($file = readdir($directory)) !== false) { // If the filename doesn't match this pattern, it's either not a session file or is not ours - if (in_array(preg_match($pattern, $file), [0, false], true) + if (preg_match($pattern, $file) !== 1 || ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file) || ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false || $mtime > $ts diff --git a/system/Session/Session.php b/system/Session/Session.php index ca26c44df420..a9b7bd4fa5fe 100644 --- a/system/Session/Session.php +++ b/system/Session/Session.php @@ -234,7 +234,7 @@ public function start() // Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers if (isset($_COOKIE[$this->config->cookieName]) - && (! is_string($_COOKIE[$this->config->cookieName]) || in_array(preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]), [0, false], true)) + && (! is_string($_COOKIE[$this->config->cookieName]) || preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]) !== 1) ) { unset($_COOKIE[$this->config->cookieName]); } diff --git a/system/Typography/Typography.php b/system/Typography/Typography.php index be2d0b36c7da..145ff68f1193 100644 --- a/system/Typography/Typography.php +++ b/system/Typography/Typography.php @@ -171,7 +171,7 @@ public function autoTypography(string $str, bool $reduceLinebreaks = false): str } // No opening block level tag? Add it if needed. - if (in_array(preg_match('/^\s*<(?:' . $this->blockElements . ')/i', $str), [0, false], true)) { + if (preg_match('/^\s*<(?:' . $this->blockElements . ')/i', $str) !== 1) { $str = preg_replace('/^(.*?)<(' . $this->blockElements . ')/i', '

$1

<$2', $str); } From dbdb1fa7dbfad3f458f82714f32e922dd7b2a47b Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:38:10 +0700 Subject: [PATCH 13/23] refactor: use empty string check on guessExtension --- system/HTTP/Files/UploadedFile.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index 0626aeb5581f..a566fa7f67c7 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -302,7 +302,8 @@ public function getTempName(): string */ public function getExtension(): string { - return ! in_array($this->guessExtension(), ['', '0'], true) ? $this->guessExtension() : $this->getClientExtension(); + $guessExtension = $this->guessExtension(); + return $guessExtension !== '' ? $guessExtension : $this->getClientExtension(); } /** From b01dbd50a755c7da5f8caee2db665d0d4005598b Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:40:48 +0700 Subject: [PATCH 14/23] refactor: run cs fix --- system/HTTP/Files/UploadedFile.php | 1 + 1 file changed, 1 insertion(+) diff --git a/system/HTTP/Files/UploadedFile.php b/system/HTTP/Files/UploadedFile.php index a566fa7f67c7..c17a9e5af8e5 100644 --- a/system/HTTP/Files/UploadedFile.php +++ b/system/HTTP/Files/UploadedFile.php @@ -303,6 +303,7 @@ public function getTempName(): string public function getExtension(): string { $guessExtension = $this->guessExtension(); + return $guessExtension !== '' ? $guessExtension : $this->getClientExtension(); } From a1ae7156fee95279b4461628ed70ddd01973f4eb Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 10:45:41 +0700 Subject: [PATCH 15/23] refactor: more !== 1 compare on preg_match() --- system/View/Parser.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/View/Parser.php b/system/View/Parser.php index 80af795bceb8..f5ca9b56b128 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -613,7 +613,7 @@ public function shouldAddEscaping(string $key) $escape = false; } // If no `esc` filter is found, then we'll need to add one. - elseif (in_array(preg_match('/\s+esc/u', $key), [0, false], true)) { + elseif (preg_match('/\s+esc/u', $key) !== 1) { $escape = 'html'; } From 9f0f470e5557fc0be9f92dd591c99514b8a470f1 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Fri, 27 Dec 2024 22:31:05 +0700 Subject: [PATCH 16/23] use direct result of pg_last_error() --- system/Database/Postgre/Connection.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 2dc1a7c717e9..6b9853d2f1ec 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -465,7 +465,7 @@ public function error(): array return [ 'code' => '', - 'message' => ! in_array($lastError, ['', '0'], true) ? $lastError : '', + 'message' => pg_last_error($this->connID), ]; } From 88e3b06753f2f2cac802ad0214b06bd2c080a889 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 00:16:37 +0700 Subject: [PATCH 17/23] refactor: use str_contains() over strpos on Forge --- system/Database/MySQLi/Forge.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index 54c073389fd3..c47ff4ded393 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -116,11 +116,11 @@ protected function _createTableAttributes(array $attributes): string } } - if ($this->db->charset !== '' && in_array(strpos($sql, 'CHARACTER SET'), [0, false], true) && in_array(strpos($sql, 'CHARSET'), [0, false], true)) { + if ($this->db->charset !== '' && ! str_contains($sql, 'CHARACTER SET') && ! str_contains($sql, 'CHARSET')) { $sql .= ' DEFAULT CHARACTER SET = ' . $this->db->escapeString($this->db->charset); } - if ($this->db->DBCollat !== '' && in_array(strpos($sql, 'COLLATE'), [0, false], true)) { + if ($this->db->DBCollat !== '' && ! str_contains($sql, 'COLLATE')) { $sql .= ' COLLATE = ' . $this->db->escapeString($this->db->DBCollat); } From 73c0e612ec16e292d2174dcdfd2ca008581080cb Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 00:18:25 +0700 Subject: [PATCH 18/23] refactor: fix unused variable --- system/Database/Postgre/Connection.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 6b9853d2f1ec..4ce2b0763536 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -461,8 +461,6 @@ protected function _enableForeignKeyChecks() */ public function error(): array { - $lastError = pg_last_error($this->connID); - return [ 'code' => '', 'message' => pg_last_error($this->connID), From c595ebb0399e29ac581a27f11afb0aaedb146722 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 00:19:59 +0700 Subject: [PATCH 19/23] refactor: check empty string on ResponseTrait --- system/HTTP/ResponseTrait.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/system/HTTP/ResponseTrait.php b/system/HTTP/ResponseTrait.php index 02ecfb40263d..eaf60f2b38b4 100644 --- a/system/HTTP/ResponseTrait.php +++ b/system/HTTP/ResponseTrait.php @@ -569,7 +569,7 @@ public function getCookieStore() */ public function hasCookie(string $name, ?string $value = null, string $prefix = ''): bool { - $prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC + $prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC return $this->cookieStore->has($name, $prefix, $value); } @@ -589,7 +589,7 @@ public function getCookie(?string $name = null, string $prefix = '') } try { - $prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC + $prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC return $this->cookieStore->get($name, $prefix); } catch (CookieException $e) { @@ -610,7 +610,7 @@ public function deleteCookie(string $name = '', string $domain = '', string $pat return $this; } - $prefix = $prefix !== '' && $prefix !== '0' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC + $prefix = $prefix !== '' ? $prefix : Cookie::setDefaults()['prefix']; // to retain BC $prefixed = $prefix . $name; $store = $this->cookieStore; From 4c5daaf615d2eed5d0cd13da3518c8b1b1bec0fe Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 00:21:21 +0700 Subject: [PATCH 20/23] refactor: more preg_match() and empty string only check --- system/Test/CIUnitTestCase.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/Test/CIUnitTestCase.php b/system/Test/CIUnitTestCase.php index c515b7e3d3c2..467e3a61bdf7 100644 --- a/system/Test/CIUnitTestCase.php +++ b/system/Test/CIUnitTestCase.php @@ -374,7 +374,7 @@ public function assertLogContains(string $level, string $logMessage, string $mes { $this->assertTrue( TestLogger::didLog($level, $logMessage, false), - $message !== '' && $message !== '0' ? $message : sprintf( + $message !== '' ? $message : sprintf( 'Failed asserting that logs have a record of message containing "%s" with level "%s".', $logMessage, $level From 095aea9ba0a4f17fe96b0e3f53631b45de4c9927 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 00:38:17 +0700 Subject: [PATCH 21/23] refactor: compare to 0 on preg_match_all() --- system/Session/Handlers/MemcachedHandler.php | 4 ++-- system/View/Parser.php | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/system/Session/Handlers/MemcachedHandler.php b/system/Session/Handlers/MemcachedHandler.php index 193ec533539e..e651808a8ba8 100644 --- a/system/Session/Handlers/MemcachedHandler.php +++ b/system/Session/Handlers/MemcachedHandler.php @@ -93,12 +93,12 @@ public function open($path, $name): bool } if ( - in_array(preg_match_all( + preg_match_all( '#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#', $this->savePath, $matches, PREG_SET_ORDER - ), [0, false], true) + ) === 0 ) { $this->memcached = null; $this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath); diff --git a/system/View/Parser.php b/system/View/Parser.php index f5ca9b56b128..08fec93e16fc 100644 --- a/system/View/Parser.php +++ b/system/View/Parser.php @@ -691,7 +691,7 @@ protected function parsePlugins(string $template) * $matches[1] = all parameters string in opening tag * $matches[2] = content between the tags to send to the plugin. */ - if (in_array(preg_match_all($pattern, $template, $matches, PREG_SET_ORDER), [0, false], true)) { + if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER) === 0) { continue; } From db363a70b0bb5dcc9b0ce03ba0347e77b90c7a7c Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 21:46:41 +0700 Subject: [PATCH 22/23] refactor: re-run rector --- system/CLI/CLI.php | 2 +- system/Database/MigrationRunner.php | 2 +- system/Helpers/form_helper.php | 2 +- system/Router/RouteCollection.php | 4 ++-- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 185f51e3635c..8aa9854900eb 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -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(); diff --git a/system/Database/MigrationRunner.php b/system/Database/MigrationRunner.php index 4a39f13562e8..13919c785372 100644 --- a/system/Database/MigrationRunner.php +++ b/system/Database/MigrationRunner.php @@ -450,7 +450,7 @@ protected function migrationFromFile(string $path, string $namespace) $filename = basename($path, '.php'); - if (! preg_match($this->regex, $filename)) { + if (preg_match($this->regex, $filename) !== 1) { return false; } diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index c3e2c83de0a6..7e11388841f4 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -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()) && stripos($form, 'method="get"') === false) { $form .= csrf_field($csrfId ?? null); } diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 2dbaba05e4cd..13cbba449989 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1329,7 +1329,7 @@ protected function fillRouteParams(string $from, ?array $params = null): string $patterns = $matches[0]; foreach ($patterns as $index => $pattern) { - if (! preg_match('#^' . $pattern . '$#u', $params[$index])) { + if (preg_match('#^' . $pattern . '$#u', $params[$index]) !== 1) { throw RouterException::forInvalidParameterType(); } @@ -1391,7 +1391,7 @@ protected function buildReverseRoute(string $from, array $params): string // or maybe $placeholder is not a placeholder, but a regex. $pattern = $this->placeholders[$placeholderName] ?? $placeholder; - if (! preg_match('#^' . $pattern . '$#u', (string) $params[$index])) { + if (preg_match('#^' . $pattern . '$#u', (string) $params[$index]) !== 1) { throw RouterException::forInvalidParameterType(); } From 19ecff2b389f92855773ccc6fc11d02a76b3f2b8 Mon Sep 17 00:00:00 2001 From: Abdul Malik Ikhsan Date: Sat, 28 Dec 2024 21:49:11 +0700 Subject: [PATCH 23/23] refactor: preg_match_all() likely less to return false --- system/CLI/CLI.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/system/CLI/CLI.php b/system/CLI/CLI.php index 8aa9854900eb..0b5b01b179aa 100644 --- a/system/CLI/CLI.php +++ b/system/CLI/CLI.php @@ -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 === 0 || $pattern === false || $maxOptions < $maxInput) { + if ($pattern === 0 || $maxOptions < $maxInput) { static::error('Please select correctly.'); CLI::newLine();