diff --git a/system/Commands/Database/CreateDatabase.php b/system/Commands/Database/CreateDatabase.php index facd060abf6e..459b243d5632 100644 --- a/system/Commands/Database/CreateDatabase.php +++ b/system/Commands/Database/CreateDatabase.php @@ -79,7 +79,7 @@ public function run(array $params) { $name = array_shift($params); - if (empty($name)) { + if ($name === null || $name === '') { $name = CLI::prompt('Database name', null, 'required'); // @codeCoverageIgnore } diff --git a/system/Commands/Database/MigrateStatus.php b/system/Commands/Database/MigrateStatus.php index 68288353458d..7307305307c1 100644 --- a/system/Commands/Database/MigrateStatus.php +++ b/system/Commands/Database/MigrateStatus.php @@ -105,7 +105,7 @@ public function run(array $params) $migrations = $runner->findNamespaceMigrations($namespace); - if (empty($migrations)) { + if ($migrations === []) { continue; } diff --git a/system/Commands/Database/Seed.php b/system/Commands/Database/Seed.php index fc1c0f1ae62e..5a536d0f1b50 100644 --- a/system/Commands/Database/Seed.php +++ b/system/Commands/Database/Seed.php @@ -71,7 +71,7 @@ public function run(array $params) $seeder = new Seeder(new Database()); $seedName = array_shift($params); - if (empty($seedName)) { + if ($seedName === null || $seedName === '') { $seedName = CLI::prompt(lang('Migrations.migSeeder'), null, 'required'); // @codeCoverageIgnore } diff --git a/system/Config/BaseService.php b/system/Config/BaseService.php index 64b5266da041..d59332b392ef 100644 --- a/system/Config/BaseService.php +++ b/system/Config/BaseService.php @@ -276,7 +276,7 @@ protected static function getSharedInstance(string $key, ...$params) public static function autoloader(bool $getShared = true) { if ($getShared) { - if (empty(static::$instances['autoloader'])) { + if (! isset(static::$instances['autoloader'])) { static::$instances['autoloader'] = new Autoloader(); } @@ -296,7 +296,7 @@ public static function autoloader(bool $getShared = true) public static function locator(bool $getShared = true) { if ($getShared) { - if (empty(static::$instances['locator'])) { + if (! isset(static::$instances['locator'])) { $cacheEnabled = class_exists(Optimize::class) && (new Optimize())->locatorCacheEnabled; diff --git a/system/Config/DotEnv.php b/system/Config/DotEnv.php index 6778c44e0d8d..2495b6b15e42 100644 --- a/system/Config/DotEnv.php +++ b/system/Config/DotEnv.php @@ -98,11 +98,11 @@ protected function setVariable(string $name, string $value = '') putenv("{$name}={$value}"); } - if (empty($_ENV[$name])) { + if (! isset($_ENV[$name]) || in_array($_ENV[$name], ['', '0'], true)) { $_ENV[$name] = $value; } - if (empty($_SERVER[$name])) { + if (! isset($_SERVER[$name]) || in_array($_SERVER[$name], ['', '0'], true)) { $_SERVER[$name] = $value; } } diff --git a/system/Config/Services.php b/system/Config/Services.php index 35db6c57241a..b465857905a1 100644 --- a/system/Config/Services.php +++ b/system/Config/Services.php @@ -230,7 +230,7 @@ public static function email($config = null, bool $getShared = true) return static::getSharedInstance('email', $config); } - if (empty($config) || (! is_array($config) && ! $config instanceof EmailConfig)) { + if (! $config instanceof EmailConfig && (! is_array($config) || $config === [])) { $config = config(EmailConfig::class); } diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index c3ed39102ae6..17f0690d8fb9 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -306,7 +306,7 @@ class BaseBuilder */ public function __construct($tableName, ConnectionInterface $db, ?array $options = null) { - if (empty($tableName)) { + if (in_array($tableName, ['', '0', []], true)) { throw new DatabaseException('A table must be specified when creating a new Query Builder.'); } @@ -769,7 +769,7 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type $escape = $this->db->protectIdentifiers; } - $prefix = empty($this->{$qbKey}) ? $this->groupGetType('') : $this->groupGetType($type); + $prefix = $this->{$qbKey} === [] ? $this->groupGetType('') : $this->groupGetType($type); foreach ($keyValue as $k => $v) { if ($rawSqlOnly) { @@ -778,7 +778,7 @@ protected function whereHaving(string $qbKey, $key, $value = null, string $type } elseif ($v !== null) { $op = $this->getOperatorFromWhereKey($k); - if (! empty($op)) { + if ($op !== false && $op !== []) { $k = trim($k); end($op); @@ -985,7 +985,7 @@ protected function _whereIn(?string $key = null, $values = null, bool $not = fal $ok = $this->setBind($ok, $whereIn, $escape); - $prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type); + $prefix = $this->{$clause} === [] ? $this->groupGetType('') : $this->groupGetType($type); $whereIn = [ 'condition' => "{$prefix}{$key}{$not} IN :{$ok}:", @@ -1125,7 +1125,7 @@ protected function _like($field, string $match = '', string $type = 'AND ', stri $v = $match; $insensitiveSearch = false; - $prefix = empty($this->{$clause}) ? $this->groupGetType('') : $this->groupGetType($type); + $prefix = $this->{$clause} === [] ? $this->groupGetType('') : $this->groupGetType($type); if ($side === 'none') { $bind = $this->setBind($field->getBindingKey(), $v, $escape); @@ -1357,7 +1357,7 @@ protected function groupStartPrepare(string $not = '', string $type = 'AND ', st $type = $this->groupGetType($type); $this->QBWhereGroupStarted = true; - $prefix = empty($this->{$clause}) ? '' : $type; + $prefix = $this->{$clause} === [] ? '' : $type; $where = [ 'condition' => $prefix . $not . str_repeat(' ', ++$this->QBWhereGroupCount) . ' (', 'escape' => false, @@ -1626,7 +1626,7 @@ protected function compileFinalQuery(string $sql): string $query = new Query($this->db); $query->setQuery($sql, $this->binds, false); - if (! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) { + if ($this->db->swapPre !== '' && $this->db->DBPrefix !== '') { $query->swapPrefix($this->db->DBPrefix, $this->db->swapPre); } @@ -1683,7 +1683,7 @@ public function countAll(bool $reset = true) $query = $this->db->query($sql, null, false); - if (empty($query->getResult())) { + if ($query->getResult() === []) { return 0; } @@ -1709,7 +1709,7 @@ public function countAllResults(bool $reset = true) // for selecting COUNT(*) ... $orderBy = []; - if (! empty($this->QBOrderBy)) { + if (is_array($this->QBOrderBy) && $this->QBOrderBy !== []) { $orderBy = $this->QBOrderBy; $this->QBOrderBy = null; @@ -1720,7 +1720,7 @@ public function countAllResults(bool $reset = true) $this->QBLimit = false; - if ($this->QBDistinct === true || ! empty($this->QBGroupBy)) { + if ($this->QBDistinct === true || $this->QBGroupBy !== []) { // We need to backup the original SELECT in case DBPrefix is used $select = $this->QBSelect; $sql = $this->countString . $this->db->protectIdentifiers('numrows') . "\nFROM (\n" . $this->compileSelect() . "\n) CI_count_all_results"; @@ -1749,7 +1749,7 @@ public function countAllResults(bool $reset = true) $row = $result instanceof ResultInterface ? $result->getRow() : null; - if (empty($row)) { + if ($row === null) { return 0; } @@ -1813,7 +1813,7 @@ public function getWhere($where = null, ?int $limit = null, ?int $offset = 0, bo */ protected function batchExecute(string $renderMethod, int $batchSize = 100) { - if (empty($this->QBSet)) { + if ($this->QBSet === []) { if ($this->db->DBDebug) { throw new DatabaseException(trim($renderMethod, '_') . '() has no data.'); } @@ -1866,7 +1866,7 @@ protected function batchExecute(string $renderMethod, int $batchSize = 100) */ public function setData($set, ?bool $escape = null, string $alias = '') { - if (empty($set)) { + if ($set === []) { if ($this->db->DBDebug) { throw new DatabaseException('setData() has no data.'); } @@ -2073,7 +2073,7 @@ private function setAlias(string $alias): BaseBuilder */ public function updateFields($set, bool $addToDefault = false, ?array $ignore = null) { - if (! empty($set)) { + if (! in_array($set, [null, [], ''], true)) { if (! is_array($set)) { $set = explode(',', $set); } @@ -2109,13 +2109,13 @@ public function updateFields($set, bool $addToDefault = false, ?array $ignore = /** * Sets constraints for batch upsert, update * - * @param array|RawSql|string $set a string of columns, key value pairs, or RawSql + * @param array|RawSql|string|null $set A string of columns, key value pairs, or RawSql * * @return $this */ public function onConstraint($set) { - if (! empty($set)) { + if (! in_array($set, [null, [], ''], true)) { if (is_string($set)) { $set = explode(',', $set); @@ -2388,7 +2388,7 @@ protected function removeAlias(string $from): string */ protected function validateInsert(): bool { - if (empty($this->QBSet)) { + if ($this->QBSet === []) { if ($this->db->DBDebug) { throw new DatabaseException('You must use the "set" method to insert an entry.'); } @@ -2424,7 +2424,7 @@ public function replace(?array $set = null) $this->set($set); } - if (empty($this->QBSet)) { + if ($this->QBSet === []) { if ($this->db->DBDebug) { throw new DatabaseException('You must use the "set" method to update an entry.'); } @@ -2576,7 +2576,7 @@ protected function _update(string $table, array $values): string */ protected function validateUpdate(): bool { - if (empty($this->QBSet)) { + if ($this->QBSet === []) { if ($this->db->DBDebug) { throw new DatabaseException('You must use the "set" method to update an entry.'); } @@ -2827,7 +2827,7 @@ public function delete($where = '', ?int $limit = null, bool $resetData = true) $this->where($where); } - if (empty($this->QBWhere)) { + if ($this->QBWhere === []) { if ($this->db->DBDebug) { throw new DatabaseException('Deletes are not allowed unless they contain a "where" or "like" clause.'); } @@ -2846,7 +2846,7 @@ public function delete($where = '', ?int $limit = null, bool $resetData = true) $this->QBLimit = $limit; } - if (! empty($this->QBLimit)) { + if ($this->QBLimit !== false && $this->QBLimit !== 0) { if (! $this->canLimitDeletes) { throw new DatabaseException('SQLite3 does not allow LIMITs on DELETE queries.'); } @@ -3105,7 +3105,7 @@ protected function compileSelect($selectOverride = false): string } else { $sql = $this->QBDistinct ? 'SELECT DISTINCT ' : 'SELECT '; - if (empty($this->QBSelect)) { + if ($this->QBSelect === []) { $sql .= '*'; } else { // Cycle through the "select" portion of the query and prep each column name. @@ -3124,11 +3124,11 @@ protected function compileSelect($selectOverride = false): string } } - if (! empty($this->QBFrom)) { + if ($this->QBFrom !== []) { $sql .= "\nFROM " . $this->_fromTables(); } - if (! empty($this->QBJoin)) { + if ($this->QBJoin !== []) { $sql .= "\n" . implode("\n", $this->QBJoin); } @@ -3177,7 +3177,7 @@ protected function compileIgnore(string $statement) */ protected function compileWhereHaving(string $qbKey): string { - if (! empty($this->{$qbKey})) { + if ($this->{$qbKey} !== []) { foreach ($this->{$qbKey} as &$qbkey) { // Is this condition already compiled? if (is_string($qbkey)) { @@ -3266,7 +3266,7 @@ protected function compileWhereHaving(string $qbKey): string */ protected function compileGroupBy(): string { - if (! empty($this->QBGroupBy)) { + if ($this->QBGroupBy !== []) { foreach ($this->QBGroupBy as &$groupBy) { // Is it already compiled? if (is_string($groupBy)) { @@ -3453,7 +3453,7 @@ protected function resetSelect() } // Reset QBFrom part - if (! empty($this->QBFrom)) { + if ($this->QBFrom !== []) { $this->from(array_shift($this->QBFrom), true); } } diff --git a/system/Database/BaseConnection.php b/system/Database/BaseConnection.php index 17a5775d425f..f872ab2bdc06 100644 --- a/system/Database/BaseConnection.php +++ b/system/Database/BaseConnection.php @@ -566,7 +566,7 @@ public function initialize() // No connection resource? Check if there is a failover else throw an error if (! $this->connID) { // Check if there is a failover set - if (! empty($this->failover) && is_array($this->failover)) { + if (is_array($this->failover) && $this->failover !== []) { // Go over all the failovers foreach ($this->failover as $index => $failover) { $typedPropertyTypes = $this->getBuiltinPropertyTypesMap(array_keys($failover)); @@ -703,7 +703,7 @@ public function getConnection(?string $alias = null) */ public function getDatabase(): string { - return empty($this->database) ? '' : $this->database; + return is_string($this->database) ? $this->database : ''; } /** @@ -791,7 +791,7 @@ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, s { $queryClass = $queryClass !== '' && $queryClass !== '0' ? $queryClass : $this->queryClass; - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } @@ -800,7 +800,7 @@ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, s $query->setQuery($sql, $binds, $setEscapeFlags); - if (! empty($this->swapPre) && ! empty($this->DBPrefix)) { + if ($this->swapPre !== '' && $this->DBPrefix !== '') { $query->swapPrefix($this->DBPrefix, $this->swapPre); } @@ -901,7 +901,7 @@ public function query(string $sql, $binds = null, bool $setEscapeFlags = true, s */ public function simpleQuery(string $sql) { - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } @@ -1015,7 +1015,7 @@ public function transBegin(bool $testMode = false): bool return true; } - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } @@ -1119,7 +1119,7 @@ abstract protected function _transRollback(): bool; */ public function table($tableName) { - if (empty($tableName)) { + if (in_array($tableName, ['', '0', []], true)) { throw new DatabaseException('You must set the database table to be used with your query.'); } @@ -1161,7 +1161,7 @@ public function newQuery(): BaseBuilder */ public function prepare(Closure $func, array $options = []) { - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } @@ -1346,9 +1346,8 @@ private function protectDotItem(string $item, string $alias, bool $protectIdenti // one of the aliases previously identified? If so, // we have nothing more to do other than escape the item // - // NOTE: The ! empty() condition prevents this method - // from breaking when QB isn't enabled. - if (! empty($this->aliasedTables) && in_array($parts[0], $this->aliasedTables, true)) { + // $aliasedTables is empty when QB isn't enabled. + if ($this->aliasedTables !== [] && in_array($parts[0], $this->aliasedTables, true)) { if ($protectIdentifiers) { foreach ($parts as $key => $val) { if (! in_array($val, $this->reservedIdentifiers, true)) { @@ -1455,7 +1454,7 @@ private function escapeTableName(TableName $tableName): string */ public function escapeIdentifiers($item) { - if ($this->escapeChar === '' || empty($item) || in_array($item, $this->reservedIdentifiers, true)) { + if ($this->escapeChar === '' || in_array($item, ['', '0', []], true) || in_array($item, $this->reservedIdentifiers, true)) { return $item; } @@ -1737,7 +1736,7 @@ public function tableExists(string $tableName, bool $cached = true): bool $tableExists = $this->query($sql)->getResultArray() !== []; // if cache has been built already - if (! empty($this->dataCache['table_names'])) { + if (($this->dataCache['table_names'] ?? []) !== []) { $key = array_search( strtolower($tableName), array_map(strtolower(...), $this->dataCache['table_names']), @@ -1772,7 +1771,7 @@ public function getFieldNames($tableName) return $this->dataCache['field_names'][$table]; } - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } diff --git a/system/Database/BasePreparedQuery.php b/system/Database/BasePreparedQuery.php index 540e9c15161c..16b23535e031 100644 --- a/system/Database/BasePreparedQuery.php +++ b/system/Database/BasePreparedQuery.php @@ -47,7 +47,7 @@ abstract class BasePreparedQuery implements PreparedQueryInterface * * @var string */ - protected $errorString; + protected $errorString = ''; /** * Holds the prepared query object @@ -90,7 +90,7 @@ public function prepare(string $sql, array $options = [], string $queryClass = Q $query->setQuery($sql); - if (! empty($this->db->swapPre) && ! empty($this->db->DBPrefix)) { + if ($this->db->swapPre !== '' && $this->db->DBPrefix !== '') { $query->swapPrefix($this->db->DBPrefix, $this->db->swapPre); } @@ -236,7 +236,7 @@ public function getQueryString(): string */ public function hasError(): bool { - return ! empty($this->errorString); + return $this->errorString !== ''; } /** diff --git a/system/Database/BaseResult.php b/system/Database/BaseResult.php index 5bede241a59d..532549262283 100644 --- a/system/Database/BaseResult.php +++ b/system/Database/BaseResult.php @@ -268,7 +268,7 @@ public function getRow($n = 0, string $type = 'object') } // array_key_exists() instead of isset() to allow for NULL values - if (empty($this->rowData) || ! array_key_exists($n, $this->rowData)) { + if ($this->rowData === null || ! array_key_exists($n, $this->rowData)) { return null; } @@ -304,7 +304,7 @@ public function getCustomRowObject(int $n, string $className) $this->getCustomResultObject($className); } - if (empty($this->customResultObject[$className])) { + if (($this->customResultObject[$className] ?? []) === []) { return null; } diff --git a/system/Database/BaseUtils.php b/system/Database/BaseUtils.php index 938c28364444..ddea4301c556 100644 --- a/system/Database/BaseUtils.php +++ b/system/Database/BaseUtils.php @@ -152,7 +152,7 @@ public function optimizeDatabase() $res = $res->getResultArray(); // Postgre & SQLite3 returns empty array - if (empty($res)) { + if ($res === []) { $key = $tableName; } else { $res = current($res); @@ -287,7 +287,7 @@ public function backup($params = []) 'foreign_key_checks' => true, ]; - if (! empty($params)) { + if ($params !== []) { foreach (array_keys($prefs) as $key) { if (isset($params[$key])) { $prefs[$key] = $params[$key]; @@ -295,7 +295,7 @@ public function backup($params = []) } } - if (empty($prefs['tables'])) { + if ($prefs['tables'] === [] || $prefs['tables'] === '') { $prefs['tables'] = $this->db->listTables(); } diff --git a/system/Database/Database.php b/system/Database/Database.php index 9598242f01bb..2955ce0d37c5 100644 --- a/system/Database/Database.php +++ b/system/Database/Database.php @@ -48,11 +48,11 @@ public function load(array $params = [], string $alias = '') throw new InvalidArgumentException('You must supply the parameter: alias.'); } - if (! empty($params['DSN']) && str_contains($params['DSN'], '://')) { + if (($params['DSN'] ?? '') !== '' && str_contains($params['DSN'], '://')) { $params = $this->parseDSN($params); } - if (empty($params['DBDriver'])) { + if (($params['DBDriver'] ?? '') === '') { throw new InvalidArgumentException('You have not selected a database type to connect to.'); } diff --git a/system/Database/Forge.php b/system/Database/Forge.php index 9291683acb5f..52ae71464573 100644 --- a/system/Database/Forge.php +++ b/system/Database/Forge.php @@ -246,7 +246,7 @@ public function createDatabase(string $dbName, bool $ifNotExists = false): bool // @codeCoverageIgnoreEnd } - if (! empty($this->db->dataCache['db_names'])) { + if (($this->db->dataCache['db_names'] ?? []) !== []) { $this->db->dataCache['db_names'][] = $dbName; } @@ -303,7 +303,7 @@ public function dropDatabase(string $dbName): bool return false; } - if (! empty($this->db->dataCache['db_names'])) { + if (($this->db->dataCache['db_names'] ?? []) !== []) { $key = array_search( strtolower($dbName), array_map(strtolower(...), $this->db->dataCache['db_names']), @@ -664,7 +664,7 @@ public function dropTable(string $tableName, bool $ifExists = false, bool $casca $this->db->enableForeignKeyChecks(); - if ($query && ! empty($this->db->dataCache['table_names'])) { + if ($query && ($this->db->dataCache['table_names'] ?? []) !== []) { $key = array_search( strtolower($this->db->DBPrefix . $tableName), array_map(strtolower(...), $this->db->dataCache['table_names']), @@ -726,7 +726,7 @@ public function renameTable(string $tableName, string $newTableName) $this->db->escapeIdentifiers($this->db->DBPrefix . $newTableName), )); - if ($result && ! empty($this->db->dataCache['table_names'])) { + if ($result && ($this->db->dataCache['table_names'] ?? []) !== []) { $key = array_search( strtolower($this->db->DBPrefix . $tableName), array_map(strtolower(...), $this->db->dataCache['table_names']), @@ -894,7 +894,7 @@ protected function _processFields(bool $createTable = false): array $attributes = array_change_key_case($attributes, CASE_UPPER); - if ($createTable && empty($attributes['TYPE'])) { + if ($createTable && ($attributes['TYPE'] ?? '') === '') { continue; } @@ -933,7 +933,7 @@ protected function _processFields(bool $createTable = false): array $nullString = ' ' . $this->null; if ($attributes['NULL'] === true) { - $field['null'] = empty($this->null) ? '' : $nullString; + $field['null'] = $this->null === '' ? '' : $nullString; } elseif ($attributes['NULL'] === $nullString) { $field['null'] = $nullString; } elseif ($attributes['NULL'] === '') { @@ -952,7 +952,7 @@ protected function _processFields(bool $createTable = false): array $field['comment'] = $this->db->escape($attributes['COMMENT']); } - if (isset($attributes['TYPE']) && ! empty($attributes['CONSTRAINT'])) { + if (isset($attributes['TYPE'], $attributes['CONSTRAINT']) && ! in_array($attributes['CONSTRAINT'], ['', '0', 0, []], true)) { if (is_array($attributes['CONSTRAINT'])) { $attributes['CONSTRAINT'] = $this->db->escape($attributes['CONSTRAINT']); $attributes['CONSTRAINT'] = implode(',', $attributes['CONSTRAINT']); @@ -1005,7 +1005,7 @@ protected function _attributeType(array &$attributes) */ protected function _attributeUnsigned(array &$attributes, array &$field) { - if (empty($attributes['UNSIGNED']) || $attributes['UNSIGNED'] !== true) { + if (($attributes['UNSIGNED'] ?? false) !== true) { return; } @@ -1044,11 +1044,11 @@ protected function _attributeDefault(array &$attributes, array &$field) if (array_key_exists('DEFAULT', $attributes)) { if ($attributes['DEFAULT'] === null) { - $field['default'] = empty($this->null) ? '' : $this->default . $this->null; + $field['default'] = $this->null === '' ? '' : $this->default . $this->null; // Override the NULL attribute if that's our default $attributes['NULL'] = true; - $field['null'] = empty($this->null) ? '' : ' ' . $this->null; + $field['null'] = $this->null === '' ? '' : ' ' . $this->null; } elseif ($attributes['DEFAULT'] instanceof RawSql) { $field['default'] = $this->default . $attributes['DEFAULT']; } else { @@ -1062,7 +1062,7 @@ protected function _attributeDefault(array &$attributes, array &$field) */ protected function _attributeUnique(array &$attributes, array &$field) { - if (! empty($attributes['UNIQUE']) && $attributes['UNIQUE'] === true) { + if (($attributes['UNIQUE'] ?? false) === true) { $field['unique'] = ' UNIQUE'; } } @@ -1072,7 +1072,7 @@ protected function _attributeUnique(array &$attributes, array &$field) */ protected function _attributeAutoIncrement(array &$attributes, array &$field) { - if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true + if (($attributes['AUTO_INCREMENT'] ?? false) === true && str_contains(strtolower($field['type']), 'int') ) { $field['auto_increment'] = ' AUTO_INCREMENT'; diff --git a/system/Database/MigrationRunner.php b/system/Database/MigrationRunner.php index df5ee049f0b7..809fd84a718d 100644 --- a/system/Database/MigrationRunner.php +++ b/system/Database/MigrationRunner.php @@ -116,7 +116,7 @@ class MigrationRunner /** * The full path to locate migration files. * - * @var string + * @var string|null */ protected $path; @@ -471,7 +471,7 @@ public function findNamespaceMigrations(string $namespace): array $migrations = []; $locator = service('locator', true); - if (! empty($this->path)) { + if ($this->path !== null && $this->path !== '') { helper('filesystem'); $dir = rtrim($this->path, DIRECTORY_SEPARATOR) . '/'; $files = get_filenames($dir, true, false, false); @@ -480,7 +480,7 @@ public function findNamespaceMigrations(string $namespace): array } foreach ($files as $file) { - $file = empty($this->path) ? $file : $this->path . str_replace($this->path, '', $file); + $file = $this->path === null || $this->path === '' ? $file : $this->path . str_replace($this->path, '', $file); if ($migration = $this->migrationFromFile($file, $namespace)) { $migrations[] = $migration; @@ -712,7 +712,7 @@ public function getHistory(string $group = 'default'): array $query = $builder->orderBy('id', 'ASC')->get(); - return empty($query) ? [] : $query->getResultObject(); + return $query === false ? [] : $query->getResultObject(); } /** @@ -729,7 +729,7 @@ public function getBatchHistory(int $batch, $order = 'asc'): array ->orderBy('id', $order) ->get(); - return empty($query) ? [] : $query->getResultObject(); + return $query === false ? [] : $query->getResultObject(); } /** diff --git a/system/Database/MySQLi/Connection.php b/system/Database/MySQLi/Connection.php index 116acb7eaf9e..5a6daa5a692e 100644 --- a/system/Database/MySQLi/Connection.php +++ b/system/Database/MySQLi/Connection.php @@ -108,7 +108,7 @@ public function connect(bool $persistent = false) $socket = $this->hostname; } else { $hostname = $persistent ? 'p:' . $this->hostname : $this->hostname; - $port = empty($this->port) ? null : $this->port; + $port = $this->port === '' ? null : $this->port; $socket = ''; } @@ -147,19 +147,19 @@ public function connect(bool $persistent = false) if (is_array($this->encrypt)) { $ssl = []; - if (! empty($this->encrypt['ssl_key'])) { + if (($this->encrypt['ssl_key'] ?? '') !== '') { $ssl['key'] = $this->encrypt['ssl_key']; } - if (! empty($this->encrypt['ssl_cert'])) { + if (($this->encrypt['ssl_cert'] ?? '') !== '') { $ssl['cert'] = $this->encrypt['ssl_cert']; } - if (! empty($this->encrypt['ssl_ca'])) { + if (($this->encrypt['ssl_ca'] ?? '') !== '') { $ssl['ca'] = $this->encrypt['ssl_ca']; } - if (! empty($this->encrypt['ssl_capath'])) { + if (($this->encrypt['ssl_capath'] ?? '') !== '') { $ssl['capath'] = $this->encrypt['ssl_capath']; } - if (! empty($this->encrypt['ssl_cipher'])) { + if (($this->encrypt['ssl_cipher'] ?? '') !== '') { $ssl['cipher'] = $this->encrypt['ssl_cipher']; } @@ -253,7 +253,7 @@ public function setDatabase(string $databaseName): bool $databaseName = $this->database; } - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } @@ -275,7 +275,7 @@ public function getVersion(): string return $this->dataCache['version']; } - if (empty($this->mysqli)) { + if (! $this->mysqli instanceof mysqli) { $this->initialize(); } @@ -473,7 +473,7 @@ protected function _indexData(string $table): array $keys = []; foreach ($indexes as $index) { - if (empty($keys[$index['Key_name']])) { + if (! isset($keys[$index['Key_name']])) { $keys[$index['Key_name']] = new stdClass(); $keys[$index['Key_name']]->name = $index['Key_name']; @@ -577,7 +577,7 @@ protected function _enableForeignKeyChecks() */ public function error(): array { - if (! empty($this->mysqli->connect_errno)) { + if ($this->mysqli instanceof mysqli && $this->mysqli->connect_errno !== 0) { return [ 'code' => $this->mysqli->connect_errno, 'message' => $this->mysqli->connect_error, diff --git a/system/Database/MySQLi/Forge.php b/system/Database/MySQLi/Forge.php index 9482f7e2329a..418cc08580ae 100644 --- a/system/Database/MySQLi/Forge.php +++ b/system/Database/MySQLi/Forge.php @@ -152,7 +152,7 @@ protected function _alterTable(string $alterType, string $table, $processedField if ($alterType === 'ADD') { $processedFields[$i]['_literal'] = "\n\tADD "; } else { - $processedFields[$i]['_literal'] = empty($field['new_name']) ? "\n\tMODIFY " : "\n\tCHANGE "; + $processedFields[$i]['_literal'] = ($field['new_name'] ?? '') === '' ? "\n\tMODIFY " : "\n\tCHANGE "; } $processedFields[$i] = $processedFields[$i]['_literal'] . $this->_processColumn($processedFields[$i]); @@ -169,19 +169,19 @@ protected function _processColumn(array $processedField): string { $extraClause = isset($processedField['after']) ? ' AFTER ' . $this->db->escapeIdentifiers($processedField['after']) : ''; - if (empty($extraClause) && isset($processedField['first']) && $processedField['first'] === true) { + if ($extraClause === '' && isset($processedField['first']) && $processedField['first'] === true) { $extraClause = ' FIRST'; } return $this->db->escapeIdentifiers($processedField['name']) - . (empty($processedField['new_name']) ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name'])) + . (($processedField['new_name'] ?? '') === '' ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name'])) . ' ' . $processedField['type'] . $processedField['length'] . $processedField['unsigned'] . $processedField['null'] . $processedField['default'] . $processedField['auto_increment'] . $processedField['unique'] - . (empty($processedField['comment']) ? '' : ' COMMENT ' . $processedField['comment']) + . (($processedField['comment'] ?? '') === '' ? '' : ' COMMENT ' . $processedField['comment']) . $extraClause; } diff --git a/system/Database/MySQLi/Result.php b/system/Database/MySQLi/Result.php index 873bbd08b9d9..05d07bb69078 100644 --- a/system/Database/MySQLi/Result.php +++ b/system/Database/MySQLi/Result.php @@ -150,7 +150,9 @@ protected function fetchAssoc() protected function fetchObject(string $className = 'stdClass') { if (is_subclass_of($className, Entity::class)) { - return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data); + $data = $this->fetchAssoc(); + + return in_array($data, [null, false, []], true) ? false : (new $className())->injectRawData($data); } return $this->resultID->fetch_object($className); diff --git a/system/Database/OCI8/Builder.php b/system/Database/OCI8/Builder.php index d1abead5060a..eb6f1ca88855 100644 --- a/system/Database/OCI8/Builder.php +++ b/system/Database/OCI8/Builder.php @@ -206,7 +206,7 @@ protected function _limit(string $sql, bool $offsetIgnore = false): string $offset = (int) ($offsetIgnore === false ? $this->QBOffset : 0); // OFFSET-FETCH can be used only with the ORDER BY clause - if (empty($this->QBOrderBy)) { + if (! is_array($this->QBOrderBy) || $this->QBOrderBy === []) { $sql .= ' ORDER BY 1'; } @@ -316,7 +316,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri if ($sql === '') { $constraints = $this->QBOptions['constraints'] ?? []; - if (empty($constraints)) { + if ($constraints === []) { $fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys); $uniqueIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { @@ -334,7 +334,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? []; } - if (empty($constraints)) { + if ($constraints === []) { if ($this->db->DBDebug) { throw new DatabaseException('No constraint found for upsert.'); } diff --git a/system/Database/OCI8/Connection.php b/system/Database/OCI8/Connection.php index dc884588a251..12fa3b4d3df6 100644 --- a/system/Database/OCI8/Connection.php +++ b/system/Database/OCI8/Connection.php @@ -628,7 +628,7 @@ public function error(): array public function insertID(): int { - if (empty($this->lastInsertedTableName)) { + if ($this->lastInsertedTableName === null || $this->lastInsertedTableName === '') { return 0; } @@ -764,7 +764,7 @@ protected function _transRollback(): bool */ public function getDatabase(): string { - if (! empty($this->database)) { + if (is_string($this->database) && $this->database !== '') { return $this->database; } diff --git a/system/Database/OCI8/Forge.php b/system/Database/OCI8/Forge.php index 8f71169115ce..e9dfb06885df 100644 --- a/system/Database/OCI8/Forge.php +++ b/system/Database/OCI8/Forge.php @@ -149,13 +149,13 @@ protected function _alterTable(string $alterType, string $table, $processedField } else { $processedFields[$i]['_literal'] = "\n\t" . $this->_processColumn($processedFields[$i]); - if (! empty($processedFields[$i]['comment'])) { + if (($processedFields[$i]['comment'] ?? '') !== '') { $sqls[] = 'COMMENT ON COLUMN ' . $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($processedFields[$i]['name']) . ' IS ' . $processedFields[$i]['comment']; } - if ($alterType === 'MODIFY' && ! empty($processedFields[$i]['new_name'])) { + if ($alterType === 'MODIFY' && ($processedFields[$i]['new_name'] ?? '') !== '') { $sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($processedFields[$i]['name']) . ' TO ' . $this->db->escapeIdentifiers($processedFields[$i]['new_name']); } @@ -182,7 +182,7 @@ protected function _alterTable(string $alterType, string $table, $processedField */ protected function _attributeAutoIncrement(array &$attributes, array &$field) { - if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true + if (($attributes['AUTO_INCREMENT'] ?? false) === true && str_contains(strtolower($field['type']), 'number') && version_compare($this->db->getVersion(), '12.1', '>=') ) { diff --git a/system/Database/Postgre/Builder.php b/system/Database/Postgre/Builder.php index 68cd00fb6246..10b42b9b3b7c 100644 --- a/system/Database/Postgre/Builder.php +++ b/system/Database/Postgre/Builder.php @@ -54,7 +54,7 @@ protected function compileIgnore(string $statement) { $sql = parent::compileIgnore($statement); - if (! empty($sql)) { + if ($sql !== '') { $sql = ' ' . trim($sql); } @@ -171,9 +171,9 @@ public function replace(?array $set = null) $builder = $this->db->table($table); $exists = $builder->where($key, $value, true)->get()->getFirstRow(); - if (empty($exists) && $this->testMode) { + if ($exists === null && $this->testMode) { $result = $this->getCompiledInsert(); - } elseif (empty($exists)) { + } elseif ($exists === null) { $result = $builder->insert($set); } elseif ($this->testMode) { $result = $this->where($key, $value, true)->getCompiledUpdate(); @@ -233,7 +233,7 @@ protected function _insertBatch(string $table, array $keys, array $values): stri */ public function delete($where = '', ?int $limit = null, bool $resetData = true) { - if ($limit !== null && $limit !== 0 || ! empty($this->QBLimit)) { + if ($limit !== null && $limit !== 0 || ($this->QBLimit !== false && $this->QBLimit !== 0)) { throw new DatabaseException('PostgreSQL does not allow LIMITs on DELETE queries.'); } @@ -255,7 +255,7 @@ protected function _limit(string $sql, bool $offsetIgnore = false): string */ protected function _update(string $table, array $values): string { - if (! empty($this->QBLimit)) { + if ($this->QBLimit !== false && $this->QBLimit !== 0) { throw new DatabaseException('Postgres does not support LIMITs with UPDATE queries.'); } @@ -464,7 +464,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->QBOptions['constraints'] ?? []; - if (empty($constraints)) { + if ($constraints === []) { $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { $hasAllFields = count(array_intersect($index->fields, $fieldNames)) === count($index->fields); @@ -479,7 +479,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? []; } - if (empty($constraints)) { + if ($constraints === []) { if ($this->db->DBDebug) { throw new DatabaseException('No constraint found for upsert.'); } diff --git a/system/Database/Postgre/Connection.php b/system/Database/Postgre/Connection.php index 4c3358a4b470..2326eb06ac3b 100644 --- a/system/Database/Postgre/Connection.php +++ b/system/Database/Postgre/Connection.php @@ -63,7 +63,7 @@ class Connection extends BaseConnection */ public function connect(bool $persistent = false) { - if (empty($this->DSN)) { + if ($this->DSN === null || $this->DSN === '') { $this->buildDSN(); } @@ -88,7 +88,7 @@ public function connect(bool $persistent = false) throw new DatabaseException($error); } - if (! empty($this->schema)) { + if ($this->schema !== '') { $this->simpleQuery("SET search_path TO {$this->schema},public"); } diff --git a/system/Database/Postgre/Forge.php b/system/Database/Postgre/Forge.php index d8e7d5886604..fdf25aa2f9ca 100644 --- a/system/Database/Postgre/Forge.php +++ b/system/Database/Postgre/Forge.php @@ -107,7 +107,7 @@ protected function _alterTable(string $alterType, string $table, $processedField . " TYPE {$field['type']}{$field['length']}"; } - if (! empty($field['default'])) { + if (($field['default'] ?? '') !== '') { $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name']) . " SET {$field['default']}"; } @@ -119,12 +119,12 @@ protected function _alterTable(string $alterType, string $table, $processedField $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name']) . ($nullable ? ' DROP' : ' SET') . ' NOT NULL'; - if (! empty($field['new_name'])) { + if (($field['new_name'] ?? '') !== '') { $sqls[] = $sql . ' RENAME COLUMN ' . $this->db->escapeIdentifiers($field['name']) . ' TO ' . $this->db->escapeIdentifiers($field['new_name']); } - if (! empty($field['comment'])) { + if (($field['comment'] ?? '') !== '') { $sqls[] = 'COMMENT ON COLUMN' . $this->db->escapeIdentifiers($table) . '.' . $this->db->escapeIdentifiers($field['name']) . " IS {$field['comment']}"; @@ -186,7 +186,7 @@ protected function _attributeType(array &$attributes) */ protected function _attributeAutoIncrement(array &$attributes, array &$field) { - if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true) { + if (($attributes['AUTO_INCREMENT'] ?? false) === true) { $field['type'] = $field['type'] === 'NUMERIC' || $field['type'] === 'BIGINT' ? 'BIGSERIAL' : 'SERIAL'; } } diff --git a/system/Database/Postgre/Result.php b/system/Database/Postgre/Result.php index e5d78c519c17..fee628296173 100644 --- a/system/Database/Postgre/Result.php +++ b/system/Database/Postgre/Result.php @@ -116,7 +116,9 @@ protected function fetchAssoc() protected function fetchObject(string $className = 'stdClass') { if (is_subclass_of($className, Entity::class)) { - return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data); + $data = $this->fetchAssoc(); + + return $data === false || $data === [] ? false : (new $className())->injectRawData($data); } return pg_fetch_object($this->resultID, null, $className); diff --git a/system/Database/Query.php b/system/Database/Query.php index 8040f54b666c..dbefaff6a09d 100644 --- a/system/Database/Query.php +++ b/system/Database/Query.php @@ -85,7 +85,7 @@ class Query implements QueryInterface, Stringable * * @var string */ - protected $errorString; + protected $errorString = ''; /** * Pointer to database connection. @@ -148,7 +148,7 @@ public function setBinds(array $binds, bool $setEscape = true) public function getQuery(): string { - if (empty($this->finalQueryString)) { + if (! isset($this->finalQueryString) || $this->finalQueryString === '') { $this->compileBinds(); } @@ -197,7 +197,7 @@ public function setError(int $code, string $error): self public function hasError(): bool { - return ! empty($this->errorString); + return $this->errorString !== ''; } public function getErrorCode(): int @@ -246,7 +246,7 @@ protected function compileBinds() $sql = $this->swappedQueryString ?? $this->originalQueryString; $binds = $this->binds; - if (empty($binds)) { + if ($binds === []) { $this->finalQueryString = $sql; return; diff --git a/system/Database/SQLSRV/Builder.php b/system/Database/SQLSRV/Builder.php index 486b30c3a6b9..f279ef750324 100644 --- a/system/Database/SQLSRV/Builder.php +++ b/system/Database/SQLSRV/Builder.php @@ -224,7 +224,7 @@ protected function _update(string $table, array $values): string $fullTableName = $this->getFullName($table); - $statement = sprintf('UPDATE %s%s SET ', empty($this->QBLimit) ? '' : 'TOP(' . $this->QBLimit . ') ', $fullTableName); + $statement = sprintf('UPDATE %s%s SET ', $this->QBLimit === false || $this->QBLimit === 0 ? '' : 'TOP(' . $this->QBLimit . ') ', $fullTableName); $statement .= implode(', ', $valstr) . $this->compileWhereHaving('QBWhere') @@ -344,7 +344,7 @@ protected function _limit(string $sql, bool $offsetIgnore = false): string return "SELECT * \nFROM " . $this->_fromTables() . ' WHERE 1=0 '; } - if (empty($this->QBOrderBy)) { + if (! is_array($this->QBOrderBy) || $this->QBOrderBy === []) { $sql .= ' ORDER BY (SELECT NULL) '; } @@ -514,7 +514,7 @@ public function countAll(bool $reset = true) } $query = $this->db->query($sql, null, false); - if (empty($query->getResult())) { + if ($query->getResult() === []) { return 0; } @@ -532,7 +532,7 @@ public function countAll(bool $reset = true) */ protected function _delete(string $table): string { - return 'DELETE' . (empty($this->QBLimit) ? '' : ' TOP (' . $this->QBLimit . ') ') . ' FROM ' . $this->getFullName($table) . $this->compileWhereHaving('QBWhere'); + return 'DELETE' . ($this->QBLimit === false || $this->QBLimit === 0 ? '' : ' TOP (' . $this->QBLimit . ') ') . ' FROM ' . $this->getFullName($table) . $this->compileWhereHaving('QBWhere'); } /** @@ -589,13 +589,13 @@ protected function compileSelect($selectOverride = false): string $sql = $this->QBDistinct ? 'SELECT DISTINCT ' : 'SELECT '; // SQL Server can't work with select * if group by is specified - if (empty($this->QBSelect) && $this->QBGroupBy !== [] && is_array($this->QBGroupBy)) { + if ($this->QBSelect === [] && $this->QBGroupBy !== [] && is_array($this->QBGroupBy)) { foreach ($this->QBGroupBy as $field) { $this->QBSelect[] = is_array($field) ? $field['field'] : $field; } } - if (empty($this->QBSelect)) { + if ($this->QBSelect === []) { $sql .= '*'; } else { // Cycle through the "select" portion of the query and prep each column name. @@ -616,7 +616,7 @@ protected function compileSelect($selectOverride = false): string } // Write the "JOIN" portion of the query - if (! empty($this->QBJoin)) { + if ($this->QBJoin !== []) { $sql .= "\n" . implode("\n", $this->QBJoin); } @@ -698,7 +698,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $fieldNames = array_map(static fn ($columnName): string => trim($columnName, '"'), $keys); - if (empty($constraints)) { + if ($constraints === []) { $tableIndexes = $this->db->getIndexData($table); $uniqueIndexes = array_filter($tableIndexes, static function ($index) use ($fieldNames): bool { @@ -725,7 +725,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? []; } - if (empty($constraints)) { + if ($constraints === []) { if ($this->db->DBDebug) { throw new DatabaseException('No constraint found for upsert.'); } diff --git a/system/Database/SQLSRV/Connection.php b/system/Database/SQLSRV/Connection.php index 970c582f60ed..ce1a210341d3 100644 --- a/system/Database/SQLSRV/Connection.php +++ b/system/Database/SQLSRV/Connection.php @@ -109,8 +109,8 @@ public function connect(bool $persistent = false) $charset = in_array(strtolower($this->charset), ['utf-8', 'utf8'], true) ? 'UTF-8' : SQLSRV_ENC_CHAR; $connection = [ - 'UID' => empty($this->username) ? '' : $this->username, - 'PWD' => empty($this->password) ? '' : $this->password, + 'UID' => is_string($this->username) ? $this->username : '', + 'PWD' => is_string($this->password) ? $this->password : '', 'Database' => $this->database, 'ConnectionPooling' => $persistent ? 1 : 0, 'CharacterSet' => $charset, @@ -120,7 +120,7 @@ public function connect(bool $persistent = false) // If the username and password are both empty, assume this is a // 'Windows Authentication Mode' connection. - if (empty($connection['UID']) && empty($connection['PWD'])) { + if ($connection['UID'] === '' && $connection['PWD'] === '') { unset($connection['UID'], $connection['PWD']); } @@ -136,7 +136,7 @@ public function connect(bool $persistent = false) $query = $this->query('SELECT CASE WHEN (@@OPTIONS | 256) = @@OPTIONS THEN 1 ELSE 0 END AS qi'); $query = $query->getResultObject(); - $this->_quoted_identifier = empty($query) ? false : (bool) $query[0]->qi; + $this->_quoted_identifier = $query === [] ? false : (bool) $query[0]->qi; $this->escapeChar = ($this->_quoted_identifier) ? '"' : ['[', ']']; return $this->connID; @@ -493,7 +493,7 @@ public function setDatabase(?string $databaseName = null) $databaseName = $this->database; } - if (empty($this->connID)) { + if ($this->connID === false) { $this->initialize(); } diff --git a/system/Database/SQLSRV/Forge.php b/system/Database/SQLSRV/Forge.php index 64a4ffaf6d35..f9f5b973a455 100644 --- a/system/Database/SQLSRV/Forge.php +++ b/system/Database/SQLSRV/Forge.php @@ -271,7 +271,7 @@ protected function _alterTable(string $alterType, string $table, $processedField . " {$field['type']}{$field['length']}"; } - if (! empty($field['default'])) { + if (($field['default'] ?? '') !== '') { $fullTable = $this->db->escapeIdentifiers($this->db->schema) . '.' . $this->db->escapeIdentifiers($table); $colName = $field['name']; // bare, for sys.columns lookup @@ -302,7 +302,7 @@ protected function _alterTable(string $alterType, string $table, $processedField $sqls[] = $sql . ' ALTER COLUMN ' . $this->db->escapeIdentifiers($field['name']) . " {$field['type']}{$field['length']} " . ($nullable ? '' : 'NOT') . ' NULL'; - if (! empty($field['comment'])) { + if (($field['comment'] ?? '') !== '') { $sqls[] = 'EXEC sys.sp_addextendedproperty ' . "@name=N'Caption', @value=N'" . $field['comment'] . "' , " . "@level0type=N'SCHEMA',@level0name=N'" . $this->db->schema . "', " @@ -310,7 +310,7 @@ protected function _alterTable(string $alterType, string $table, $processedField . "@level2type=N'COLUMN',@level2name=N'" . $this->db->escapeIdentifiers($field['name']) . "'"; } - if (! empty($field['new_name'])) { + if (($field['new_name'] ?? '') !== '') { $sqls[] = "EXEC sp_rename '[" . $this->db->schema . '].[' . $table . '].[' . $field['name'] . "]' , '" . $field['new_name'] . "', 'COLUMN';"; } } @@ -382,7 +382,7 @@ protected function _processIndexes(string $table, bool $asQuery = false): array protected function _processColumn(array $processedField): string { return $this->db->escapeIdentifiers($processedField['name']) - . (empty($processedField['new_name']) ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name'])) + . (($processedField['new_name'] ?? '') === '' ? '' : ' ' . $this->db->escapeIdentifiers($processedField['new_name'])) . ' ' . $processedField['type'] . ($processedField['type'] === 'text' ? '' : $processedField['length']) . $processedField['default'] . $processedField['null'] @@ -449,7 +449,7 @@ protected function _attributeType(array &$attributes) */ protected function _attributeAutoIncrement(array &$attributes, array &$field) { - if (! empty($attributes['AUTO_INCREMENT']) && $attributes['AUTO_INCREMENT'] === true && str_contains(strtolower($field['type']), strtolower('INT'))) { + if (($attributes['AUTO_INCREMENT'] ?? false) === true && str_contains(strtolower($field['type']), strtolower('INT'))) { $field['auto_increment'] = ' IDENTITY(1,1)'; } } diff --git a/system/Database/SQLSRV/Result.php b/system/Database/SQLSRV/Result.php index 4d9b836fdda0..27e3ee1e5256 100644 --- a/system/Database/SQLSRV/Result.php +++ b/system/Database/SQLSRV/Result.php @@ -156,7 +156,9 @@ protected function fetchAssoc() protected function fetchObject(string $className = 'stdClass') { if (is_subclass_of($className, Entity::class)) { - return empty($data = $this->fetchAssoc()) ? false : (new $className())->injectRawData($data); + $data = $this->fetchAssoc(); + + return in_array($data, [null, false, []], true) ? false : (new $className())->injectRawData($data); } return sqlsrv_fetch_object($this->resultID, $className); diff --git a/system/Database/SQLite3/Builder.php b/system/Database/SQLite3/Builder.php index 4f8dff97a0ea..68b62a219230 100644 --- a/system/Database/SQLite3/Builder.php +++ b/system/Database/SQLite3/Builder.php @@ -142,7 +142,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri if ($sql === '') { $constraints = $this->QBOptions['constraints'] ?? []; - if (empty($constraints)) { + if ($constraints === []) { $fieldNames = array_map(static fn ($columnName): string => trim($columnName, '`'), $keys); $allIndexes = array_filter($this->db->getIndexData($table), static function ($index) use ($fieldNames): bool { @@ -159,7 +159,7 @@ protected function _upsertBatch(string $table, array $keys, array $values): stri $constraints = $this->onConstraint($constraints)->QBOptions['constraints'] ?? []; } - if (empty($constraints)) { + if ($constraints === []) { if ($this->db->DBDebug) { throw new DatabaseException('No constraint found for upsert.'); } diff --git a/system/Database/SQLite3/Connection.php b/system/Database/SQLite3/Connection.php index 268ceaa7bea2..a78fca8c8b65 100644 --- a/system/Database/SQLite3/Connection.php +++ b/system/Database/SQLite3/Connection.php @@ -295,7 +295,7 @@ protected function _fieldData(string $table): array $query = $query->getResultObject(); - if (empty($query)) { + if ($query === []) { return []; } diff --git a/system/Database/SQLite3/Forge.php b/system/Database/SQLite3/Forge.php index 2bb9386f6c9e..ed5aee740895 100644 --- a/system/Database/SQLite3/Forge.php +++ b/system/Database/SQLite3/Forge.php @@ -100,7 +100,7 @@ public function dropDatabase(string $dbName): bool return false; } - if (! empty($this->db->dataCache['db_names'])) { + if (($this->db->dataCache['db_names'] ?? []) !== []) { $key = array_search(strtolower($dbName), array_map(strtolower(...), $this->db->dataCache['db_names']), true); if ($key !== false) { unset($this->db->dataCache['db_names'][$key]); @@ -222,8 +222,7 @@ protected function _attributeType(array &$attributes) protected function _attributeAutoIncrement(array &$attributes, array &$field) { if ( - ! empty($attributes['AUTO_INCREMENT']) - && $attributes['AUTO_INCREMENT'] === true + ($attributes['AUTO_INCREMENT'] ?? false) === true && str_contains(strtolower($field['type']), 'int') ) { $field['type'] = 'INTEGER PRIMARY KEY'; diff --git a/system/Database/SQLite3/Table.php b/system/Database/SQLite3/Table.php index ea84e0011e3f..48e081ed906b 100644 --- a/system/Database/SQLite3/Table.php +++ b/system/Database/SQLite3/Table.php @@ -96,7 +96,7 @@ public function fromTable(string $table) $prefix = $this->db->DBPrefix; - if (! empty($prefix) && str_starts_with($table, $prefix)) { + if ($prefix !== '' && str_starts_with($table, $prefix)) { $table = substr($table, strlen($prefix)); } @@ -217,7 +217,7 @@ public function dropPrimaryKey(): Table */ public function dropForeignKey(string $foreignName) { - if (empty($this->foreignKeys)) { + if ($this->foreignKeys === []) { return $this; } diff --git a/system/Debug/Timer.php b/system/Debug/Timer.php index 98b1299a89f7..45be554ea7ce 100644 --- a/system/Debug/Timer.php +++ b/system/Debug/Timer.php @@ -46,7 +46,7 @@ class Timer public function start(string $name, ?float $time = null) { $this->timers[strtolower($name)] = [ - 'start' => empty($time) ? microtime(true) : $time, + 'start' => $time === null || $time === 0.0 ? microtime(true) : $time, 'end' => null, ]; @@ -67,7 +67,7 @@ public function stop(string $name) { $name = strtolower($name); - if (empty($this->timers[$name])) { + if (! isset($this->timers[$name])) { throw new RuntimeException('Cannot stop timer: invalid name given.'); } @@ -90,13 +90,13 @@ public function getElapsedTime(string $name, int $decimals = 4) { $name = strtolower($name); - if (empty($this->timers[$name])) { + if (! isset($this->timers[$name])) { return null; } $timer = $this->timers[$name]; - if (empty($timer['end'])) { + if ($timer['end'] === null) { $timer['end'] = microtime(true); } @@ -113,7 +113,7 @@ public function getTimers(int $decimals = 4): array $timers = $this->timers; foreach ($timers as &$timer) { - if (empty($timer['end'])) { + if ($timer['end'] === null) { $timer['end'] = microtime(true); } diff --git a/system/Debug/Toolbar.php b/system/Debug/Toolbar.php index f5885aa0555c..311a41a2bf9d 100644 --- a/system/Debug/Toolbar.php +++ b/system/Debug/Toolbar.php @@ -210,8 +210,8 @@ protected function renderTimelineRecursive(array $rows, float $startTime, int $s $output = ''; foreach ($rows as $row) { - $hasChildren = isset($row['children']) && ! empty($row['children']); - $isQuery = isset($row['query']) && ! empty($row['query']); + $hasChildren = ($row['children'] ?? []) !== []; + $isQuery = ($row['query'] ?? '') !== ''; // Open controller timeline by default $open = $row['name'] === 'Controller'; diff --git a/system/Email/Email.php b/system/Email/Email.php index 4b3e94dfb38b..71c68d9e2841 100644 --- a/system/Email/Email.php +++ b/system/Email/Email.php @@ -693,7 +693,7 @@ public function attach($file, $disposition = '', $newname = null, $mime = '') $this->attachments[] = [ 'name' => $namesAttached, - 'disposition' => empty($disposition) ? 'attachment' : $disposition, + 'disposition' => $disposition === '' ? 'attachment' : $disposition, // Can also be 'inline' Not sure if it matters 'type' => $mime, 'content' => chunk_split(base64_encode($fileContent)), @@ -1488,7 +1488,7 @@ protected function prepQEncoding($str) */ public function send($autoClear = true) { - if (! isset($this->headers['From']) && ! empty($this->fromEmail)) { + if (! isset($this->headers['From']) && $this->fromEmail !== null && $this->fromEmail !== '') { $this->setFrom($this->fromEmail, $this->fromName); } @@ -1503,8 +1503,8 @@ public function send($autoClear = true) } if ( - empty($this->recipients) && ! isset($this->headers['To']) - && empty($this->BCCArray) && ! isset($this->headers['Bcc']) + $this->recipients === [] && ! isset($this->headers['To']) + && $this->BCCArray === [] && ! isset($this->headers['Bcc']) && ! isset($this->headers['Cc']) ) { $this->setErrorMessage(lang('Email.noRecipients')); @@ -2180,7 +2180,7 @@ protected function mimeTypes($ext = '') { $mime = Mimes::guessTypeFromExtension(strtolower($ext)); - return empty($mime) ? 'application/x-unknown-content-type' : $mime; + return $mime ?? 'application/x-unknown-content-type'; } public function __destruct() diff --git a/system/Encryption/Encryption.php b/system/Encryption/Encryption.php index 73ec458b837a..47a6ec649e1d 100644 --- a/system/Encryption/Encryption.php +++ b/system/Encryption/Encryption.php @@ -121,7 +121,7 @@ public function initialize(?EncryptionConfig $config = null) $this->digest = $config->digest; } - if (empty($this->driver)) { + if ($this->driver === null || $this->driver === '') { throw EncryptionException::forNoDriverRequested(); } @@ -129,7 +129,7 @@ public function initialize(?EncryptionConfig $config = null) throw EncryptionException::forUnKnownHandler($this->driver); } - if (empty($this->key)) { + if (in_array($this->key, [null, '', '0'], true)) { throw EncryptionException::forNeedsStarterKey(); } diff --git a/system/Encryption/Handlers/OpenSSLHandler.php b/system/Encryption/Handlers/OpenSSLHandler.php index 8e1be06d60ed..26c10a258536 100644 --- a/system/Encryption/Handlers/OpenSSLHandler.php +++ b/system/Encryption/Handlers/OpenSSLHandler.php @@ -87,7 +87,7 @@ public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $para ? (is_array($params) && isset($params['key']) ? $params['key'] : $params) : $this->key; - if (empty($key)) { + if (! is_string($key) || in_array($key, ['', '0'], true)) { throw EncryptionException::forNeedsStarterKey(); } @@ -123,7 +123,7 @@ public function decrypt($data, #[SensitiveParameter] $params = null) ? (is_array($params) && isset($params['key']) ? $params['key'] : $params) : $this->key; - if (empty($key)) { + if (! is_string($key) || in_array($key, ['', '0'], true)) { throw EncryptionException::forNeedsStarterKey(); } diff --git a/system/Encryption/Handlers/SodiumHandler.php b/system/Encryption/Handlers/SodiumHandler.php index 55bf14893251..c759bdbf518f 100644 --- a/system/Encryption/Handlers/SodiumHandler.php +++ b/system/Encryption/Handlers/SodiumHandler.php @@ -56,7 +56,7 @@ public function encrypt(#[SensitiveParameter] $data, #[SensitiveParameter] $para } } - if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { + if (! is_string($key) || strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { throw EncryptionException::forNeedsStarterKey(); } @@ -92,7 +92,7 @@ public function decrypt($data, #[SensitiveParameter] $params = null) } } - if (empty($key) || strlen((string) $key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { + if (! is_string($key) || strlen($key) !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) { throw EncryptionException::forNeedsStarterKey(); } diff --git a/system/Files/File.php b/system/Files/File.php index 83a304f26e99..8a06b29edb81 100644 --- a/system/Files/File.php +++ b/system/Files/File.php @@ -143,7 +143,7 @@ public function getMimeType(): string public function getRandomName(): string { $extension = $this->getExtension(); - $extension = empty($extension) ? '' : '.' . $extension; + $extension = $extension === '' ? '' : '.' . $extension; return Time::now()->getTimestamp() . '_' . bin2hex(random_bytes(10)) . $extension; } diff --git a/system/Filters/Filters.php b/system/Filters/Filters.php index bf5419eab560..38bd553249bb 100644 --- a/system/Filters/Filters.php +++ b/system/Filters/Filters.php @@ -254,7 +254,7 @@ private function runBefore(array $filterClassList) } // Ignore an empty result - if (empty($result)) { + if (! is_string($result) || $result === '') { continue; } diff --git a/system/HTTP/CURLRequest.php b/system/HTTP/CURLRequest.php index 76ded55c20a6..e1d9d3316b5e 100644 --- a/system/HTTP/CURLRequest.php +++ b/system/HTTP/CURLRequest.php @@ -371,11 +371,13 @@ public function send(string $method, string $url) // Reset our curl options so we're on a fresh slate. $curlOptions = []; - if (! empty($this->config['query']) && is_array($this->config['query'])) { + $query = $this->config['query'] ?? []; + + if (is_array($query) && $query !== []) { // This is likely too naive a solution. // Should look into handling when $url already // has query vars on it. - $url .= '?' . http_build_query($this->config['query']); + $url .= '?' . http_build_query($query); unset($this->config['query']); } @@ -431,7 +433,7 @@ public function send(string $method, string $url) */ protected function applyRequestHeaders(array $curlOptions = []): array { - if (empty($this->headers)) { + if ($this->headers === []) { return $curlOptions; } @@ -478,7 +480,7 @@ protected function applyMethod(string $method, array $curlOptions): array */ protected function applyBody(array $curlOptions = []): array { - if (! empty($this->body)) { + if (! in_array($this->body, [null, '', '0'], true)) { $curlOptions[CURLOPT_POSTFIELDS] = (string) $this->getBody(); } diff --git a/system/HTTP/IncomingRequest.php b/system/HTTP/IncomingRequest.php index c980810b9b2b..09f80d33253b 100644 --- a/system/HTTP/IncomingRequest.php +++ b/system/HTTP/IncomingRequest.php @@ -280,7 +280,14 @@ public function isSecure(): bool return true; } - return $this->hasHeader('Front-End-Https') && ! empty($this->header('Front-End-Https')->getValue()) && strtolower($this->header('Front-End-Https')->getValue()) !== 'off'; + if (! $this->hasHeader('Front-End-Https')) { + return false; + } + + $frontEndHttps = $this->header('Front-End-Https')->getValue(); + + return is_string($frontEndHttps) && ! in_array($frontEndHttps, ['', '0'], true) + && strtolower($frontEndHttps) !== 'off'; } /** diff --git a/system/HTTP/MessageTrait.php b/system/HTTP/MessageTrait.php index 044594bcfcdd..ffef1f07bc3d 100644 --- a/system/HTTP/MessageTrait.php +++ b/system/HTTP/MessageTrait.php @@ -82,7 +82,7 @@ public function appendBody($data): self public function populateHeaders(): void { $contentType = service('superglobals')->server('CONTENT_TYPE', (string) getenv('CONTENT_TYPE')); - if (! empty($contentType)) { + if ($contentType !== '') { $this->setHeader('Content-Type', $contentType); } unset($contentType); @@ -113,7 +113,7 @@ public function headers(): array // If no headers are defined, but the user is // requesting it, then it's likely they want // it to be populated so do that... - if (empty($this->headers)) { + if ($this->headers === []) { $this->populateHeaders(); } diff --git a/system/HTTP/Request.php b/system/HTTP/Request.php index 125646b6c7c7..63b5f0a8dbfd 100644 --- a/system/HTTP/Request.php +++ b/system/HTTP/Request.php @@ -33,11 +33,11 @@ public function __construct($config = null) { $this->config = $config ?? config(App::class); - if (empty($this->method)) { + if ($this->method === null || $this->method === '') { $this->method = $this->getServer('REQUEST_METHOD') ?? Method::GET; } - if (empty($this->uri)) { + if (! $this->uri instanceof URI) { $this->uri = new URI(); } } diff --git a/system/HTTP/RequestTrait.php b/system/HTTP/RequestTrait.php index 9011f4148eba..beb5b30570a3 100644 --- a/system/HTTP/RequestTrait.php +++ b/system/HTTP/RequestTrait.php @@ -72,7 +72,7 @@ public function getIPAddress(): string $proxyIPs = $this->config->proxyIPs; - if (! empty($proxyIPs) && (! is_array($proxyIPs) || is_int(array_key_first($proxyIPs)))) { + if ($proxyIPs !== [] && (! is_array($proxyIPs) || is_int(array_key_first($proxyIPs)))) { throw new ConfigException( 'You must set an array with Proxy IP address key and HTTP header name value in Config\App::$proxyIPs.', ); diff --git a/system/HTTP/Response.php b/system/HTTP/Response.php index 3c59f2e9800d..e1193c063945 100644 --- a/system/HTTP/Response.php +++ b/system/HTTP/Response.php @@ -197,7 +197,7 @@ public function pretend(bool $pretend = true) */ public function getStatusCode(): int { - if (empty($this->statusCode)) { + if ($this->statusCode === 0) { throw HTTPException::forMissingResponseStatus(); } @@ -221,7 +221,7 @@ public function getStatusCode(): int public function getReasonPhrase() { if ($this->reason === '') { - return empty($this->statusCode) ? '' : static::$statusCodes[$this->statusCode]; + return $this->statusCode === 0 ? '' : static::$statusCodes[$this->statusCode]; } return $this->reason; diff --git a/system/Helpers/form_helper.php b/system/Helpers/form_helper.php index 6fa4777e2454..a1f7defc4d14 100644 --- a/system/Helpers/form_helper.php +++ b/system/Helpers/form_helper.php @@ -637,7 +637,7 @@ function set_checkbox(string $field, string $value = '', bool $default = false): $hasOldInput = $session->has('_ci_old_input'); // Unchecked checkbox and radio inputs are not even submitted by browsers ... - if ((string) $input === '0' || ! empty($request->getPost()) || $hasOldInput) { + if ((string) $input === '0' || $request->getPost() !== [] || $hasOldInput) { return ($input === $value) ? ' checked="checked"' : ''; } diff --git a/system/Helpers/test_helper.php b/system/Helpers/test_helper.php index f86ca468b0cc..645d407dfcbf 100644 --- a/system/Helpers/test_helper.php +++ b/system/Helpers/test_helper.php @@ -57,13 +57,13 @@ function mock(string $className) $mockClass = $className::$mockClass; $mockService = $className::$mockServiceName ?? ''; - if (empty($mockClass) || ! class_exists($mockClass)) { + if ($mockClass === '' || ! class_exists($mockClass)) { throw TestException::forInvalidMockClass($mockClass); } $mock = new $mockClass(); - if (! empty($mockService)) { + if ($mockService !== '') { Services::injectMock($mockService, $mock); } diff --git a/system/Helpers/url_helper.php b/system/Helpers/url_helper.php index f8cb6b2540f9..208ae722a2f2 100644 --- a/system/Helpers/url_helper.php +++ b/system/Helpers/url_helper.php @@ -205,7 +205,7 @@ function anchor_popup($uri = '', string $title = '', $attributes = false, ?App $ // Ref: http://www.w3schools.com/jsref/met_win_open.asp $windowName = '_blank'; - } elseif (! empty($attributes['window_name'])) { + } elseif (($attributes['window_name'] ?? '') !== '') { $windowName = $attributes['window_name']; unset($attributes['window_name']); } else { diff --git a/system/Honeypot/Honeypot.php b/system/Honeypot/Honeypot.php index a816bdd1ed60..badf1d719b53 100644 --- a/system/Honeypot/Honeypot.php +++ b/system/Honeypot/Honeypot.php @@ -64,7 +64,7 @@ public function hasContent(RequestInterface $request) { assert($request instanceof IncomingRequest); - return ! empty($request->getPost($this->config->name)); + return ! in_array($request->getPost($this->config->name), [null, false, 0, 0.0, '', '0', []], true); } /** diff --git a/system/Images/Handlers/BaseHandler.php b/system/Images/Handlers/BaseHandler.php index 9301b1573c23..1ceebf7fe7a4 100644 --- a/system/Images/Handlers/BaseHandler.php +++ b/system/Images/Handlers/BaseHandler.php @@ -564,7 +564,7 @@ public function fit(int $width, ?int $height = null, string $position = 'center' */ protected function calcAspectRatio($width, $height = null, $origWidth = 0, $origHeight = 0): array { - if (empty($origWidth) || empty($origHeight)) { + if (in_array($origWidth, [0, 0.0], true) || in_array($origHeight, [0, 0.0], true)) { throw new InvalidArgumentException('You must supply the parameters: origWidth, origHeight.'); } diff --git a/system/Images/Image.php b/system/Images/Image.php index 0634405c6ec0..3e0b0ba6876d 100644 --- a/system/Images/Image.php +++ b/system/Images/Image.php @@ -75,7 +75,7 @@ public function copy(string $targetPath, ?string $targetName = null, int $perms $targetName ??= $this->getFilename(); - if (empty($targetName)) { + if ($targetName === null || $targetName === '') { throw ImageException::forInvalidFile($targetName); } diff --git a/system/Pager/Pager.php b/system/Pager/Pager.php index 66b1dd13d78f..1a01de3f1aa9 100644 --- a/system/Pager/Pager.php +++ b/system/Pager/Pager.php @@ -310,7 +310,7 @@ public function getNextPageURI(string $group = 'default', bool $returnObject = f $curr = $this->getCurrentPage($group); $page = null; - if (! empty($last) && $curr !== 0 && $last === $curr) { + if (! in_array($last, [null, 0], true) && $curr !== 0 && $last === $curr) { return null; } diff --git a/system/RESTful/BaseResource.php b/system/RESTful/BaseResource.php index f2e171c8319e..638f46becbbe 100644 --- a/system/RESTful/BaseResource.php +++ b/system/RESTful/BaseResource.php @@ -66,11 +66,11 @@ public function setModel($which = null) $this->modelName = is_object($which) ? null : $which; } - if (empty($this->model) && ! empty($this->modelName) && class_exists($this->modelName)) { + if ($this->model === null && $this->modelName !== null && class_exists($this->modelName)) { $this->model = model($this->modelName); } - if (! empty($this->model) && empty($this->modelName)) { + if ($this->model !== null && ($this->modelName === null || $this->modelName === '')) { $this->modelName = $this->model::class; } } diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 8253973beb27..6dfb42286972 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1017,7 +1017,7 @@ public function presenter(string $name, ?array $options = null): RouteCollection */ public function match(array $verbs = [], string $from = '', $to = '', ?array $options = null): RouteCollectionInterface { - if ($from === '' || empty($to)) { + if ($from === '' || in_array($to, ['', []], true)) { throw new InvalidArgumentException('You must supply the parameters: from, to.'); } @@ -1316,7 +1316,7 @@ protected function fillRouteParams(string $from, ?array $params = null): string // Find all of our back-references in the original route preg_match_all('/\(([^)]+)\)/', $from, $matches); - if (empty($matches[0])) { + if ($matches[0] === []) { return '/' . ltrim($from, '/'); } @@ -1355,7 +1355,7 @@ protected function buildReverseRoute(string $from, array $params): string // Find all of our back-references in the original route preg_match_all('/\(([^)]+)\)/', $from, $matches); - if (empty($matches[0])) { + if ($matches[0] === []) { if (str_contains($from, '{locale}')) { $locale = $params[0] ?? null; } @@ -1475,7 +1475,7 @@ protected function create(string $verb, string $from, $to, ?array $options = nul } // Hostname limiting? - if (! empty($options['hostname'])) { + if (! in_array($options['hostname'] ?? '', ['', '0', []], true)) { // @todo determine if there's a way to whitelist hosts? if (! $this->checkHostname($options['hostname'])) { return; @@ -1484,7 +1484,7 @@ protected function create(string $verb, string $from, $to, ?array $options = nul $overwrite = true; } // Limiting to subdomains? - elseif (! empty($options['subdomain'])) { + elseif (! in_array($options['subdomain'] ?? '', ['', '0', []], true)) { // If we don't match the current subdomain, then // we don't need to add the route. if (! $this->checkSubdomains($options['subdomain'])) { @@ -1646,7 +1646,7 @@ private function checkSubdomains($subdomains): bool // Routes can be limited to any sub-domain. In that case, though, // it does require a sub-domain to be present. - if (! empty($this->currentSubdomain) && in_array('*', $subdomains, true)) { + if (! in_array($this->currentSubdomain, [null, ''], true) && in_array('*', $subdomains, true)) { return true; } diff --git a/system/Router/Router.php b/system/Router/Router.php index 1eda4c616d62..cb53b439ea30 100644 --- a/system/Router/Router.php +++ b/system/Router/Router.php @@ -729,7 +729,7 @@ protected function setRequest(array $segments = []) */ protected function setDefaultController() { - if (empty($this->controller)) { + if (! is_string($this->controller) || $this->controller === '') { throw RouterException::forMissingDefaultRoute(); } diff --git a/system/Session/Handlers/RedisHandler.php b/system/Session/Handlers/RedisHandler.php index 54f628c4789b..d1c3c02e6fe4 100644 --- a/system/Session/Handlers/RedisHandler.php +++ b/system/Session/Handlers/RedisHandler.php @@ -174,7 +174,7 @@ protected function setSavePath(): void */ public function open($path, $name): bool { - if (empty($this->savePath)) { + if ($this->savePath === [] || $this->savePath === '') { return false; } diff --git a/system/Test/FeatureTestTrait.php b/system/Test/FeatureTestTrait.php index db298084e023..ce115761c117 100644 --- a/system/Test/FeatureTestTrait.php +++ b/system/Test/FeatureTestTrait.php @@ -366,10 +366,8 @@ protected function setupRequest(string $method, ?string $path = null): IncomingR */ protected function setupHeaders(IncomingRequest $request) { - if (! empty($this->headers)) { - foreach ($this->headers as $name => $value) { - $request->setHeader($name, $value); - } + foreach ($this->headers as $name => $value) { + $request->setHeader($name, $value); } return $request; diff --git a/system/Test/FilterTestTrait.php b/system/Test/FilterTestTrait.php index 1140adf7dc5e..59ffff646a79 100644 --- a/system/Test/FilterTestTrait.php +++ b/system/Test/FilterTestTrait.php @@ -178,7 +178,7 @@ protected function getFilterCaller($filter, string $position): Closure if ($result instanceof ResponseInterface) { return $result; } - if (empty($result)) { + if (! is_string($result) || $result === '') { continue; } } diff --git a/system/Validation/Rules.php b/system/Validation/Rules.php index 7617b283f099..31aa042c5d36 100644 --- a/system/Validation/Rules.php +++ b/system/Validation/Rules.php @@ -369,8 +369,8 @@ public function required_with($str = null, ?string $fields = null, array $data = foreach (explode(',', $fields) as $field) { if ( - (array_key_exists($field, $data) && ! empty($data[$field])) - || (str_contains($field, '.') && ! empty(dot_array_search($field, $data))) + (array_key_exists($field, $data) && ! $this->isBlank($data[$field])) + || (str_contains($field, '.') && ! $this->isBlank(dot_array_search($field, $data))) ) { $requiredFields[] = $field; } @@ -417,7 +417,7 @@ public function required_without( if ( (! str_contains($otherField, '.')) && (! array_key_exists($otherField, $data) - || empty($data[$otherField])) + || $this->isBlank($data[$otherField])) ) { return false; } @@ -432,7 +432,7 @@ public function required_without( $fieldKey = $fieldSplitArray[1] ?? null; if (is_array($fieldData)) { - if (empty($fieldData[$fieldKey])) { + if ($this->isBlank($fieldData[$fieldKey] ?? null)) { return false; } @@ -472,4 +472,15 @@ public function field_exists( return array_key_exists($field, $data); } + + /** + * Whether the value counts as blank for the `required_with` and + * `required_without` rules. + * + * @param mixed $value + */ + private function isBlank($value): bool + { + return in_array($value, [null, false, 0, 0.0, '', '0', []], true); + } } diff --git a/system/View/Filters.php b/system/View/Filters.php index c74e385cdb96..9e57976e575c 100644 --- a/system/View/Filters.php +++ b/system/View/Filters.php @@ -71,7 +71,7 @@ public static function date_modify($value, string $adjustment) */ public static function default($value, string $default): string { - return empty($value) ? $default : $value; + return in_array($value, [null, false, 0, 0.0, '', '0', []], true) ? $default : $value; } /** diff --git a/tests/system/Session/SessionTest.php b/tests/system/Session/SessionTest.php index 3b7cd3860ccd..e405325501d5 100644 --- a/tests/system/Session/SessionTest.php +++ b/tests/system/Session/SessionTest.php @@ -80,7 +80,8 @@ public function testSessionSetsRegenerateTime(): void $session = $this->getInstance(); $session->start(); - $this->assertTrue(isset($_SESSION['__ci_last_regenerate']) && ! empty($_SESSION['__ci_last_regenerate'])); + $this->assertArrayHasKey('__ci_last_regenerate', $_SESSION); + $this->assertGreaterThan(0, $_SESSION['__ci_last_regenerate']); } public function testWillRegenerateSessionAutomatically(): void diff --git a/utils/phpstan-baseline/empty.notAllowed.neon b/utils/phpstan-baseline/empty.notAllowed.neon deleted file mode 100644 index 9060c95a91ec..000000000000 --- a/utils/phpstan-baseline/empty.notAllowed.neon +++ /dev/null @@ -1,323 +0,0 @@ -# total 204 errors - -parameters: - ignoreErrors: - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Commands/Database/CreateDatabase.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Commands/Database/MigrateStatus.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Commands/Database/Seed.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Config/BaseService.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Config/DotEnv.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Config/Services.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 27 - path: ../../system/Database/BaseBuilder.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 13 - path: ../../system/Database/BaseConnection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/Database/BasePreparedQuery.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/BaseResult.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/Database/BaseUtils.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/Database.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 12 - path: ../../system/Database/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 4 - path: ../../system/Database/MigrationRunner.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 10 - path: ../../system/Database/MySQLi/Connection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 4 - path: ../../system/Database/MySQLi/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Database/MySQLi/Result.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/Database/OCI8/Builder.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/OCI8/Connection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/Database/OCI8/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 7 - path: ../../system/Database/Postgre/Builder.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/Postgre/Connection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 4 - path: ../../system/Database/Postgre/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Database/Postgre/Result.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/Database/Query.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 9 - path: ../../system/Database/SQLSRV/Builder.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 6 - path: ../../system/Database/SQLSRV/Connection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 5 - path: ../../system/Database/SQLSRV/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Database/SQLSRV/Result.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/SQLite3/Builder.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Database/SQLite3/Connection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/SQLite3/Forge.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Database/SQLite3/Table.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 5 - path: ../../system/Debug/Timer.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Debug/Toolbar.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 5 - path: ../../system/Email/Email.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Encryption/Encryption.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Encryption/Handlers/OpenSSLHandler.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Encryption/Handlers/SodiumHandler.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Files/File.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Filters/Filters.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/HTTP/CURLRequest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/HTTP/IncomingRequest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/HTTP/Message.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 3 - path: ../../system/HTTP/Request.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/HTTP/Response.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Helpers/form_helper.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Helpers/test_helper.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Helpers/url_helper.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Honeypot/Honeypot.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 2 - path: ../../system/Images/Handlers/BaseHandler.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Images/Image.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Pager/Pager.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 4 - path: ../../system/RESTful/BaseResource.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 6 - path: ../../system/Router/RouteCollection.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Router/Router.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/Session/Handlers/RedisHandler.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 4 - path: ../../system/Validation/Rules.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../system/View/Filters.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../tests/system/HomeTest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../tests/system/Session/SessionTest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../tests/system/Test/FeatureTestAutoRoutingImprovedTest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../tests/system/Test/FeatureTestTraitTest.php - - - - message: '#^Construct empty\(\) is not allowed\. Use more strict comparison\.$#' - count: 1 - path: ../../tests/system/Test/FilterTestTraitTest.php diff --git a/utils/phpstan-baseline/loader.neon b/utils/phpstan-baseline/loader.neon index 32ad4dacc2f5..588d3cec14bd 100644 --- a/utils/phpstan-baseline/loader.neon +++ b/utils/phpstan-baseline/loader.neon @@ -1,4 +1,4 @@ -# total 1808 errors +# total 1604 errors includes: - argument.type.neon @@ -6,7 +6,6 @@ includes: - assign.propertyType.neon - codeigniter.modelArgumentType.neon - deadCode.unreachable.neon - - empty.notAllowed.neon - function.resultUnused.neon - method.alreadyNarrowedType.neon - method.childParameterType.neon